1/*-
2 * SPDX-License-Identifier: BSD-2-Clause
3 *
4 * Copyright (c) 2018 Kyle Evans <kevans@FreeBSD.org>
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 AUTHOR ``AS IS'' AND ANY EXPRESS OR
16 * IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES
17 * OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE DISCLAIMED.
18 * IN NO EVENT SHALL THE AUTHOR BE LIABLE FOR ANY DIRECT, INDIRECT,
19 * INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING,
20 * BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES;
21 * LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED
22 * AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY,
23 * 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/param.h>
29#include <stdbool.h>
30#include <stdio.h>
31#include <string.h>
32#include <unistd.h>
33
34#include <be.h>
35
36#include "bectl.h"
37
38struct sort_column {
39	const char *name;
40	const char *val;
41	nvlist_t *nvl;
42};
43
44struct printc {
45	int	active_colsz_def;
46	int	be_colsz;
47	int	current_indent;
48	int	mount_colsz;
49	int	space_colsz;
50	bool	script_fmt;
51	bool	show_all_datasets;
52	bool	show_snaps;
53	bool	show_space;
54};
55
56static const char *get_origin_props(nvlist_t *dsprops, nvlist_t **originprops);
57static void print_padding(const char *fval, int colsz, struct printc *pc);
58static int print_snapshots(const char *dsname, struct printc *pc);
59static void print_info(const char *name, nvlist_t *dsprops, struct printc *pc);
60static void print_headers(nvlist_t *props, struct printc *pc);
61static unsigned long long dataset_space(const char *oname);
62
63#define	HEADER_BE	"BE"
64#define	HEADER_BEPLUS	"BE/Dataset/Snapshot"
65#define	HEADER_ACTIVE	"Active"
66#define	HEADER_MOUNT	"Mountpoint"
67#define	HEADER_SPACE	"Space"
68#define	HEADER_CREATED	"Created"
69
70/* Spaces */
71#define	INDENT_INCREMENT	2
72
73/*
74 * Given a set of dataset properties (for a BE dataset), populate originprops
75 * with the origin's properties.
76 */
77static const char *
78get_origin_props(nvlist_t *dsprops, nvlist_t **originprops)
79{
80	const char *propstr;
81
82	if (nvlist_lookup_string(dsprops, "origin", &propstr) == 0) {
83		if (be_prop_list_alloc(originprops) != 0) {
84			fprintf(stderr,
85			    "bectl list: failed to allocate origin prop nvlist\n");
86			return (NULL);
87		}
88		if (be_get_dataset_props(be, propstr, *originprops) != 0) {
89			/* XXX TODO: Real errors */
90			fprintf(stderr,
91			    "bectl list: failed to fetch origin properties\n");
92			return (NULL);
93		}
94
95		return (propstr);
96	}
97	return (NULL);
98}
99
100static void
101print_padding(const char *fval, int colsz, struct printc *pc)
102{
103
104	/* -H flag handling; all delimiters/padding are a single tab */
105	if (pc->script_fmt) {
106		printf("\t");
107		return;
108	}
109
110	if (fval != NULL)
111		colsz -= strlen(fval);
112	printf("%*s ", colsz, "");
113}
114
115static unsigned long long
116dataset_space(const char *oname)
117{
118	unsigned long long space;
119	char *dsname, *sep;
120	const char *propstr;
121	nvlist_t *dsprops;
122
123	space = 0;
124	dsname = strdup(oname);
125	if (dsname == NULL)
126		return (0);
127
128	/* Truncate snapshot to dataset name, as needed */
129	if ((sep = strchr(dsname, '@')) != NULL)
130		*sep = '\0';
131
132	if (be_prop_list_alloc(&dsprops) != 0) {
133		free(dsname);
134		return (0);
135	}
136
137	if (be_get_dataset_props(be, dsname, dsprops) != 0) {
138		nvlist_free(dsprops);
139		free(dsname);
140		return (0);
141	}
142
143	if (nvlist_lookup_string(dsprops, "used", &propstr) == 0)
144		space = strtoull(propstr, NULL, 10);
145
146	nvlist_free(dsprops);
147	free(dsname);
148	return (space);
149}
150
151static int
152print_snapshots(const char *dsname, struct printc *pc)
153{
154	nvpair_t *cur;
155	nvlist_t *props, *sprops;
156
157	if (be_prop_list_alloc(&props) != 0) {
158		fprintf(stderr, "bectl list: failed to allocate snapshot nvlist\n");
159		return (1);
160	}
161	if (be_get_dataset_snapshots(be, dsname, props) != 0) {
162		fprintf(stderr, "bectl list: failed to fetch boot ds snapshots\n");
163		return (1);
164	}
165	for (cur = nvlist_next_nvpair(props, NULL); cur != NULL;
166	    cur = nvlist_next_nvpair(props, cur)) {
167		nvpair_value_nvlist(cur, &sprops);
168		print_info(nvpair_name(cur), sprops, pc);
169	}
170	return (0);
171}
172
173static void
174print_info(const char *name, nvlist_t *dsprops, struct printc *pc)
175{
176#define	BUFSZ	64
177	char buf[BUFSZ];
178	unsigned long long ctimenum, space;
179	nvlist_t *originprops;
180	const char *oname, *dsname, *propstr;
181	int active_colsz;
182	boolean_t active_now, active_reboot, bootonce;
183
184	dsname = NULL;
185	originprops = NULL;
186	printf("%*s%s", pc->current_indent, "", name);
187	nvlist_lookup_string(dsprops, "dataset", &dsname);
188
189	/* Recurse at the base level if we're breaking info down */
190	if (pc->current_indent == 0 && (pc->show_all_datasets ||
191	    pc->show_snaps)) {
192		printf("\n");
193		if (dsname == NULL)
194			/* XXX TODO: Error? */
195			return;
196		/*
197		 * Whether we're dealing with -a or -s, we'll always print the
198		 * dataset name/information followed by its origin. For -s, we
199		 * additionally iterate through all snapshots of this boot
200		 * environment and also print their information.
201		 */
202		pc->current_indent += INDENT_INCREMENT;
203		print_info(dsname, dsprops, pc);
204		pc->current_indent += INDENT_INCREMENT;
205		if ((oname = get_origin_props(dsprops, &originprops)) != NULL) {
206			print_info(oname, originprops, pc);
207			nvlist_free(originprops);
208		}
209
210		/* Back up a level; snapshots at the same level as dataset */
211		pc->current_indent -= INDENT_INCREMENT;
212		if (pc->show_snaps)
213			print_snapshots(dsname, pc);
214		pc->current_indent = 0;
215		return;
216	} else
217		print_padding(name, pc->be_colsz - pc->current_indent, pc);
218
219	active_colsz = pc->active_colsz_def;
220	if (nvlist_lookup_boolean_value(dsprops, "active",
221	    &active_now) == 0 && active_now) {
222		printf("N");
223		active_colsz--;
224	}
225	if (nvlist_lookup_boolean_value(dsprops, "nextboot",
226	    &active_reboot) == 0 && active_reboot) {
227		printf("R");
228		active_colsz--;
229	}
230	if (nvlist_lookup_boolean_value(dsprops, "bootonce",
231	    &bootonce) == 0 && bootonce) {
232		printf("T");
233		active_colsz--;
234	}
235	if (active_colsz == pc->active_colsz_def) {
236		printf("-");
237		active_colsz--;
238	}
239	print_padding(NULL, active_colsz, pc);
240	if (nvlist_lookup_string(dsprops, "mounted", &propstr) == 0) {
241		printf("%s", propstr);
242		print_padding(propstr, pc->mount_colsz, pc);
243	} else {
244		printf("%s", "-");
245		print_padding("-", pc->mount_colsz, pc);
246	}
247
248	oname = get_origin_props(dsprops, &originprops);
249	if (nvlist_lookup_string(dsprops, "used", &propstr) == 0) {
250		/*
251		 * The space used column is some composition of:
252		 * - The "used" property of the dataset
253		 * - The "used" property of the origin snapshot (not -a or -s)
254		 * - The "used" property of the origin dataset (-D flag only)
255		 *
256		 * The -D flag is ignored if -a or -s are specified.
257		 */
258		space = strtoull(propstr, NULL, 10);
259
260		if (!pc->show_all_datasets && !pc->show_snaps &&
261		    originprops != NULL &&
262		    nvlist_lookup_string(originprops, "used", &propstr) == 0)
263			space += strtoull(propstr, NULL, 10);
264
265		if (pc->show_space && oname != NULL)
266			space += dataset_space(oname);
267
268		/* Alas, there's more to it,. */
269		be_nicenum(space, buf, 6);
270		printf("%s", buf);
271		print_padding(buf, pc->space_colsz, pc);
272	} else {
273		printf("-");
274		print_padding("-", pc->space_colsz, pc);
275	}
276
277	if (nvlist_lookup_string(dsprops, "creation", &propstr) == 0) {
278		ctimenum = strtoull(propstr, NULL, 10);
279		strftime(buf, BUFSZ, "%Y-%m-%d %H:%M",
280		    localtime((time_t *)&ctimenum));
281		printf("%s", buf);
282	}
283
284	printf("\n");
285	if (originprops != NULL)
286		be_prop_list_free(originprops);
287#undef BUFSZ
288}
289
290static void
291print_headers(nvlist_t *props, struct printc *pc)
292{
293	const char *chosen_be_header, *propstr;
294	nvpair_t *cur;
295	nvlist_t *dsprops;
296	size_t be_maxcol, mount_colsz;
297
298	if (pc->show_all_datasets || pc->show_snaps)
299		chosen_be_header = HEADER_BEPLUS;
300	else
301		chosen_be_header = HEADER_BE;
302	be_maxcol = strlen(chosen_be_header);
303	mount_colsz = strlen(HEADER_MOUNT);
304	for (cur = nvlist_next_nvpair(props, NULL); cur != NULL;
305	    cur = nvlist_next_nvpair(props, cur)) {
306		be_maxcol = MAX(be_maxcol, strlen(nvpair_name(cur)));
307		nvpair_value_nvlist(cur, &dsprops);
308
309		if (nvlist_lookup_string(dsprops, "mounted", &propstr) == 0)
310			mount_colsz = MAX(mount_colsz, strlen(propstr));
311		if (!pc->show_all_datasets && !pc->show_snaps)
312			continue;
313		if (nvlist_lookup_string(dsprops, "dataset", &propstr) != 0)
314			continue;
315		be_maxcol = MAX(be_maxcol, strlen(propstr) + INDENT_INCREMENT);
316		if (nvlist_lookup_string(dsprops, "origin", &propstr) != 0)
317			continue;
318		be_maxcol = MAX(be_maxcol,
319		    strlen(propstr) + INDENT_INCREMENT * 2);
320	}
321
322	pc->be_colsz = be_maxcol;
323	pc->active_colsz_def = strlen(HEADER_ACTIVE);
324	pc->mount_colsz = mount_colsz;
325	pc->space_colsz = strlen(HEADER_SPACE);
326	printf("%*s %s %*s %s %s\n", -pc->be_colsz, chosen_be_header,
327	    HEADER_ACTIVE, -pc->mount_colsz, HEADER_MOUNT, HEADER_SPACE, HEADER_CREATED);
328
329	/*
330	 * All other invocations in which we aren't using the default header
331	 * will produce quite a bit of input.  Throw an extra blank line after
332	 * the header to make it look nicer.
333	 */
334	if (strcmp(chosen_be_header, HEADER_BE) != 0)
335		printf("\n");
336}
337
338/*
339 * Sort the given nvlist of boot environments by property.
340 */
341static int
342prop_list_sort(nvlist_t *props, char *property, bool reverse)
343{
344	nvpair_t *nvp;
345	nvlist_t *nvl;
346	int i, nvp_count;
347	uint64_t lval, rval;
348	struct sort_column sc_prev, sc_next;
349
350	/* a temporary list to work with */
351	nvlist_dup(props, &nvl, 0);
352
353	nvp_count = fnvlist_num_pairs(nvl);
354	for (i = 0; i < nvp_count; i++) {
355
356		nvp = nvlist_next_nvpair(nvl, NULL);
357		nvpair_value_nvlist(nvp, &sc_prev.nvl);
358		nvlist_lookup_string(sc_prev.nvl, "name", &sc_prev.name);
359		nvlist_lookup_string(sc_prev.nvl, property, &sc_prev.val);
360
361		while ((nvp = nvlist_next_nvpair(nvl, nvp)) != NULL) {
362
363			nvpair_value_nvlist(nvp, &sc_next.nvl);
364			nvlist_lookup_string(sc_next.nvl, "name", &sc_next.name);
365			nvlist_lookup_string(sc_next.nvl, property, &sc_next.val);
366
367			/* properties that use numerical comparison */
368			if (strcmp(property, "creation") == 0 ||
369			    strcmp(property, "used") == 0 ||
370			    strcmp(property, "usedds") == 0 ||
371			    strcmp(property, "usedsnap") == 0 ||
372			    strcmp(property, "usedrefreserv") == 0) {
373
374				lval = strtoull(sc_prev.val, NULL, 10);
375				rval = strtoull(sc_next.val, NULL, 10);
376
377				if ((lval < rval && reverse) ||
378				    (lval > rval && !reverse))
379					sc_prev = sc_next;
380			}
381
382			/* properties that use string comparison */
383			else if (strcmp(property, "name") == 0 ||
384				 strcmp(property, "origin") == 0) {
385				if ((strcmp(sc_prev.val, sc_next.val) < 0 && reverse) ||
386				    (strcmp(sc_prev.val, sc_next.val) > 0 && !reverse))
387					sc_prev = sc_next;
388			}
389		}
390
391		/*
392		 * The 'props' nvlist has been created to only have unique names.
393		 * When a name is added, any existing nvlist's with the same name
394		 * will be removed. Eventually, all existing nvlist's are replaced
395		 * in sorted order.
396		 */
397		nvlist_add_nvlist(props, sc_prev.name, sc_prev.nvl);
398		nvlist_remove_all(nvl, sc_prev.name);
399	}
400
401	be_prop_list_free(nvl);
402
403	return 0;
404}
405
406int
407bectl_cmd_list(int argc, char *argv[])
408{
409	struct printc pc;
410	nvpair_t *cur;
411	nvlist_t *dsprops, *props;
412	int opt, printed;
413	char *column;
414	bool reverse;
415
416	column = NULL;
417	props = NULL;
418	printed = 0;
419	bzero(&pc, sizeof(pc));
420	reverse = false;
421	while ((opt = getopt(argc, argv, "aDHsc:C:")) != -1) {
422		switch (opt) {
423		case 'a':
424			pc.show_all_datasets = true;
425			break;
426		case 'D':
427			pc.show_space = true;
428			break;
429		case 'H':
430			pc.script_fmt = true;
431			break;
432		case 's':
433			pc.show_snaps = true;
434			break;
435		case 'c':
436			if (column != NULL)
437				free(column);
438			column = strdup(optarg);
439			reverse = false;
440			break;
441		case 'C':
442			if (column != NULL)
443				free(column);
444			column = strdup(optarg);
445			reverse = true;
446			break;
447		default:
448			fprintf(stderr, "bectl list: unknown option '-%c'\n",
449			    optopt);
450			return (usage(false));
451		}
452	}
453
454	argc -= optind;
455
456	if (argc != 0) {
457		fprintf(stderr, "bectl list: extra argument provided\n");
458		return (usage(false));
459	}
460
461	if (be_prop_list_alloc(&props) != 0) {
462		fprintf(stderr, "bectl list: failed to allocate prop nvlist\n");
463		return (1);
464	}
465	if (be_get_bootenv_props(be, props) != 0) {
466		/* XXX TODO: Real errors */
467		fprintf(stderr, "bectl list: failed to fetch boot environments\n");
468		return (1);
469	}
470
471	/* List boot environments in alphabetical order by default */
472	if (column == NULL)
473		column = strdup("name");
474
475	prop_list_sort(props, column, reverse);
476
477	/* Force -D off if either -a or -s are specified */
478	if (pc.show_all_datasets || pc.show_snaps)
479		pc.show_space = false;
480	if (!pc.script_fmt)
481		print_headers(props, &pc);
482
483	/* Print boot environments */
484	for (cur = nvlist_next_nvpair(props, NULL); cur != NULL;
485	    cur = nvlist_next_nvpair(props, cur)) {
486		nvpair_value_nvlist(cur, &dsprops);
487
488		if (printed > 0 && (pc.show_all_datasets || pc.show_snaps))
489			printf("\n");
490
491		print_info(nvpair_name(cur), dsprops, &pc);
492		printed++;
493	}
494
495	free(column);
496	be_prop_list_free(props);
497
498	return (0);
499}
500
501