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