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