xref: /freebsd/lib/libbe/be.c (revision 6829dae12bb055451fa467da4589c43bd03b1e64)
1 /*-
2  * SPDX-License-Identifier: BSD-2-Clause-FreeBSD
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/cdefs.h>
30 __FBSDID("$FreeBSD$");
31 
32 #include <sys/param.h>
33 #include <sys/mount.h>
34 #include <sys/stat.h>
35 #include <sys/ucred.h>
36 
37 #include <ctype.h>
38 #include <libgen.h>
39 #include <libzfs_core.h>
40 #include <stdio.h>
41 #include <stdlib.h>
42 #include <time.h>
43 #include <unistd.h>
44 
45 #include "be.h"
46 #include "be_impl.h"
47 
48 struct be_destroy_data {
49 	libbe_handle_t		*lbh;
50 	char			*snapname;
51 };
52 
53 #if SOON
54 static int be_create_child_noent(libbe_handle_t *lbh, const char *active,
55     const char *child_path);
56 static int be_create_child_cloned(libbe_handle_t *lbh, const char *active);
57 #endif
58 
59 /*
60  * Iterator function for locating the rootfs amongst the children of the
61  * zfs_be_root set by loader(8).  data is expected to be a libbe_handle_t *.
62  */
63 static int
64 be_locate_rootfs(libbe_handle_t *lbh)
65 {
66 	struct statfs sfs;
67 	struct extmnttab entry;
68 	zfs_handle_t *zfs;
69 
70 	/*
71 	 * Check first if root is ZFS; if not, we'll bail on rootfs capture.
72 	 * Unfortunately needed because zfs_path_to_zhandle will emit to
73 	 * stderr if / isn't actually a ZFS filesystem, which we'd like
74 	 * to avoid.
75 	 */
76 	if (statfs("/", &sfs) == 0) {
77 		statfs2mnttab(&sfs, &entry);
78 		if (strcmp(entry.mnt_fstype, MNTTYPE_ZFS) != 0)
79 			return (1);
80 	} else
81 		return (1);
82 	zfs = zfs_path_to_zhandle(lbh->lzh, "/", ZFS_TYPE_FILESYSTEM);
83 	if (zfs == NULL)
84 		return (1);
85 
86 	strlcpy(lbh->rootfs, zfs_get_name(zfs), sizeof(lbh->rootfs));
87 	zfs_close(zfs);
88 	return (0);
89 }
90 
91 /*
92  * Initializes the libbe context to operate in the root boot environment
93  * dataset, for example, zroot/ROOT.
94  */
95 libbe_handle_t *
96 libbe_init(const char *root)
97 {
98 	char altroot[MAXPATHLEN];
99 	libbe_handle_t *lbh;
100 	char *poolname, *pos;
101 	int pnamelen;
102 
103 	lbh = NULL;
104 	poolname = pos = NULL;
105 
106 	if ((lbh = calloc(1, sizeof(libbe_handle_t))) == NULL)
107 		goto err;
108 
109 	if ((lbh->lzh = libzfs_init()) == NULL)
110 		goto err;
111 
112 	/*
113 	 * Grab rootfs, we'll work backwards from there if an optional BE root
114 	 * has not been passed in.
115 	 */
116 	if (be_locate_rootfs(lbh) != 0) {
117 		if (root == NULL)
118 			goto err;
119 		*lbh->rootfs = '\0';
120 	}
121 	if (root == NULL) {
122 		/* Strip off the final slash from rootfs to get the be root */
123 		strlcpy(lbh->root, lbh->rootfs, sizeof(lbh->root));
124 		pos = strrchr(lbh->root, '/');
125 		if (pos == NULL)
126 			goto err;
127 		*pos = '\0';
128 	} else
129 		strlcpy(lbh->root, root, sizeof(lbh->root));
130 
131 	if ((pos = strchr(lbh->root, '/')) == NULL)
132 		goto err;
133 
134 	pnamelen = pos - lbh->root;
135 	poolname = malloc(pnamelen + 1);
136 	if (poolname == NULL)
137 		goto err;
138 
139 	strlcpy(poolname, lbh->root, pnamelen + 1);
140 	if ((lbh->active_phandle = zpool_open(lbh->lzh, poolname)) == NULL)
141 		goto err;
142 	free(poolname);
143 	poolname = NULL;
144 
145 	if (zpool_get_prop(lbh->active_phandle, ZPOOL_PROP_BOOTFS, lbh->bootfs,
146 	    sizeof(lbh->bootfs), NULL, true) != 0)
147 		goto err;
148 
149 	if (zpool_get_prop(lbh->active_phandle, ZPOOL_PROP_ALTROOT,
150 	    altroot, sizeof(altroot), NULL, true) == 0 &&
151 	    strcmp(altroot, "-") != 0)
152 		lbh->altroot_len = strlen(altroot);
153 
154 	return (lbh);
155 err:
156 	if (lbh != NULL) {
157 		if (lbh->active_phandle != NULL)
158 			zpool_close(lbh->active_phandle);
159 		if (lbh->lzh != NULL)
160 			libzfs_fini(lbh->lzh);
161 		free(lbh);
162 	}
163 	free(poolname);
164 	return (NULL);
165 }
166 
167 
168 /*
169  * Free memory allocated by libbe_init()
170  */
171 void
172 libbe_close(libbe_handle_t *lbh)
173 {
174 
175 	if (lbh->active_phandle != NULL)
176 		zpool_close(lbh->active_phandle);
177 	libzfs_fini(lbh->lzh);
178 	free(lbh);
179 }
180 
181 /*
182  * Proxy through to libzfs for the moment.
183  */
184 void
185 be_nicenum(uint64_t num, char *buf, size_t buflen)
186 {
187 
188 	zfs_nicenum(num, buf, buflen);
189 }
190 
191 static int
192 be_destroy_cb(zfs_handle_t *zfs_hdl, void *data)
193 {
194 	char path[BE_MAXPATHLEN];
195 	struct be_destroy_data *bdd;
196 	zfs_handle_t *snap;
197 	int err;
198 
199 	bdd = (struct be_destroy_data *)data;
200 	if (bdd->snapname == NULL) {
201 		err = zfs_iter_children(zfs_hdl, be_destroy_cb, data);
202 		if (err != 0)
203 			return (err);
204 		return (zfs_destroy(zfs_hdl, false));
205 	}
206 	/* If we're dealing with snapshots instead, delete that one alone */
207 	err = zfs_iter_filesystems(zfs_hdl, be_destroy_cb, data);
208 	if (err != 0)
209 		return (err);
210 	/*
211 	 * This part is intentionally glossing over any potential errors,
212 	 * because there's a lot less potential for errors when we're cleaning
213 	 * up snapshots rather than a full deep BE.  The primary error case
214 	 * here being if the snapshot doesn't exist in the first place, which
215 	 * the caller will likely deem insignificant as long as it doesn't
216 	 * exist after the call.  Thus, such a missing snapshot shouldn't jam
217 	 * up the destruction.
218 	 */
219 	snprintf(path, sizeof(path), "%s@%s", zfs_get_name(zfs_hdl),
220 	    bdd->snapname);
221 	if (!zfs_dataset_exists(bdd->lbh->lzh, path, ZFS_TYPE_SNAPSHOT))
222 		return (0);
223 	snap = zfs_open(bdd->lbh->lzh, path, ZFS_TYPE_SNAPSHOT);
224 	if (snap != NULL)
225 		zfs_destroy(snap, false);
226 	return (0);
227 }
228 
229 /*
230  * Destroy the boot environment or snapshot specified by the name
231  * parameter. Options are or'd together with the possible values:
232  * BE_DESTROY_FORCE : forces operation on mounted datasets
233  * BE_DESTROY_ORIGIN: destroy the origin snapshot as well
234  */
235 int
236 be_destroy(libbe_handle_t *lbh, const char *name, int options)
237 {
238 	struct be_destroy_data bdd;
239 	char origin[BE_MAXPATHLEN], path[BE_MAXPATHLEN];
240 	zfs_handle_t *fs;
241 	char *snapdelim;
242 	int err, force, mounted;
243 	size_t rootlen;
244 
245 	bdd.lbh = lbh;
246 	bdd.snapname = NULL;
247 	force = options & BE_DESTROY_FORCE;
248 	*origin = '\0';
249 
250 	be_root_concat(lbh, name, path);
251 
252 	if ((snapdelim = strchr(path, '@')) == NULL) {
253 		if (!zfs_dataset_exists(lbh->lzh, path, ZFS_TYPE_FILESYSTEM))
254 			return (set_error(lbh, BE_ERR_NOENT));
255 
256 		if (strcmp(path, lbh->rootfs) == 0 ||
257 		    strcmp(path, lbh->bootfs) == 0)
258 			return (set_error(lbh, BE_ERR_DESTROYACT));
259 
260 		fs = zfs_open(lbh->lzh, path, ZFS_TYPE_FILESYSTEM);
261 		if (fs == NULL)
262 			return (set_error(lbh, BE_ERR_ZFSOPEN));
263 
264 		if ((options & BE_DESTROY_ORIGIN) != 0 &&
265 		    zfs_prop_get(fs, ZFS_PROP_ORIGIN, origin, sizeof(origin),
266 		    NULL, NULL, 0, 1) != 0)
267 			return (set_error(lbh, BE_ERR_NOORIGIN));
268 	} else {
269 		if (!zfs_dataset_exists(lbh->lzh, path, ZFS_TYPE_SNAPSHOT))
270 			return (set_error(lbh, BE_ERR_NOENT));
271 
272 		bdd.snapname = strdup(snapdelim + 1);
273 		if (bdd.snapname == NULL)
274 			return (set_error(lbh, BE_ERR_NOMEM));
275 		*snapdelim = '\0';
276 		fs = zfs_open(lbh->lzh, path, ZFS_TYPE_DATASET);
277 		if (fs == NULL) {
278 			free(bdd.snapname);
279 			return (set_error(lbh, BE_ERR_ZFSOPEN));
280 		}
281 	}
282 
283 	/* Check if mounted, unmount if force is specified */
284 	if ((mounted = zfs_is_mounted(fs, NULL)) != 0) {
285 		if (force) {
286 			zfs_unmount(fs, NULL, 0);
287 		} else {
288 			free(bdd.snapname);
289 			return (set_error(lbh, BE_ERR_DESTROYMNT));
290 		}
291 	}
292 
293 	err = be_destroy_cb(fs, &bdd);
294 	zfs_close(fs);
295 	free(bdd.snapname);
296 	if (err != 0) {
297 		/* Children are still present or the mount is referenced */
298 		if (err == EBUSY)
299 			return (set_error(lbh, BE_ERR_DESTROYMNT));
300 		return (set_error(lbh, BE_ERR_UNKNOWN));
301 	}
302 
303 	if ((options & BE_DESTROY_ORIGIN) == 0)
304 		return (0);
305 
306 	/* The origin can't possibly be shorter than the BE root */
307 	rootlen = strlen(lbh->root);
308 	if (*origin == '\0' || strlen(origin) <= rootlen + 1)
309 		return (set_error(lbh, BE_ERR_INVORIGIN));
310 
311 	/*
312 	 * We'll be chopping off the BE root and running this back through
313 	 * be_destroy, so that we properly handle the origin snapshot whether
314 	 * it be that of a deep BE or not.
315 	 */
316 	if (strncmp(origin, lbh->root, rootlen) != 0 || origin[rootlen] != '/')
317 		return (0);
318 
319 	return (be_destroy(lbh, origin + rootlen + 1,
320 	    options & ~BE_DESTROY_ORIGIN));
321 }
322 
323 int
324 be_snapshot(libbe_handle_t *lbh, const char *source, const char *snap_name,
325     bool recursive, char *result)
326 {
327 	char buf[BE_MAXPATHLEN];
328 	time_t rawtime;
329 	int len, err;
330 
331 	be_root_concat(lbh, source, buf);
332 
333 	if ((err = be_exists(lbh, buf)) != 0)
334 		return (set_error(lbh, err));
335 
336 	if (snap_name != NULL) {
337 		if (strlcat(buf, "@", sizeof(buf)) >= sizeof(buf))
338 			return (set_error(lbh, BE_ERR_INVALIDNAME));
339 
340 		if (strlcat(buf, snap_name, sizeof(buf)) >= sizeof(buf))
341 			return (set_error(lbh, BE_ERR_INVALIDNAME));
342 
343 		if (result != NULL)
344 			snprintf(result, BE_MAXPATHLEN, "%s@%s", source,
345 			    snap_name);
346 	} else {
347 		time(&rawtime);
348 		len = strlen(buf);
349 		strftime(buf + len, sizeof(buf) - len,
350 		    "@%F-%T", localtime(&rawtime));
351 		if (result != NULL && strlcpy(result, strrchr(buf, '/') + 1,
352 		    sizeof(buf)) >= sizeof(buf))
353 			return (set_error(lbh, BE_ERR_INVALIDNAME));
354 	}
355 
356 	if ((err = zfs_snapshot(lbh->lzh, buf, recursive, NULL)) != 0) {
357 		switch (err) {
358 		case EZFS_INVALIDNAME:
359 			return (set_error(lbh, BE_ERR_INVALIDNAME));
360 
361 		default:
362 			/*
363 			 * The other errors that zfs_ioc_snapshot might return
364 			 * shouldn't happen if we've set things up properly, so
365 			 * we'll gloss over them and call it UNKNOWN as it will
366 			 * require further triage.
367 			 */
368 			if (errno == ENOTSUP)
369 				return (set_error(lbh, BE_ERR_NOPOOL));
370 			return (set_error(lbh, BE_ERR_UNKNOWN));
371 		}
372 	}
373 
374 	return (BE_ERR_SUCCESS);
375 }
376 
377 
378 /*
379  * Create the boot environment specified by the name parameter
380  */
381 int
382 be_create(libbe_handle_t *lbh, const char *name)
383 {
384 	int err;
385 
386 	err = be_create_from_existing(lbh, name, be_active_path(lbh));
387 
388 	return (set_error(lbh, err));
389 }
390 
391 static int
392 be_deep_clone_prop(int prop, void *cb)
393 {
394 	int err;
395         struct libbe_dccb *dccb;
396 	zprop_source_t src;
397 	char pval[BE_MAXPATHLEN];
398 	char source[BE_MAXPATHLEN];
399 	char *val;
400 
401 	dccb = cb;
402 	/* Skip some properties we don't want to touch */
403 	if (prop == ZFS_PROP_CANMOUNT)
404 		return (ZPROP_CONT);
405 
406 	/* Don't copy readonly properties */
407 	if (zfs_prop_readonly(prop))
408 		return (ZPROP_CONT);
409 
410 	if ((err = zfs_prop_get(dccb->zhp, prop, (char *)&pval,
411 	    sizeof(pval), &src, (char *)&source, sizeof(source), false)))
412 		/* Just continue if we fail to read a property */
413 		return (ZPROP_CONT);
414 
415 	/* Only copy locally defined properties */
416 	if (src != ZPROP_SRC_LOCAL)
417 		return (ZPROP_CONT);
418 
419 	/* Augment mountpoint with altroot, if needed */
420 	val = pval;
421 	if (prop == ZFS_PROP_MOUNTPOINT)
422 		val = be_mountpoint_augmented(dccb->lbh, val);
423 
424 	nvlist_add_string(dccb->props, zfs_prop_to_name(prop), val);
425 
426 	return (ZPROP_CONT);
427 }
428 
429 static int
430 be_deep_clone(zfs_handle_t *ds, void *data)
431 {
432 	int err;
433 	char be_path[BE_MAXPATHLEN];
434 	char snap_path[BE_MAXPATHLEN];
435 	const char *dspath;
436 	char *dsname;
437 	zfs_handle_t *snap_hdl;
438 	nvlist_t *props;
439 	struct libbe_deep_clone *isdc, sdc;
440 	struct libbe_dccb dccb;
441 
442 	isdc = (struct libbe_deep_clone *)data;
443 	dspath = zfs_get_name(ds);
444 	if ((dsname = strrchr(dspath, '/')) == NULL)
445 		return (BE_ERR_UNKNOWN);
446 	dsname++;
447 
448 	if (isdc->bename == NULL)
449 		snprintf(be_path, sizeof(be_path), "%s/%s", isdc->be_root, dsname);
450 	else
451 		snprintf(be_path, sizeof(be_path), "%s/%s", isdc->be_root, isdc->bename);
452 
453 	snprintf(snap_path, sizeof(snap_path), "%s@%s", dspath, isdc->snapname);
454 
455 	if (zfs_dataset_exists(isdc->lbh->lzh, be_path, ZFS_TYPE_DATASET))
456 		return (set_error(isdc->lbh, BE_ERR_EXISTS));
457 
458 	if ((snap_hdl =
459 	    zfs_open(isdc->lbh->lzh, snap_path, ZFS_TYPE_SNAPSHOT)) == NULL)
460 		return (set_error(isdc->lbh, BE_ERR_ZFSOPEN));
461 
462 	nvlist_alloc(&props, NV_UNIQUE_NAME, KM_SLEEP);
463 	nvlist_add_string(props, "canmount", "noauto");
464 
465 	dccb.lbh = isdc->lbh;
466 	dccb.zhp = ds;
467 	dccb.props = props;
468 	if (zprop_iter(be_deep_clone_prop, &dccb, B_FALSE, B_FALSE,
469 	    ZFS_TYPE_FILESYSTEM) == ZPROP_INVAL)
470 		return (-1);
471 
472 	if ((err = zfs_clone(snap_hdl, be_path, props)) != 0)
473 		err = BE_ERR_ZFSCLONE;
474 
475 	nvlist_free(props);
476 	zfs_close(snap_hdl);
477 
478 	/* Failed to clone */
479 	if (err != BE_ERR_SUCCESS)
480 		return (set_error(isdc->lbh, err));
481 
482 	sdc.lbh = isdc->lbh;
483 	sdc.bename = NULL;
484 	sdc.snapname = isdc->snapname;
485 	sdc.be_root = (char *)&be_path;
486 
487 	err = zfs_iter_filesystems(ds, be_deep_clone, &sdc);
488 
489 	return (err);
490 }
491 
492 /*
493  * Create the boot environment from pre-existing snapshot
494  */
495 int
496 be_create_from_existing_snap(libbe_handle_t *lbh, const char *name,
497     const char *snap)
498 {
499 	int err;
500 	char be_path[BE_MAXPATHLEN];
501 	char snap_path[BE_MAXPATHLEN];
502 	const char *bename;
503 	char *parentname, *snapname;
504 	zfs_handle_t *parent_hdl;
505 	struct libbe_deep_clone sdc;
506 
507 	if ((err = be_validate_name(lbh, name)) != 0)
508 		return (set_error(lbh, err));
509 	if ((err = be_root_concat(lbh, snap, snap_path)) != 0)
510 		return (set_error(lbh, err));
511 	if ((err = be_validate_snap(lbh, snap_path)) != 0)
512 		return (set_error(lbh, err));
513 
514 	if ((err = be_root_concat(lbh, name, be_path)) != 0)
515 		return (set_error(lbh, err));
516 
517 	if ((bename = strrchr(name, '/')) == NULL)
518 		bename = name;
519 	else
520 		bename++;
521 
522 	if ((parentname = strdup(snap_path)) == NULL)
523 		return (set_error(lbh, BE_ERR_UNKNOWN));
524 
525 	snapname = strchr(parentname, '@');
526 	if (snapname == NULL) {
527 		free(parentname);
528 		return (set_error(lbh, BE_ERR_UNKNOWN));
529 	}
530 	*snapname = '\0';
531 	snapname++;
532 
533 	sdc.lbh = lbh;
534 	sdc.bename = bename;
535 	sdc.snapname = snapname;
536 	sdc.be_root = lbh->root;
537 
538 	parent_hdl = zfs_open(lbh->lzh, parentname, ZFS_TYPE_DATASET);
539 	err = be_deep_clone(parent_hdl, &sdc);
540 
541 	free(parentname);
542 	return (set_error(lbh, err));
543 }
544 
545 
546 /*
547  * Create a boot environment from an existing boot environment
548  */
549 int
550 be_create_from_existing(libbe_handle_t *lbh, const char *name, const char *old)
551 {
552 	int err;
553 	char buf[BE_MAXPATHLEN];
554 
555 	if ((err = be_snapshot(lbh, old, NULL, true, (char *)&buf)) != 0)
556 		return (set_error(lbh, err));
557 
558 	err = be_create_from_existing_snap(lbh, name, (char *)buf);
559 
560 	return (set_error(lbh, err));
561 }
562 
563 
564 /*
565  * Verifies that a snapshot has a valid name, exists, and has a mountpoint of
566  * '/'. Returns BE_ERR_SUCCESS (0), upon success, or the relevant BE_ERR_* upon
567  * failure. Does not set the internal library error state.
568  */
569 int
570 be_validate_snap(libbe_handle_t *lbh, const char *snap_name)
571 {
572 
573 	if (strlen(snap_name) >= BE_MAXPATHLEN)
574 		return (BE_ERR_PATHLEN);
575 
576 	if (!zfs_dataset_exists(lbh->lzh, snap_name,
577 	    ZFS_TYPE_SNAPSHOT))
578 		return (BE_ERR_NOENT);
579 
580 	return (BE_ERR_SUCCESS);
581 }
582 
583 
584 /*
585  * Idempotently appends the name argument to the root boot environment path
586  * and copies the resulting string into the result buffer (which is assumed
587  * to be at least BE_MAXPATHLEN characters long. Returns BE_ERR_SUCCESS upon
588  * success, BE_ERR_PATHLEN if the resulting path is longer than BE_MAXPATHLEN,
589  * or BE_ERR_INVALIDNAME if the name is a path that does not begin with
590  * zfs_be_root. Does not set internal library error state.
591  */
592 int
593 be_root_concat(libbe_handle_t *lbh, const char *name, char *result)
594 {
595 	size_t name_len, root_len;
596 
597 	name_len = strlen(name);
598 	root_len = strlen(lbh->root);
599 
600 	/* Act idempotently; return be name if it is already a full path */
601 	if (strrchr(name, '/') != NULL) {
602 		if (strstr(name, lbh->root) != name)
603 			return (BE_ERR_INVALIDNAME);
604 
605 		if (name_len >= BE_MAXPATHLEN)
606 			return (BE_ERR_PATHLEN);
607 
608 		strlcpy(result, name, BE_MAXPATHLEN);
609 		return (BE_ERR_SUCCESS);
610 	} else if (name_len + root_len + 1 < BE_MAXPATHLEN) {
611 		snprintf(result, BE_MAXPATHLEN, "%s/%s", lbh->root,
612 		    name);
613 		return (BE_ERR_SUCCESS);
614 	}
615 
616 	return (BE_ERR_PATHLEN);
617 }
618 
619 
620 /*
621  * Verifies the validity of a boot environment name (A-Za-z0-9-_.). Returns
622  * BE_ERR_SUCCESS (0) if name is valid, otherwise returns BE_ERR_INVALIDNAME
623  * or BE_ERR_PATHLEN.
624  * Does not set internal library error state.
625  */
626 int
627 be_validate_name(libbe_handle_t *lbh, const char *name)
628 {
629 	for (int i = 0; *name; i++) {
630 		char c = *(name++);
631 		if (isalnum(c) || (c == '-') || (c == '_') || (c == '.'))
632 			continue;
633 		return (BE_ERR_INVALIDNAME);
634 	}
635 
636 	/*
637 	 * Impose the additional restriction that the entire dataset name must
638 	 * not exceed the maximum length of a dataset, i.e. MAXNAMELEN.
639 	 */
640 	if (strlen(lbh->root) + 1 + strlen(name) > MAXNAMELEN)
641 		return (BE_ERR_PATHLEN);
642 	return (BE_ERR_SUCCESS);
643 }
644 
645 
646 /*
647  * usage
648  */
649 int
650 be_rename(libbe_handle_t *lbh, const char *old, const char *new)
651 {
652 	char full_old[BE_MAXPATHLEN];
653 	char full_new[BE_MAXPATHLEN];
654 	zfs_handle_t *zfs_hdl;
655 	int err;
656 
657 	/*
658 	 * be_validate_name is documented not to set error state, so we should
659 	 * do so here.
660 	 */
661 	if ((err = be_validate_name(lbh, new)) != 0)
662 		return (set_error(lbh, err));
663 	if ((err = be_root_concat(lbh, old, full_old)) != 0)
664 		return (set_error(lbh, err));
665 	if ((err = be_root_concat(lbh, new, full_new)) != 0)
666 		return (set_error(lbh, err));
667 
668 	if (!zfs_dataset_exists(lbh->lzh, full_old, ZFS_TYPE_DATASET))
669 		return (set_error(lbh, BE_ERR_NOENT));
670 
671 	if (zfs_dataset_exists(lbh->lzh, full_new, ZFS_TYPE_DATASET))
672 		return (set_error(lbh, BE_ERR_EXISTS));
673 
674 	if ((zfs_hdl = zfs_open(lbh->lzh, full_old,
675 	    ZFS_TYPE_FILESYSTEM)) == NULL)
676 		return (set_error(lbh, BE_ERR_ZFSOPEN));
677 
678 	/* recurse, nounmount, forceunmount */
679 	struct renameflags flags = {
680 		.nounmount = 1,
681 	};
682 
683 	err = zfs_rename(zfs_hdl, NULL, full_new, flags);
684 
685 	zfs_close(zfs_hdl);
686 	if (err != 0)
687 		return (set_error(lbh, BE_ERR_UNKNOWN));
688 	return (0);
689 }
690 
691 
692 int
693 be_export(libbe_handle_t *lbh, const char *bootenv, int fd)
694 {
695 	char snap_name[BE_MAXPATHLEN];
696 	char buf[BE_MAXPATHLEN];
697 	zfs_handle_t *zfs;
698 	int err;
699 
700 	if ((err = be_snapshot(lbh, bootenv, NULL, true, snap_name)) != 0)
701 		/* Use the error set by be_snapshot */
702 		return (err);
703 
704 	be_root_concat(lbh, snap_name, buf);
705 
706 	if ((zfs = zfs_open(lbh->lzh, buf, ZFS_TYPE_DATASET)) == NULL)
707 		return (set_error(lbh, BE_ERR_ZFSOPEN));
708 
709 	err = zfs_send_one(zfs, NULL, fd, 0);
710 	zfs_close(zfs);
711 
712 	return (err);
713 }
714 
715 
716 int
717 be_import(libbe_handle_t *lbh, const char *bootenv, int fd)
718 {
719 	char buf[BE_MAXPATHLEN];
720 	nvlist_t *props;
721 	zfs_handle_t *zfs;
722 	recvflags_t flags = { .nomount = 1 };
723 	int err;
724 
725 	be_root_concat(lbh, bootenv, buf);
726 
727 	if ((err = zfs_receive(lbh->lzh, buf, NULL, &flags, fd, NULL)) != 0) {
728 		switch (err) {
729 		case EINVAL:
730 			return (set_error(lbh, BE_ERR_NOORIGIN));
731 		case ENOENT:
732 			return (set_error(lbh, BE_ERR_NOENT));
733 		case EIO:
734 			return (set_error(lbh, BE_ERR_IO));
735 		default:
736 			return (set_error(lbh, BE_ERR_UNKNOWN));
737 		}
738 	}
739 
740 	if ((zfs = zfs_open(lbh->lzh, buf, ZFS_TYPE_FILESYSTEM)) == NULL)
741 		return (set_error(lbh, BE_ERR_ZFSOPEN));
742 
743 	nvlist_alloc(&props, NV_UNIQUE_NAME, KM_SLEEP);
744 	nvlist_add_string(props, "canmount", "noauto");
745 	nvlist_add_string(props, "mountpoint", "/");
746 
747 	err = zfs_prop_set_list(zfs, props);
748 	nvlist_free(props);
749 
750 	zfs_close(zfs);
751 
752 	if (err != 0)
753 		return (set_error(lbh, BE_ERR_UNKNOWN));
754 
755 	return (0);
756 }
757 
758 #if SOON
759 static int
760 be_create_child_noent(libbe_handle_t *lbh, const char *active,
761     const char *child_path)
762 {
763 	nvlist_t *props;
764 	zfs_handle_t *zfs;
765 	int err;
766 
767 	nvlist_alloc(&props, NV_UNIQUE_NAME, KM_SLEEP);
768 	nvlist_add_string(props, "canmount", "noauto");
769 	nvlist_add_string(props, "mountpoint", child_path);
770 
771 	/* Create */
772 	if ((err = zfs_create(lbh->lzh, active, ZFS_TYPE_DATASET,
773 	    props)) != 0) {
774 		switch (err) {
775 		case EZFS_EXISTS:
776 			return (set_error(lbh, BE_ERR_EXISTS));
777 		case EZFS_NOENT:
778 			return (set_error(lbh, BE_ERR_NOENT));
779 		case EZFS_BADTYPE:
780 		case EZFS_BADVERSION:
781 			return (set_error(lbh, BE_ERR_NOPOOL));
782 		case EZFS_BADPROP:
783 		default:
784 			/* We set something up wrong, probably... */
785 			return (set_error(lbh, BE_ERR_UNKNOWN));
786 		}
787 	}
788 	nvlist_free(props);
789 
790 	if ((zfs = zfs_open(lbh->lzh, active, ZFS_TYPE_DATASET)) == NULL)
791 		return (set_error(lbh, BE_ERR_ZFSOPEN));
792 
793 	/* Set props */
794 	if ((err = zfs_prop_set(zfs, "canmount", "noauto")) != 0) {
795 		zfs_close(zfs);
796 		/*
797 		 * Similar to other cases, this shouldn't fail unless we've
798 		 * done something wrong.  This is a new dataset that shouldn't
799 		 * have been mounted anywhere between creation and now.
800 		 */
801 		if (err == EZFS_NOMEM)
802 			return (set_error(lbh, BE_ERR_NOMEM));
803 		return (set_error(lbh, BE_ERR_UNKNOWN));
804 	}
805 	zfs_close(zfs);
806 	return (BE_ERR_SUCCESS);
807 }
808 
809 static int
810 be_create_child_cloned(libbe_handle_t *lbh, const char *active)
811 {
812 	char buf[BE_MAXPATHLEN], tmp[BE_MAXPATHLEN];;
813 	zfs_handle_t *zfs;
814 	int err;
815 
816 	/* XXX TODO ? */
817 
818 	/*
819 	 * Establish if the existing path is a zfs dataset or just
820 	 * the subdirectory of one
821 	 */
822 	strlcpy(tmp, "tmp/be_snap.XXXXX", sizeof(tmp));
823 	if (mktemp(tmp) == NULL)
824 		return (set_error(lbh, BE_ERR_UNKNOWN));
825 
826 	be_root_concat(lbh, tmp, buf);
827 	printf("Here %s?\n", buf);
828 	if ((err = zfs_snapshot(lbh->lzh, buf, false, NULL)) != 0) {
829 		switch (err) {
830 		case EZFS_INVALIDNAME:
831 			return (set_error(lbh, BE_ERR_INVALIDNAME));
832 
833 		default:
834 			/*
835 			 * The other errors that zfs_ioc_snapshot might return
836 			 * shouldn't happen if we've set things up properly, so
837 			 * we'll gloss over them and call it UNKNOWN as it will
838 			 * require further triage.
839 			 */
840 			if (errno == ENOTSUP)
841 				return (set_error(lbh, BE_ERR_NOPOOL));
842 			return (set_error(lbh, BE_ERR_UNKNOWN));
843 		}
844 	}
845 
846 	/* Clone */
847 	if ((zfs = zfs_open(lbh->lzh, buf, ZFS_TYPE_SNAPSHOT)) == NULL)
848 		return (BE_ERR_ZFSOPEN);
849 
850 	if ((err = zfs_clone(zfs, active, NULL)) != 0)
851 		/* XXX TODO correct error */
852 		return (set_error(lbh, BE_ERR_UNKNOWN));
853 
854 	/* set props */
855 	zfs_close(zfs);
856 	return (BE_ERR_SUCCESS);
857 }
858 
859 int
860 be_add_child(libbe_handle_t *lbh, const char *child_path, bool cp_if_exists)
861 {
862 	struct stat sb;
863 	char active[BE_MAXPATHLEN], buf[BE_MAXPATHLEN];
864 	nvlist_t *props;
865 	const char *s;
866 
867 	/* Require absolute paths */
868 	if (*child_path != '/')
869 		return (set_error(lbh, BE_ERR_BADPATH));
870 
871 	strlcpy(active, be_active_path(lbh), BE_MAXPATHLEN);
872 	strcpy(buf, active);
873 
874 	/* Create non-mountable parent dataset(s) */
875 	s = child_path;
876 	for (char *p; (p = strchr(s+1, '/')) != NULL; s = p) {
877 		size_t len = p - s;
878 		strncat(buf, s, len);
879 
880 		nvlist_alloc(&props, NV_UNIQUE_NAME, KM_SLEEP);
881 		nvlist_add_string(props, "canmount", "off");
882 		nvlist_add_string(props, "mountpoint", "none");
883 		zfs_create(lbh->lzh, buf, ZFS_TYPE_DATASET, props);
884 		nvlist_free(props);
885 	}
886 
887 	/* Path does not exist as a descendent of / yet */
888 	if (strlcat(active, child_path, BE_MAXPATHLEN) >= BE_MAXPATHLEN)
889 		return (set_error(lbh, BE_ERR_PATHLEN));
890 
891 	if (stat(child_path, &sb) != 0) {
892 		/* Verify that error is ENOENT */
893 		if (errno != ENOENT)
894 			return (set_error(lbh, BE_ERR_UNKNOWN));
895 		return (be_create_child_noent(lbh, active, child_path));
896 	} else if (cp_if_exists)
897 		/* Path is already a descendent of / and should be copied */
898 		return (be_create_child_cloned(lbh, active));
899 	return (set_error(lbh, BE_ERR_EXISTS));
900 }
901 #endif	/* SOON */
902 
903 static int
904 be_set_nextboot(libbe_handle_t *lbh, nvlist_t *config, uint64_t pool_guid,
905     const char *zfsdev)
906 {
907 	nvlist_t **child;
908 	uint64_t vdev_guid;
909 	int c, children;
910 
911 	if (nvlist_lookup_nvlist_array(config, ZPOOL_CONFIG_CHILDREN, &child,
912 	    &children) == 0) {
913 		for (c = 0; c < children; ++c)
914 			if (be_set_nextboot(lbh, child[c], pool_guid, zfsdev) != 0)
915 				return (1);
916 		return (0);
917 	}
918 
919 	if (nvlist_lookup_uint64(config, ZPOOL_CONFIG_GUID,
920 	    &vdev_guid) != 0) {
921 		return (1);
922 	}
923 
924 	if (zpool_nextboot(lbh->lzh, pool_guid, vdev_guid, zfsdev) != 0) {
925 		perror("ZFS_IOC_NEXTBOOT failed");
926 		return (1);
927 	}
928 
929 	return (0);
930 }
931 
932 /*
933  * Deactivate old BE dataset; currently just sets canmount=noauto
934  */
935 static int
936 be_deactivate(libbe_handle_t *lbh, const char *ds)
937 {
938 	zfs_handle_t *zfs;
939 
940 	if ((zfs = zfs_open(lbh->lzh, ds, ZFS_TYPE_DATASET)) == NULL)
941 		return (1);
942 	if (zfs_prop_set(zfs, "canmount", "noauto") != 0)
943 		return (1);
944 	zfs_close(zfs);
945 	return (0);
946 }
947 
948 int
949 be_activate(libbe_handle_t *lbh, const char *bootenv, bool temporary)
950 {
951 	char be_path[BE_MAXPATHLEN];
952 	char buf[BE_MAXPATHLEN];
953 	nvlist_t *config, *dsprops, *vdevs;
954 	char *origin;
955 	uint64_t pool_guid;
956 	zfs_handle_t *zhp;
957 	int err;
958 
959 	be_root_concat(lbh, bootenv, be_path);
960 
961 	/* Note: be_exists fails if mountpoint is not / */
962 	if ((err = be_exists(lbh, be_path)) != 0)
963 		return (set_error(lbh, err));
964 
965 	if (temporary) {
966 		config = zpool_get_config(lbh->active_phandle, NULL);
967 		if (config == NULL)
968 			/* config should be fetchable... */
969 			return (set_error(lbh, BE_ERR_UNKNOWN));
970 
971 		if (nvlist_lookup_uint64(config, ZPOOL_CONFIG_POOL_GUID,
972 		    &pool_guid) != 0)
973 			/* Similarly, it shouldn't be possible */
974 			return (set_error(lbh, BE_ERR_UNKNOWN));
975 
976 		/* Expected format according to zfsbootcfg(8) man */
977 		snprintf(buf, sizeof(buf), "zfs:%s:", be_path);
978 
979 		/* We have no config tree */
980 		if (nvlist_lookup_nvlist(config, ZPOOL_CONFIG_VDEV_TREE,
981 		    &vdevs) != 0)
982 			return (set_error(lbh, BE_ERR_NOPOOL));
983 
984 		return (be_set_nextboot(lbh, vdevs, pool_guid, buf));
985 	} else {
986 		if (be_deactivate(lbh, lbh->bootfs) != 0)
987 			return (-1);
988 
989 		/* Obtain bootenv zpool */
990 		err = zpool_set_prop(lbh->active_phandle, "bootfs", be_path);
991 		if (err)
992 			return (-1);
993 
994 		zhp = zfs_open(lbh->lzh, be_path, ZFS_TYPE_FILESYSTEM);
995 		if (zhp == NULL)
996 			return (-1);
997 
998 		if (be_prop_list_alloc(&dsprops) != 0)
999 			return (-1);
1000 
1001 		if (be_get_dataset_props(lbh, be_path, dsprops) != 0) {
1002 			nvlist_free(dsprops);
1003 			return (-1);
1004 		}
1005 
1006 		if (nvlist_lookup_string(dsprops, "origin", &origin) == 0)
1007 			err = zfs_promote(zhp);
1008 		nvlist_free(dsprops);
1009 
1010 		zfs_close(zhp);
1011 
1012 		if (err)
1013 			return (-1);
1014 	}
1015 
1016 	return (BE_ERR_SUCCESS);
1017 }
1018