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