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