]> CyberLeo.Net >> Repos - FreeBSD/FreeBSD.git/blob - sbin/bectl/bectl.c
bectl(8): Take -H parameter to list into account
[FreeBSD/FreeBSD.git] / sbin / bectl / bectl.c
1 /*
2  * be.c
3  *
4  * Copyright (c) 2017 Kyle J. Kneitinger <kyle@kneit.in>
5  * 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  *
16  * THIS SOFTWARE IS PROVIDED BY THE REGENTS AND CONTRIBUTORS ``AS IS'' AND
17  * ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
18  * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE
19  * ARE DISCLAIMED.  IN NO EVENT SHALL THE REGENTS OR CONTRIBUTORS BE LIABLE
20  * FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL
21  * DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS
22  * OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION)
23  * HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT
24  * LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY
25  * OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF
26  * SUCH DAMAGE.
27  */
28
29 #include <sys/param.h>
30 #include <sys/jail.h>
31 #include <sys/mount.h>
32 #include <errno.h>
33 #include <jail.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 #define HEADER_BE       "BE"
47 #define HEADER_BEPLUS   "BE/Dataset/Snapshot"
48 #define HEADER_ACTIVE   "Active"
49 #define HEADER_MOUNT    "Mountpoint"
50 #define HEADER_SPACE    "Space"
51 #define HEADER_CREATED  "Created"
52
53 /* Spaces */
54 #define INDENT_INCREMENT        2
55
56 struct printc {
57         int     active_colsz_def;
58         int     be_colsz;
59         int     current_indent;
60         int     mount_colsz;
61         int     space_colsz;
62         bool    script_fmt;
63         bool    show_all_datasets;
64         bool    show_snaps;
65         bool    show_space;
66 };
67
68 static int bectl_cmd_activate(int argc, char *argv[]);
69 static int bectl_cmd_create(int argc, char *argv[]);
70 static int bectl_cmd_destroy(int argc, char *argv[]);
71 static int bectl_cmd_export(int argc, char *argv[]);
72 static int bectl_cmd_import(int argc, char *argv[]);
73 static int bectl_cmd_add(int argc, char *argv[]);
74 static int bectl_cmd_jail(int argc, char *argv[]);
75 static const char *get_origin_props(nvlist_t *dsprops, nvlist_t **originprops);
76 static void print_padding(const char *fval, int colsz, struct printc *pc);
77 static void print_info(const char *name, nvlist_t *dsprops, struct printc *pc);
78 static void print_headers(nvlist_t *props, struct printc *pc);
79 static int bectl_cmd_list(int argc, char *argv[]);
80 static int bectl_cmd_mount(int argc, char *argv[]);
81 static int bectl_cmd_rename(int argc, char *argv[]);
82 static int bectl_search_jail_paths(const char *mnt);
83 static int bectl_locate_jail(const char *ident);
84 static int bectl_cmd_unjail(int argc, char *argv[]);
85 static int bectl_cmd_unmount(int argc, char *argv[]);
86
87 static libbe_handle_t *be;
88
89 static int
90 usage(bool explicit)
91 {
92         FILE *fp;
93
94         fp =  explicit ? stdout : stderr;
95         fprintf(fp,
96             "usage:\tbectl ( -h | -? | subcommand [args...] )\n"
97             "\tbectl activate [-t] beName\n"
98             "\tbectl create [-e nonActiveBe | -e beName@snapshot] beName\n"
99             "\tbectl create beName@snapshot\n"
100             "\tbectl destroy [-F] beName | beName@snapshot⟩\n"
101             "\tbectl export sourceBe\n"
102             "\tbectl import targetBe\n"
103             "\tbectl add (path)*\n"
104             "\tbectl jail bootenv\n"
105             "\tbectl list [-a] [-D] [-H] [-s]\n"
106             "\tbectl mount beName [mountpoint]\n"
107             "\tbectl rename origBeName newBeName\n"
108             "\tbectl { ujail | unjail } ⟨jailID | jailName | bootenv)\n"
109             "\tbectl { umount | unmount } [-f] beName\n");
110
111         return (explicit ? 0 : EX_USAGE);
112 }
113
114
115 /*
116  * Represents a relationship between the command name and the parser action
117  * that handles it.
118  */
119 struct command_map_entry {
120         const char *command;
121         int (*fn)(int argc, char *argv[]);
122 };
123
124 static struct command_map_entry command_map[] =
125 {
126         { "activate", bectl_cmd_activate },
127         { "create",   bectl_cmd_create   },
128         { "destroy",  bectl_cmd_destroy  },
129         { "export",   bectl_cmd_export   },
130         { "import",   bectl_cmd_import   },
131         { "add",      bectl_cmd_add      },
132         { "jail",     bectl_cmd_jail     },
133         { "list",     bectl_cmd_list     },
134         { "mount",    bectl_cmd_mount    },
135         { "rename",   bectl_cmd_rename   },
136         { "unjail",   bectl_cmd_unjail   },
137         { "unmount",  bectl_cmd_unmount  },
138 };
139
140 static int
141 get_cmd_index(const char *cmd, int *index)
142 {
143         int map_size;
144
145         map_size = nitems(command_map);
146         for (int i = 0; i < map_size; ++i) {
147                 if (strcmp(cmd, command_map[i].command) == 0) {
148                         *index = i;
149                         return (0);
150                 }
151         }
152
153         return (1);
154 }
155
156
157 static int
158 bectl_cmd_activate(int argc, char *argv[])
159 {
160         int err, opt;
161         bool temp;
162
163         temp = false;
164         while ((opt = getopt(argc, argv, "t")) != -1) {
165                 switch (opt) {
166                 case 't':
167                         temp = true;
168                         break;
169                 default:
170                         fprintf(stderr, "bectl activate: unknown option '-%c'\n",
171                             optopt);
172                         return (usage(false));
173                 }
174         }
175
176         argc -= optind;
177         argv += optind;
178
179         if (argc != 1) {
180                 fprintf(stderr, "bectl activate: wrong number of arguments\n");
181                 return (usage(false));
182         }
183
184
185         /* activate logic goes here */
186         if ((err = be_activate(be, argv[0], temp)) != 0)
187                 /* XXX TODO: more specific error msg based on err */
188                 printf("did not successfully activate boot environment %s\n",
189                     argv[0]);
190         else
191                 printf("successfully activated boot environment %s\n", argv[0]);
192
193         if (temp)
194                 printf("for next boot\n");
195
196         return (err);
197 }
198
199
200 /*
201  * TODO: when only one arg is given, and it contains an "@" the this should
202  * create that snapshot
203  */
204 static int
205 bectl_cmd_create(int argc, char *argv[])
206 {
207         char *bootenv, *snapname, *source;
208         int err, opt;
209
210         snapname = NULL;
211         while ((opt = getopt(argc, argv, "e:")) != -1) {
212                 switch (opt) {
213                 case 'e':
214                         snapname = optarg;
215                         break;
216                 default:
217                         fprintf(stderr, "bectl create: unknown option '-%c'\n",
218                             optopt);
219                         return (usage(false));
220                 }
221         }
222
223         argc -= optind;
224         argv += optind;
225
226         if (argc != 1) {
227                 fprintf(stderr, "bectl create: wrong number of arguments\n");
228                 return (usage(false));
229         }
230
231         bootenv = *argv;
232
233         if (snapname != NULL) {
234                 if (strchr(snapname, '@') != NULL)
235                         err = be_create_from_existing_snap(be, bootenv,
236                             snapname);
237                 else
238                         err = be_create_from_existing(be, bootenv, snapname);
239         } else {
240                 if ((snapname = strchr(bootenv, '@')) != NULL) {
241                         *(snapname++) = '\0';
242                         if ((err = be_snapshot(be, be_active_path(be),
243                             snapname, true, NULL)) != BE_ERR_SUCCESS)
244                                 fprintf(stderr, "failed to create snapshot\n");
245                         asprintf(&source, "%s@%s", be_active_path(be), snapname);
246                         err = be_create_from_existing_snap(be, bootenv,
247                             source);
248                         return (err);
249                 } else
250                         err = be_create(be, bootenv);
251         }
252
253         switch (err) {
254         case BE_ERR_SUCCESS:
255                 break;
256         default:
257                 if (snapname == NULL)
258                         fprintf(stderr,
259                             "failed to create bootenv %s\n", bootenv);
260                 else
261                         fprintf(stderr,
262                             "failed to create bootenv %s from snapshot %s\n",
263                             bootenv, snapname);
264         }
265
266         return (err);
267 }
268
269
270 static int
271 bectl_cmd_export(int argc, char *argv[])
272 {
273         char *bootenv;
274
275         if (argc == 1) {
276                 fprintf(stderr, "bectl export: missing boot environment name\n");
277                 return (usage(false));
278         }
279
280         if (argc > 2) {
281                 fprintf(stderr, "bectl export: extra arguments provided\n");
282                 return (usage(false));
283         }
284
285         bootenv = argv[1];
286
287         if (isatty(STDOUT_FILENO)) {
288                 fprintf(stderr, "bectl export: must redirect output\n");
289                 return (EX_USAGE);
290         }
291
292         be_export(be, bootenv, STDOUT_FILENO);
293
294         return (0);
295 }
296
297
298 static int
299 bectl_cmd_import(int argc, char *argv[])
300 {
301         char *bootenv;
302         int err;
303
304         if (argc == 1) {
305                 fprintf(stderr, "bectl import: missing boot environment name\n");
306                 return (usage(false));
307         }
308
309         if (argc > 2) {
310                 fprintf(stderr, "bectl import: extra arguments provided\n");
311                 return (usage(false));
312         }
313
314         bootenv = argv[1];
315
316         if (isatty(STDIN_FILENO)) {
317                 fprintf(stderr, "bectl import: input can not be from terminal\n");
318                 return (EX_USAGE);
319         }
320
321         err = be_import(be, bootenv, STDIN_FILENO);
322
323         return (err);
324 }
325
326
327 static int
328 bectl_cmd_add(int argc, char *argv[])
329 {
330
331         if (argc < 2) {
332                 fprintf(stderr, "bectl add: must provide at least one path\n");
333                 return (usage(false));
334         }
335
336         for (int i = 1; i < argc; ++i) {
337                 printf("arg %d: %s\n", i, argv[i]);
338                 /* XXX TODO catch err */
339                 be_add_child(be, argv[i], true);
340         }
341
342         return (0);
343 }
344
345
346 static int
347 bectl_cmd_destroy(int argc, char *argv[])
348 {
349         char *target;
350         int opt, err;
351         bool force;
352
353         force = false;
354         while ((opt = getopt(argc, argv, "F")) != -1) {
355                 switch (opt) {
356                 case 'F':
357                         force = true;
358                         break;
359                 default:
360                         fprintf(stderr, "bectl destroy: unknown option '-%c'\n",
361                             optopt);
362                         return (usage(false));
363                 }
364         }
365
366         argc -= optind;
367         argv += optind;
368
369         if (argc != 1) {
370                 fprintf(stderr, "bectl destroy: wrong number of arguments\n");
371                 return (usage(false));
372         }
373
374         target = argv[0];
375
376         err = be_destroy(be, target, force);
377
378         return (err);
379 }
380
381
382 static int
383 bectl_cmd_jail(int argc, char *argv[])
384 {
385         char *bootenv;
386         char mnt_loc[BE_MAXPATHLEN];
387         int err, jid;
388
389         /* struct jail be_jail = { 0 }; */
390
391         if (argc == 1) {
392                 fprintf(stderr, "bectl jail: missing boot environment name\n");
393                 return (usage(false));
394         }
395         if (argc > 2) {
396                 fprintf(stderr, "bectl jail: too many arguments\n");
397                 return (usage(false));
398         }
399
400         bootenv = argv[1];
401
402         /*
403          * XXX TODO: if its already mounted, perhaps there should be a flag to
404          * indicate its okay to proceed??
405          */
406         if ((err = be_mount(be, bootenv, NULL, 0, mnt_loc)) != BE_ERR_SUCCESS) {
407                 fprintf(stderr, "could not mount bootenv\n");
408                 return (1);
409         }
410
411         /* XXX TODO: Make the IP/hostname configurable? */
412         jid = jail_setv(JAIL_CREATE | JAIL_ATTACH,
413             "name", bootenv,
414             "path", mnt_loc,
415             "host.hostname", bootenv,
416             "persist", "true",
417             "ip4.addr", "10.20.30.40",
418             "allow.mount", "true",
419             "allow.mount.devfs", "true",
420             "enforce_statfs", "1",
421             NULL);
422         if (jid == -1) {
423                 fprintf(stderr, "unable to create jail.  error: %d\n", errno);
424                 return (1);
425         }
426
427         /* We're attached within the jail... good bye! */
428         chdir("/");
429         execl("/bin/sh", "/bin/sh", NULL);
430         return (0);
431 }
432
433 /*
434  * Given a set of dataset properties (for a BE dataset), populate originprops
435  * with the origin's properties.
436  */
437 static const char *
438 get_origin_props(nvlist_t *dsprops, nvlist_t **originprops)
439 {
440         char *propstr;
441
442         if (nvlist_lookup_string(dsprops, "origin", &propstr) == 0) {
443                 if (be_prop_list_alloc(originprops) != 0) {
444                         fprintf(stderr,
445                             "bectl list: failed to allocate origin prop nvlist\n");
446                         return (NULL);
447                 }
448                 if (be_get_snapshot_props(be, propstr, *originprops) != 0) {
449                         /* XXX TODO: Real errors */
450                         fprintf(stderr,
451                             "bectl list: failed to fetch origin properties\n");
452                         return (NULL);
453                 }
454
455                 return (propstr);
456         }
457         return (NULL);
458 }
459
460 static void
461 print_padding(const char *fval, int colsz, struct printc *pc)
462 {
463
464         if (pc->script_fmt) {
465                 printf("\t");
466                 return;
467         }
468
469         if (fval != NULL)
470                 colsz -= strlen(fval);
471         printf("%*s ", colsz, "");
472 }
473
474 static void
475 print_info(const char *name, nvlist_t *dsprops, struct printc *pc)
476 {
477 #define BUFSZ   64
478         char buf[BUFSZ];
479         unsigned long long ctimenum, space;
480         nvlist_t *originprops;
481         const char *oname;
482         char *propstr;
483         int active_colsz;
484         boolean_t active_now, active_reboot;
485
486         originprops = NULL;
487         printf("%*s%s", pc->current_indent, "", name);
488
489         /* Recurse at the base level if we're breaking info down */
490         if (pc->current_indent == 0 && (pc->show_all_datasets ||
491             pc->show_snaps)) {
492                 printf("\n");
493                 if (nvlist_lookup_string(dsprops, "dataset", &propstr) != 0)
494                         /* XXX TODO: Error? */
495                         return;
496                 pc->current_indent += INDENT_INCREMENT;
497                 print_info(propstr, dsprops, pc);
498                 pc->current_indent += INDENT_INCREMENT;
499                 if ((oname = get_origin_props(dsprops, &originprops)) != NULL) {
500                         print_info(oname, originprops, pc);
501                         nvlist_free(originprops);
502                 }
503                 pc->current_indent = 0;
504                 return;
505         } else
506                 print_padding(name, pc->be_colsz - pc->current_indent, pc);
507
508         active_colsz = pc->active_colsz_def;
509         if (nvlist_lookup_boolean_value(dsprops, "active",
510             &active_now) == 0 && active_now) {
511                 printf("N");
512                 active_colsz--;
513         }
514         if (nvlist_lookup_boolean_value(dsprops, "nextboot",
515             &active_reboot) == 0 && active_reboot) {
516                 printf("R");
517                 active_colsz--;
518         }
519         if (active_colsz == pc->active_colsz_def) {
520                 printf("-");
521                 active_colsz--;
522         }
523         print_padding(NULL, active_colsz, pc);
524         if (nvlist_lookup_string(dsprops, "mountpoint", &propstr) == 0){
525                 printf("%s", propstr);
526                 print_padding(propstr, pc->mount_colsz, pc);
527         } else {
528                 printf("%s", "-");
529                 print_padding("-", pc->mount_colsz, pc);
530         }
531
532         get_origin_props(dsprops, &originprops);
533
534         if (nvlist_lookup_string(dsprops, "used", &propstr) == 0) {
535                 space = strtoull(propstr, NULL, 10);
536
537                 if (!pc->show_all_datasets && originprops != NULL &&
538                     nvlist_lookup_string(originprops, "used", &propstr) == 0)
539                         space += strtoull(propstr, NULL, 10);
540
541                 /* Alas, there's more to it,. */
542                 humanize_number(buf, 6, space, "", HN_AUTOSCALE,
543                         HN_DECIMAL | HN_NOSPACE | HN_B);
544                 printf("%s", buf);
545                 print_padding(buf, pc->space_colsz, pc);
546         } else {
547                 printf("%s", "-");
548                 print_padding("-", pc->space_colsz, pc);
549         }
550
551         if (nvlist_lookup_string(dsprops, "creation", &propstr) == 0) {
552                 ctimenum = strtoull(propstr, NULL, 10);
553                 strftime(buf, BUFSZ, "%Y-%m-%d %H:%M",
554                     localtime((time_t *)&ctimenum));
555                 printf("%s", buf);
556         }
557
558         printf("\n");
559         if (originprops != NULL) {
560                 /*if (pc->show_all_datasets) {
561                 }*/
562                 be_prop_list_free(originprops);
563         }
564 #undef BUFSZ
565 }
566
567 static void
568 print_headers(nvlist_t *props, struct printc *pc)
569 {
570         const char *chosen_be_header;
571         nvpair_t *cur;
572         nvlist_t *dsprops;
573         char *propstr;
574         size_t be_maxcol;
575
576         if (pc->show_all_datasets || pc->show_snaps)
577                 chosen_be_header = HEADER_BEPLUS;
578         else
579                 chosen_be_header = HEADER_BE;
580         be_maxcol = strlen(chosen_be_header);
581         for (cur = nvlist_next_nvpair(props, NULL); cur != NULL;
582             cur = nvlist_next_nvpair(props, cur)) {
583                 be_maxcol = MAX(be_maxcol, strlen(nvpair_name(cur)));
584                 if (!pc->show_all_datasets && !pc->show_snaps)
585                         continue;
586                 nvpair_value_nvlist(cur, &dsprops);
587                 if (nvlist_lookup_string(dsprops, "dataset", &propstr) != 0)
588                         continue;
589                 be_maxcol = MAX(be_maxcol, strlen(propstr) + INDENT_INCREMENT);
590                 if (nvlist_lookup_string(dsprops, "origin", &propstr) != 0)
591                         continue;
592                 be_maxcol = MAX(be_maxcol,
593                     strlen(propstr) + INDENT_INCREMENT * 2);
594         }
595
596         pc->be_colsz = be_maxcol;
597         pc->active_colsz_def = strlen(HEADER_ACTIVE);
598         pc->mount_colsz = strlen(HEADER_MOUNT);
599         pc->space_colsz = strlen(HEADER_SPACE);
600         printf("%*s %s %s %s %s\n", -pc->be_colsz, chosen_be_header,
601             HEADER_ACTIVE, HEADER_MOUNT, HEADER_SPACE, HEADER_CREATED);
602
603         /*
604          * All other invocations in which we aren't using the default header
605          * will produce quite a bit of input.  Throw an extra blank line after
606          * the header to make it look nicer.
607          */
608         if (chosen_be_header != HEADER_BE)
609                 printf("\n");
610 }
611
612 static int
613 bectl_cmd_list(int argc, char *argv[])
614 {
615         struct printc pc;
616         nvpair_t *cur;
617         nvlist_t *dsprops, *props;
618         int opt, printed;
619         boolean_t active_now, active_reboot;
620
621         props = NULL;
622         printed = 0;
623         bzero(&pc, sizeof(pc));
624         while ((opt = getopt(argc, argv, "aDHs")) != -1) {
625                 switch (opt) {
626                 case 'a':
627                         pc.show_all_datasets = true;
628                         break;
629                 case 'D':
630                         pc.show_space = true;
631                         break;
632                 case 'H':
633                         pc.script_fmt = true;
634                         break;
635                 case 's':
636                         pc.show_snaps = true;
637                         break;
638                 default:
639                         fprintf(stderr, "bectl list: unknown option '-%c'\n",
640                             optopt);
641                         return (usage(false));
642                 }
643         }
644
645         argc -= optind;
646
647         if (argc != 0) {
648                 fprintf(stderr, "bectl list: extra argument provided\n");
649                 return (usage(false));
650         }
651
652         if (be_prop_list_alloc(&props) != 0) {
653                 fprintf(stderr, "bectl list: failed to allocate prop nvlist\n");
654                 return (1);
655         }
656         if (be_get_bootenv_props(be, props) != 0) {
657                 /* XXX TODO: Real errors */
658                 fprintf(stderr, "bectl list: failed to fetch boot environments\n");
659                 return (1);
660         }
661
662         if (!pc.script_fmt)
663                 print_headers(props, &pc);
664         /* Do a first pass to print active and next active first */
665         for (cur = nvlist_next_nvpair(props, NULL); cur != NULL;
666             cur = nvlist_next_nvpair(props, cur)) {
667                 nvpair_value_nvlist(cur, &dsprops);
668                 active_now = active_reboot = false;
669
670                 nvlist_lookup_boolean_value(dsprops, "active", &active_now);
671                 nvlist_lookup_boolean_value(dsprops, "nextboot",
672                     &active_reboot);
673                 if (!active_now && !active_reboot)
674                         continue;
675                 if (printed > 0 && (pc.show_all_datasets || pc.show_snaps))
676                         printf("\n");
677                 print_info(nvpair_name(cur), dsprops, &pc);
678                 printed++;
679         }
680
681         /* Now pull everything else */
682         for (cur = nvlist_next_nvpair(props, NULL); cur != NULL;
683             cur = nvlist_next_nvpair(props, cur)) {
684                 nvpair_value_nvlist(cur, &dsprops);
685                 active_now = active_reboot = false;
686
687                 nvlist_lookup_boolean_value(dsprops, "active", &active_now);
688                 nvlist_lookup_boolean_value(dsprops, "nextboot",
689                     &active_reboot);
690                 if (active_now || active_reboot)
691                         continue;
692                 if (printed > 0 && (pc.show_all_datasets || pc.show_snaps))
693                         printf("\n");
694                 print_info(nvpair_name(cur), dsprops, &pc);
695                 printed++;
696         }
697         be_prop_list_free(props);
698
699         return (0);
700 }
701
702
703 static int
704 bectl_cmd_mount(int argc, char *argv[])
705 {
706         char result_loc[BE_MAXPATHLEN];
707         char *bootenv, *mountpoint;
708         int err;
709
710         if (argc < 2) {
711                 fprintf(stderr, "bectl mount: missing argument(s)\n");
712                 return (usage(false));
713         }
714
715         if (argc > 3) {
716                 fprintf(stderr, "bectl mount: too many arguments\n");
717                 return (usage(false));
718         }
719
720         bootenv = argv[1];
721         mountpoint = ((argc == 3) ? argv[2] : NULL);
722
723         err = be_mount(be, bootenv, mountpoint, 0, result_loc);
724
725         switch (err) {
726         case BE_ERR_SUCCESS:
727                 printf("successfully mounted %s at %s\n", bootenv, result_loc);
728                 break;
729         default:
730                 fprintf(stderr,
731                     (argc == 3) ? "failed to mount bootenv %s at %s\n" :
732                     "failed to mount bootenv %s at temporary path %s\n",
733                     bootenv, mountpoint);
734         }
735
736         return (err);
737 }
738
739
740 static int
741 bectl_cmd_rename(int argc, char *argv[])
742 {
743         char *dest, *src;
744         int err;
745
746         if (argc < 3) {
747                 fprintf(stderr, "bectl rename: missing argument\n");
748                 return (usage(false));
749         }
750
751         if (argc > 3) {
752                 fprintf(stderr, "bectl rename: too many arguments\n");
753                 return (usage(false));
754         }
755
756         src = argv[1];
757         dest = argv[2];
758
759         err = be_rename(be, src, dest);
760
761         switch (err) {
762         case BE_ERR_SUCCESS:
763                 break;
764         default:
765                 fprintf(stderr, "failed to rename bootenv %s to %s\n",
766                     src, dest);
767         }
768
769         return (0);
770 }
771
772 static int
773 bectl_search_jail_paths(const char *mnt)
774 {
775         char jailpath[MAXPATHLEN + 1];
776         int jid;
777
778         jid = 0;
779         (void)mnt;
780         while ((jid = jail_getv(0, "lastjid", &jid, "path", &jailpath,
781             NULL)) != -1) {
782                 if (strcmp(jailpath, mnt) == 0)
783                         return (jid);
784         }
785
786         return (-1);
787 }
788
789 /*
790  * Locate a jail based on an arbitrary identifier.  This may be either a name,
791  * a jid, or a BE name.  Returns the jid or -1 on failure.
792  */
793 static int
794 bectl_locate_jail(const char *ident)
795 {
796         nvlist_t *belist, *props;
797         char *mnt;
798         int jid;
799
800         /* Try the easy-match first */
801         jid = jail_getid(ident);
802         if (jid != -1)
803                 return (jid);
804
805         /* Attempt to try it as a BE name, first */
806         if (be_prop_list_alloc(&belist) != 0)
807                 return (-1);
808
809         if (be_get_bootenv_props(be, belist) != 0)
810                 return (-1);
811
812         if (nvlist_lookup_nvlist(belist, ident, &props) == 0) {
813                 /* We'll attempt to resolve the jid by way of mountpoint */
814                 if (nvlist_lookup_string(props, "mountpoint", &mnt) == 0) {
815                         jid = bectl_search_jail_paths(mnt);
816                         be_prop_list_free(belist);
817                         return (jid);
818                 }
819
820                 be_prop_list_free(belist);
821         }
822
823         return (-1);
824 }
825
826 static int
827 bectl_cmd_unjail(int argc, char *argv[])
828 {
829         char path[MAXPATHLEN + 1];
830         char *cmd, *name, *target;
831         int jid;
832
833         /* Store alias used */
834         cmd = argv[0];
835
836         if (argc != 2) {
837                 fprintf(stderr, "bectl %s: wrong number of arguments\n", cmd);
838                 return (usage(false));
839         }
840
841         target = argv[1];
842
843         /* Locate the jail */
844         if ((jid = bectl_locate_jail(target)) == -1) {
845                 fprintf(stderr, "bectl %s: failed to locate BE by '%s'\n", cmd, target);
846                 return (1);
847         }
848
849         bzero(&path, MAXPATHLEN + 1);
850         name = jail_getname(jid);
851         if (jail_getv(0, "name", name, "path", path, NULL) != jid) {
852                 free(name);
853                 fprintf(stderr, "bectl %s: failed to get path for jail requested by '%s'\n", cmd, target);
854                 return (1);
855         }
856
857         free(name);
858
859         if (be_mounted_at(be, path, NULL) != 0) {
860                 fprintf(stderr, "bectl %s: jail requested by '%s' not a BE\n", cmd, target);
861                 return (1);
862         }
863
864         jail_remove(jid);
865         unmount(path, 0);
866
867         return (0);
868 }
869
870
871 static int
872 bectl_cmd_unmount(int argc, char *argv[])
873 {
874         char *bootenv, *cmd;
875         int err, flags, opt;
876
877         /* Store alias used */
878         cmd = argv[0];
879
880         flags = 0;
881         while ((opt = getopt(argc, argv, "f")) != -1) {
882                 switch (opt) {
883                 case 'f':
884                         flags |= BE_MNT_FORCE;
885                         break;
886                 default:
887                         fprintf(stderr, "bectl %s: unknown option '-%c'\n",
888                             cmd, optopt);
889                         return (usage(false));
890                 }
891         }
892
893         argc -= optind;
894         argv += optind;
895
896         if (argc != 1) {
897                 fprintf(stderr, "bectl %s: wrong number of arguments\n", cmd);
898                 return (usage(false));
899         }
900
901         bootenv = argv[0];
902
903         err = be_unmount(be, bootenv, flags);
904
905         switch (err) {
906         case BE_ERR_SUCCESS:
907                 break;
908         default:
909                 fprintf(stderr, "failed to unmount bootenv %s\n", bootenv);
910         }
911
912         return (err);
913 }
914
915
916 int
917 main(int argc, char *argv[])
918 {
919         const char *command;
920         int command_index, rc;
921
922         if (argc < 2) {
923                 fprintf(stderr, "missing command\n");
924                 return (usage(false));
925         }
926
927         command = argv[1];
928
929         /* Handle command aliases */
930         if (strcmp(command, "umount") == 0)
931                 command = "unmount";
932
933         if (strcmp(command, "ujail") == 0)
934                 command = "unjail";
935
936         if ((strcmp(command, "-?") == 0) || (strcmp(command, "-h") == 0))
937                 return (usage(true));
938
939         if (get_cmd_index(command, &command_index)) {
940                 fprintf(stderr, "unknown command: %s\n", command);
941                 return (usage(false));
942         }
943
944
945         if ((be = libbe_init()) == NULL)
946                 return (-1);
947
948         libbe_print_on_error(be, true);
949
950         /* XXX TODO: can be simplified if offset by 2 instead of one */
951         rc = command_map[command_index].fn(argc-1, argv+1);
952
953         libbe_close(be);
954         return (rc);
955 }