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