1 /*-
2  * SPDX-License-Identifier: BSD-2-Clause-FreeBSD
3  *
4  * Copyright (c) 2017 Kyle J. Kneitinger <kyle@kneit.in>
5  *
6  * Redistribution and use in source and binary forms, with or without
7  * modification, are permitted provided that the following conditions
8  * are met:
9  * 1. Redistributions of source code must retain the above copyright
10  *    notice, this list of conditions and the following disclaimer.
11  * 2. Redistributions in binary form must reproduce the above copyright
12  *    notice, this list of conditions and the following disclaimer in the
13  *    documentation and/or other materials provided with the distribution.
14  *
15  * THIS SOFTWARE IS PROVIDED BY THE REGENTS AND CONTRIBUTORS ``AS IS'' AND
16  * ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
17  * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE
18  * ARE DISCLAIMED.  IN NO EVENT SHALL THE REGENTS OR CONTRIBUTORS BE LIABLE
19  * FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL
20  * DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS
21  * OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION)
22  * HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT
23  * LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY
24  * OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF
25  * SUCH DAMAGE.
26  */
27 
28 #include <sys/cdefs.h>
29 __FBSDID("$FreeBSD: stable/12/lib/libbe/be.c 373261 2023-11-03 04:51:35Z kevans $");
30 
31 #include <sys/param.h>
32 #include <sys/module.h>
33 #include <sys/mount.h>
34 #include <sys/stat.h>
35 #include <sys/ucred.h>
36 #include <sys/queue.h>
37 #include <sys/zfs_context.h>
38 #include <sys/mntent.h>
39 
40 #include <ctype.h>
41 #include <libgen.h>
42 #include <libzfs_core.h>
43 #include <stdio.h>
44 #include <stdlib.h>
45 #include <time.h>
46 #include <unistd.h>
47 
48 #include "be.h"
49 #include "be_impl.h"
50 
51 struct promote_entry {
52 	char				name[BE_MAXPATHLEN];
53 	SLIST_ENTRY(promote_entry)	link;
54 };
55 
56 struct be_destroy_data {
57 	libbe_handle_t			*lbh;
58 	char				target_name[BE_MAXPATHLEN];
59 	char				*snapname;
60 	SLIST_HEAD(, promote_entry)	promotelist;
61 };
62 
63 #if SOON
64 static int be_create_child_noent(libbe_handle_t *lbh, const char *active,
65     const char *child_path);
66 static int be_create_child_cloned(libbe_handle_t *lbh, const char *active);
67 #endif
68 
69 /* Arbitrary... should tune */
70 #define	BE_SNAP_SERIAL_MAX	1024
71 
72 /*
73  * Iterator function for locating the rootfs amongst the children of the
74  * zfs_be_root set by loader(8).  data is expected to be a libbe_handle_t *.
75  */
76 static int
be_locate_rootfs(libbe_handle_t * lbh)77 be_locate_rootfs(libbe_handle_t *lbh)
78 {
79 	struct statfs sfs;
80 	struct mnttab entry;
81 	zfs_handle_t *zfs;
82 
83 	/*
84 	 * Check first if root is ZFS; if not, we'll bail on rootfs capture.
85 	 * Unfortunately needed because zfs_path_to_zhandle will emit to
86 	 * stderr if / isn't actually a ZFS filesystem, which we'd like
87 	 * to avoid.
88 	 */
89 	if (statfs("/", &sfs) == 0) {
90 		statfs2mnttab(&sfs, &entry);
91 		if (strcmp(entry.mnt_fstype, MNTTYPE_ZFS) != 0)
92 			return (1);
93 	} else
94 		return (1);
95 	zfs = zfs_path_to_zhandle(lbh->lzh, "/", ZFS_TYPE_FILESYSTEM);
96 	if (zfs == NULL)
97 		return (1);
98 
99 	strlcpy(lbh->rootfs, zfs_get_name(zfs), sizeof(lbh->rootfs));
100 	zfs_close(zfs);
101 	return (0);
102 }
103 
104 /*
105  * Initializes the libbe context to operate in the root boot environment
106  * dataset, for example, zroot/ROOT.
107  */
108 libbe_handle_t *
libbe_init(const char * root)109 libbe_init(const char *root)
110 {
111 	char altroot[MAXPATHLEN];
112 	libbe_handle_t *lbh;
113 	char *poolname, *pos;
114 	int pnamelen;
115 
116 	lbh = NULL;
117 	poolname = pos = NULL;
118 
119 	/*
120 	 * If the zfs kmod's not loaded then the later libzfs_init() will load
121 	 * the module for us, but that's not desirable for a couple reasons.  If
122 	 * the module's not loaded, there's no pool imported and we're going to
123 	 * fail anyways.  We also don't really want libbe consumers to have that
124 	 * kind of side-effect (module loading) in the general case.
125 	 */
126 	if (modfind("zfs") < 0)
127 		goto err;
128 
129 	if ((lbh = calloc(1, sizeof(libbe_handle_t))) == NULL)
130 		goto err;
131 
132 	if ((lbh->lzh = libzfs_init()) == NULL)
133 		goto err;
134 
135 	/*
136 	 * Grab rootfs, we'll work backwards from there if an optional BE root
137 	 * has not been passed in.
138 	 */
139 	if (be_locate_rootfs(lbh) != 0) {
140 		if (root == NULL)
141 			goto err;
142 		*lbh->rootfs = '\0';
143 	}
144 	if (root == NULL) {
145 		/* Strip off the final slash from rootfs to get the be root */
146 		strlcpy(lbh->root, lbh->rootfs, sizeof(lbh->root));
147 		pos = strrchr(lbh->root, '/');
148 		if (pos == NULL)
149 			goto err;
150 		*pos = '\0';
151 	} else
152 		strlcpy(lbh->root, root, sizeof(lbh->root));
153 
154 	if ((pos = strchr(lbh->root, '/')) == NULL)
155 		goto err;
156 
157 	pnamelen = pos - lbh->root;
158 	poolname = malloc(pnamelen + 1);
159 	if (poolname == NULL)
160 		goto err;
161 
162 	strlcpy(poolname, lbh->root, pnamelen + 1);
163 	if ((lbh->active_phandle = zpool_open(lbh->lzh, poolname)) == NULL)
164 		goto err;
165 	free(poolname);
166 	poolname = NULL;
167 
168 	if (zpool_get_prop(lbh->active_phandle, ZPOOL_PROP_BOOTFS, lbh->bootfs,
169 	    sizeof(lbh->bootfs), NULL, true) != 0)
170 		goto err;
171 
172 	if (zpool_get_prop(lbh->active_phandle, ZPOOL_PROP_ALTROOT,
173 	    altroot, sizeof(altroot), NULL, true) == 0 &&
174 	    strcmp(altroot, "-") != 0)
175 		lbh->altroot_len = strlen(altroot);
176 
177 	return (lbh);
178 err:
179 	if (lbh != NULL) {
180 		if (lbh->active_phandle != NULL)
181 			zpool_close(lbh->active_phandle);
182 		if (lbh->lzh != NULL)
183 			libzfs_fini(lbh->lzh);
184 		free(lbh);
185 	}
186 	free(poolname);
187 	return (NULL);
188 }
189 
190 
191 /*
192  * Free memory allocated by libbe_init()
193  */
194 void
libbe_close(libbe_handle_t * lbh)195 libbe_close(libbe_handle_t *lbh)
196 {
197 
198 	if (lbh->active_phandle != NULL)
199 		zpool_close(lbh->active_phandle);
200 	libzfs_fini(lbh->lzh);
201 	free(lbh);
202 }
203 
204 /*
205  * Proxy through to libzfs for the moment.
206  */
207 void
be_nicenum(uint64_t num,char * buf,size_t buflen)208 be_nicenum(uint64_t num, char *buf, size_t buflen)
209 {
210 
211 	zfs_nicenum(num, buf, buflen);
212 }
213 
214 static bool
be_should_promote_clones(zfs_handle_t * zfs_hdl,struct be_destroy_data * bdd)215 be_should_promote_clones(zfs_handle_t *zfs_hdl, struct be_destroy_data *bdd)
216 {
217 	char *atpos;
218 
219 	if (zfs_get_type(zfs_hdl) != ZFS_TYPE_SNAPSHOT)
220 		return (false);
221 
222 	/*
223 	 * If we're deleting a snapshot, we need to make sure we only promote
224 	 * clones that are derived from one of the snapshots we're deleting,
225 	 * rather than that of a snapshot we're not touching.  This keeps stuff
226 	 * in a consistent state, making sure that we don't error out unless
227 	 * we really need to.
228 	 */
229 	if (bdd->snapname == NULL)
230 		return (true);
231 
232 	atpos = strchr(zfs_get_name(zfs_hdl), '@');
233 	return (strcmp(atpos + 1, bdd->snapname) == 0);
234 }
235 
236 /*
237  * This is executed from be_promote_dependent_clones via zfs_iter_dependents,
238  * It checks if the dependent type is a snapshot then attempts to find any
239  * clones associated with it. Any clones not related to the destroy target are
240  * added to the promote list.
241  */
242 static int
be_dependent_clone_cb(zfs_handle_t * zfs_hdl,void * data)243 be_dependent_clone_cb(zfs_handle_t *zfs_hdl, void *data)
244 {
245 	int err;
246 	bool found;
247 	char *name;
248 	struct nvlist *nvl;
249 	struct nvpair *nvp;
250 	struct be_destroy_data *bdd;
251 	struct promote_entry *entry, *newentry;
252 
253 	nvp = NULL;
254 	err = 0;
255 	bdd = (struct be_destroy_data *)data;
256 
257 	if (be_should_promote_clones(zfs_hdl, bdd) &&
258 	    (nvl = zfs_get_clones_nvl(zfs_hdl)) != NULL) {
259 		while ((nvp = nvlist_next_nvpair(nvl, nvp)) != NULL) {
260 			name = nvpair_name(nvp);
261 
262 			/*
263 			 * Skip if the clone is equal to, or a child of, the
264 			 * destroy target.
265 			 */
266 			if (strncmp(name, bdd->target_name,
267 			    strlen(bdd->target_name)) == 0 ||
268 			    strstr(name, bdd->target_name) == name) {
269 				continue;
270 			}
271 
272 			found = false;
273 			SLIST_FOREACH(entry, &bdd->promotelist, link) {
274 				if (strcmp(entry->name, name) == 0) {
275 					found = true;
276 					break;
277 				}
278 			}
279 
280 			if (found)
281 				continue;
282 
283 			newentry = malloc(sizeof(struct promote_entry));
284 			if (newentry == NULL) {
285 				err = ENOMEM;
286 				break;
287 			}
288 
289 #define	BE_COPY_NAME(entry, src)	\
290 	strlcpy((entry)->name, (src), sizeof((entry)->name))
291 			if (BE_COPY_NAME(newentry, name) >=
292 			    sizeof(newentry->name)) {
293 				/* Shouldn't happen. */
294 				free(newentry);
295 				err = ENAMETOOLONG;
296 				break;
297 			}
298 #undef BE_COPY_NAME
299 
300 			/*
301 			 * We're building up a SLIST here to make sure both that
302 			 * we get the order right and so that we don't
303 			 * inadvertently observe the wrong state by promoting
304 			 * datasets while we're still walking the tree.  The
305 			 * latter can lead to situations where we promote a BE
306 			 * then effectively demote it again.
307 			 */
308 			SLIST_INSERT_HEAD(&bdd->promotelist, newentry, link);
309 		}
310 		nvlist_free(nvl);
311 	}
312 	zfs_close(zfs_hdl);
313 	return (err);
314 }
315 
316 /*
317  * This is called before a destroy, so that any datasets(environments) that are
318  * dependent on this one get promoted before destroying the target.
319  */
320 static int
be_promote_dependent_clones(zfs_handle_t * zfs_hdl,struct be_destroy_data * bdd)321 be_promote_dependent_clones(zfs_handle_t *zfs_hdl, struct be_destroy_data *bdd)
322 {
323 	int err;
324 	zfs_handle_t *clone;
325 	struct promote_entry *entry;
326 
327 	snprintf(bdd->target_name, BE_MAXPATHLEN, "%s/", zfs_get_name(zfs_hdl));
328 	err = zfs_iter_dependents(zfs_hdl, true, be_dependent_clone_cb, bdd);
329 
330 	/*
331 	 * Drain the list and walk away from it if we're only deleting a
332 	 * snapshot.
333 	 */
334 	if (bdd->snapname != NULL && !SLIST_EMPTY(&bdd->promotelist))
335 		err = BE_ERR_HASCLONES;
336 	while (!SLIST_EMPTY(&bdd->promotelist)) {
337 		entry = SLIST_FIRST(&bdd->promotelist);
338 		SLIST_REMOVE_HEAD(&bdd->promotelist, link);
339 
340 #define	ZFS_GRAB_CLONE()	\
341 	zfs_open(bdd->lbh->lzh, entry->name, ZFS_TYPE_FILESYSTEM)
342 		/*
343 		 * Just skip this part on error, we still want to clean up the
344 		 * promotion list after the first error.  We'll then preserve it
345 		 * all the way back.
346 		 */
347 		if (err == 0 && (clone = ZFS_GRAB_CLONE()) != NULL) {
348 			err = zfs_promote(clone);
349 			if (err != 0)
350 				err = BE_ERR_DESTROYMNT;
351 			zfs_close(clone);
352 		}
353 #undef ZFS_GRAB_CLONE
354 		free(entry);
355 	}
356 
357 	return (err);
358 }
359 
360 static int
be_destroy_cb(zfs_handle_t * zfs_hdl,void * data)361 be_destroy_cb(zfs_handle_t *zfs_hdl, void *data)
362 {
363 	char path[BE_MAXPATHLEN];
364 	struct be_destroy_data *bdd;
365 	zfs_handle_t *snap;
366 	int err;
367 
368 	bdd = (struct be_destroy_data *)data;
369 	if (bdd->snapname == NULL) {
370 		err = zfs_iter_children(zfs_hdl, be_destroy_cb, data);
371 		if (err != 0)
372 			return (err);
373 		return (zfs_destroy(zfs_hdl, false));
374 	}
375 	/* If we're dealing with snapshots instead, delete that one alone */
376 	err = zfs_iter_filesystems(zfs_hdl, be_destroy_cb, data);
377 	if (err != 0)
378 		return (err);
379 	/*
380 	 * This part is intentionally glossing over any potential errors,
381 	 * because there's a lot less potential for errors when we're cleaning
382 	 * up snapshots rather than a full deep BE.  The primary error case
383 	 * here being if the snapshot doesn't exist in the first place, which
384 	 * the caller will likely deem insignificant as long as it doesn't
385 	 * exist after the call.  Thus, such a missing snapshot shouldn't jam
386 	 * up the destruction.
387 	 */
388 	snprintf(path, sizeof(path), "%s@%s", zfs_get_name(zfs_hdl),
389 	    bdd->snapname);
390 	if (!zfs_dataset_exists(bdd->lbh->lzh, path, ZFS_TYPE_SNAPSHOT))
391 		return (0);
392 	snap = zfs_open(bdd->lbh->lzh, path, ZFS_TYPE_SNAPSHOT);
393 	if (snap != NULL)
394 		zfs_destroy(snap, false);
395 	return (0);
396 }
397 
398 #define	BE_DESTROY_WANTORIGIN	(BE_DESTROY_ORIGIN | BE_DESTROY_AUTOORIGIN)
399 /*
400  * Destroy the boot environment or snapshot specified by the name
401  * parameter. Options are or'd together with the possible values:
402  * BE_DESTROY_FORCE : forces operation on mounted datasets
403  * BE_DESTROY_ORIGIN: destroy the origin snapshot as well
404  */
405 static int
be_destroy_internal(libbe_handle_t * lbh,const char * name,int options,bool odestroyer)406 be_destroy_internal(libbe_handle_t *lbh, const char *name, int options,
407     bool odestroyer)
408 {
409 	struct be_destroy_data bdd;
410 	char origin[BE_MAXPATHLEN], path[BE_MAXPATHLEN];
411 	zfs_handle_t *fs;
412 	char *snapdelim;
413 	int err, force, mounted;
414 	size_t rootlen;
415 
416 	bdd.lbh = lbh;
417 	bdd.snapname = NULL;
418 	SLIST_INIT(&bdd.promotelist);
419 	force = options & BE_DESTROY_FORCE;
420 	*origin = '\0';
421 
422 	be_root_concat(lbh, name, path);
423 
424 	if ((snapdelim = strchr(path, '@')) == NULL) {
425 		if (!zfs_dataset_exists(lbh->lzh, path, ZFS_TYPE_FILESYSTEM))
426 			return (set_error(lbh, BE_ERR_NOENT));
427 
428 		if (strcmp(path, lbh->rootfs) == 0 ||
429 		    strcmp(path, lbh->bootfs) == 0)
430 			return (set_error(lbh, BE_ERR_DESTROYACT));
431 
432 		fs = zfs_open(lbh->lzh, path, ZFS_TYPE_FILESYSTEM);
433 		if (fs == NULL)
434 			return (set_error(lbh, BE_ERR_ZFSOPEN));
435 
436 		/* Don't destroy a mounted dataset unless force is specified */
437 		if ((mounted = zfs_is_mounted(fs, NULL)) != 0) {
438 			if (force) {
439 				zfs_unmount(fs, NULL, 0);
440 			} else {
441 				free(bdd.snapname);
442 				return (set_error(lbh, BE_ERR_DESTROYMNT));
443 			}
444 		}
445 	} else {
446 		/*
447 		 * If we're initially destroying a snapshot, origin options do
448 		 * not make sense.  If we're destroying the origin snapshot of
449 		 * a BE, we want to maintain the options in case we need to
450 		 * fake success after failing to promote.
451 		 */
452 		if (!odestroyer)
453 			options &= ~BE_DESTROY_WANTORIGIN;
454 		if (!zfs_dataset_exists(lbh->lzh, path, ZFS_TYPE_SNAPSHOT))
455 			return (set_error(lbh, BE_ERR_NOENT));
456 
457 		bdd.snapname = strdup(snapdelim + 1);
458 		if (bdd.snapname == NULL)
459 			return (set_error(lbh, BE_ERR_NOMEM));
460 		*snapdelim = '\0';
461 		fs = zfs_open(lbh->lzh, path, ZFS_TYPE_DATASET);
462 		if (fs == NULL) {
463 			free(bdd.snapname);
464 			return (set_error(lbh, BE_ERR_ZFSOPEN));
465 		}
466 	}
467 
468 	/*
469 	 * Whether we're destroying a BE or a single snapshot, we need to walk
470 	 * the tree of what we're going to destroy and promote everything in our
471 	 * path so that we can make it happen.
472 	 */
473 	if ((err = be_promote_dependent_clones(fs, &bdd)) != 0) {
474 		free(bdd.snapname);
475 
476 		/*
477 		 * If we're just destroying the origin of some other dataset
478 		 * we were invoked to destroy, then we just ignore
479 		 * BE_ERR_HASCLONES and return success unless the caller wanted
480 		 * to force the issue.
481 		 */
482 		if (odestroyer && err == BE_ERR_HASCLONES &&
483 		    (options & BE_DESTROY_AUTOORIGIN) != 0)
484 			return (0);
485 		return (set_error(lbh, err));
486 	}
487 
488 	/*
489 	 * This was deferred until after we promote all of the derivatives so
490 	 * that we grab the new origin after everything's settled down.
491 	 */
492 	if ((options & BE_DESTROY_WANTORIGIN) != 0 &&
493 	    zfs_prop_get(fs, ZFS_PROP_ORIGIN, origin, sizeof(origin),
494 	    NULL, NULL, 0, 1) != 0 &&
495 	    (options & BE_DESTROY_ORIGIN) != 0)
496 		return (set_error(lbh, BE_ERR_NOORIGIN));
497 
498 	/*
499 	 * If the caller wants auto-origin destruction and the origin
500 	 * name matches one of our automatically created snapshot names
501 	 * (i.e. strftime("%F-%T") with a serial at the end), then
502 	 * we'll set the DESTROY_ORIGIN flag and nuke it
503 	 * be_is_auto_snapshot_name is exported from libbe(3) so that
504 	 * the caller can determine if it needs to warn about the origin
505 	 * not being destroyed or not.
506 	 */
507 	if ((options & BE_DESTROY_AUTOORIGIN) != 0 && *origin != '\0' &&
508 	    be_is_auto_snapshot_name(lbh, origin))
509 		options |= BE_DESTROY_ORIGIN;
510 
511 	err = be_destroy_cb(fs, &bdd);
512 	zfs_close(fs);
513 	free(bdd.snapname);
514 	if (err != 0) {
515 		/* Children are still present or the mount is referenced */
516 		if (err == EBUSY)
517 			return (set_error(lbh, BE_ERR_DESTROYMNT));
518 		return (set_error(lbh, BE_ERR_UNKNOWN));
519 	}
520 
521 	if ((options & BE_DESTROY_ORIGIN) == 0)
522 		return (0);
523 
524 	/* The origin can't possibly be shorter than the BE root */
525 	rootlen = strlen(lbh->root);
526 	if (*origin == '\0' || strlen(origin) <= rootlen + 1)
527 		return (set_error(lbh, BE_ERR_INVORIGIN));
528 
529 	/*
530 	 * We'll be chopping off the BE root and running this back through
531 	 * be_destroy, so that we properly handle the origin snapshot whether
532 	 * it be that of a deep BE or not.
533 	 */
534 	if (strncmp(origin, lbh->root, rootlen) != 0 || origin[rootlen] != '/')
535 		return (0);
536 
537 	return (be_destroy_internal(lbh, origin + rootlen + 1,
538 	    options & ~BE_DESTROY_ORIGIN, true));
539 }
540 
541 int
be_destroy(libbe_handle_t * lbh,const char * name,int options)542 be_destroy(libbe_handle_t *lbh, const char *name, int options)
543 {
544 
545 	/*
546 	 * The consumer must not set both BE_DESTROY_AUTOORIGIN and
547 	 * BE_DESTROY_ORIGIN.  Internally, we'll set the latter from the former.
548 	 * The latter should imply that we must succeed at destroying the
549 	 * origin, or complain otherwise.
550 	 */
551 	if ((options & BE_DESTROY_WANTORIGIN) == BE_DESTROY_WANTORIGIN)
552 		return (set_error(lbh, BE_ERR_UNKNOWN));
553 	return (be_destroy_internal(lbh, name, options, false));
554 }
555 
556 static void
be_setup_snapshot_name(libbe_handle_t * lbh,char * buf,size_t buflen)557 be_setup_snapshot_name(libbe_handle_t *lbh, char *buf, size_t buflen)
558 {
559 	time_t rawtime;
560 	int len, serial;
561 
562 	time(&rawtime);
563 	len = strlen(buf);
564 	len += strftime(buf + len, buflen - len, "@%F-%T", localtime(&rawtime));
565 	/* No room for serial... caller will do its best */
566 	if (buflen - len < 2)
567 		return;
568 
569 	for (serial = 0; serial < BE_SNAP_SERIAL_MAX; ++serial) {
570 		snprintf(buf + len, buflen - len, "-%d", serial);
571 		if (!zfs_dataset_exists(lbh->lzh, buf, ZFS_TYPE_SNAPSHOT))
572 			return;
573 	}
574 }
575 
576 bool
be_is_auto_snapshot_name(libbe_handle_t * lbh __unused,const char * name)577 be_is_auto_snapshot_name(libbe_handle_t *lbh __unused, const char *name)
578 {
579 	const char *snap;
580 	int day, hour, minute, month, second, serial, year;
581 
582 	if ((snap = strchr(name, '@')) == NULL)
583 		return (false);
584 	++snap;
585 	/* We'll grab the individual components and do some light validation. */
586 	if (sscanf(snap, "%d-%d-%d-%d:%d:%d-%d", &year, &month, &day, &hour,
587 	    &minute, &second, &serial) != 7)
588 		return (false);
589 	return (year >= 1970) && (month >= 1 && month <= 12) &&
590 	    (day >= 1 && day <= 31) && (hour >= 0 && hour <= 23) &&
591 	    (minute >= 0 && minute <= 59) && (second >= 0 && second <= 60) &&
592 	    serial >= 0;
593 }
594 
595 int
be_snapshot(libbe_handle_t * lbh,const char * source,const char * snap_name,bool recursive,char * result)596 be_snapshot(libbe_handle_t *lbh, const char *source, const char *snap_name,
597     bool recursive, char *result)
598 {
599 	char buf[BE_MAXPATHLEN];
600 	int err;
601 
602 	be_root_concat(lbh, source, buf);
603 
604 	if ((err = be_exists(lbh, buf)) != 0)
605 		return (set_error(lbh, err));
606 
607 	if (snap_name != NULL) {
608 		if (strlcat(buf, "@", sizeof(buf)) >= sizeof(buf))
609 			return (set_error(lbh, BE_ERR_INVALIDNAME));
610 
611 		if (strlcat(buf, snap_name, sizeof(buf)) >= sizeof(buf))
612 			return (set_error(lbh, BE_ERR_INVALIDNAME));
613 
614 		if (result != NULL)
615 			snprintf(result, BE_MAXPATHLEN, "%s@%s", source,
616 			    snap_name);
617 	} else {
618 		be_setup_snapshot_name(lbh, buf, sizeof(buf));
619 
620 		if (result != NULL && strlcpy(result, strrchr(buf, '/') + 1,
621 		    sizeof(buf)) >= sizeof(buf))
622 			return (set_error(lbh, BE_ERR_INVALIDNAME));
623 	}
624 	if ((err = zfs_snapshot(lbh->lzh, buf, recursive, NULL)) != 0) {
625 		switch (err) {
626 		case EZFS_INVALIDNAME:
627 			return (set_error(lbh, BE_ERR_INVALIDNAME));
628 
629 		default:
630 			/*
631 			 * The other errors that zfs_ioc_snapshot might return
632 			 * shouldn't happen if we've set things up properly, so
633 			 * we'll gloss over them and call it UNKNOWN as it will
634 			 * require further triage.
635 			 */
636 			if (errno == ENOTSUP)
637 				return (set_error(lbh, BE_ERR_NOPOOL));
638 			return (set_error(lbh, BE_ERR_UNKNOWN));
639 		}
640 	}
641 
642 	return (BE_ERR_SUCCESS);
643 }
644 
645 
646 /*
647  * Create the boot environment specified by the name parameter
648  */
649 int
be_create(libbe_handle_t * lbh,const char * name)650 be_create(libbe_handle_t *lbh, const char *name)
651 {
652 	int err;
653 
654 	err = be_create_from_existing(lbh, name, be_active_path(lbh));
655 
656 	return (set_error(lbh, err));
657 }
658 
659 static int
be_deep_clone_prop(int prop,void * cb)660 be_deep_clone_prop(int prop, void *cb)
661 {
662 	int err;
663         struct libbe_dccb *dccb;
664 	zprop_source_t src;
665 	char pval[BE_MAXPATHLEN];
666 	char source[BE_MAXPATHLEN];
667 	char *val;
668 
669 	dccb = cb;
670 	/* Skip some properties we don't want to touch */
671 	if (prop == ZFS_PROP_CANMOUNT)
672 		return (ZPROP_CONT);
673 
674 	/* Don't copy readonly properties */
675 	if (zfs_prop_readonly(prop))
676 		return (ZPROP_CONT);
677 
678 	if ((err = zfs_prop_get(dccb->zhp, prop, (char *)&pval,
679 	    sizeof(pval), &src, (char *)&source, sizeof(source), false)))
680 		/* Just continue if we fail to read a property */
681 		return (ZPROP_CONT);
682 
683 	/*
684 	 * Only copy locally defined or received properties.  This continues
685 	 * to avoid temporary/default/local properties intentionally without
686 	 * breaking received datasets.
687 	 */
688 	if (src != ZPROP_SRC_LOCAL && src != ZPROP_SRC_RECEIVED)
689 		return (ZPROP_CONT);
690 
691 	/* Augment mountpoint with altroot, if needed */
692 	val = pval;
693 	if (prop == ZFS_PROP_MOUNTPOINT)
694 		val = be_mountpoint_augmented(dccb->lbh, val);
695 
696 	nvlist_add_string(dccb->props, zfs_prop_to_name(prop), val);
697 
698 	return (ZPROP_CONT);
699 }
700 
701 /*
702  * Return the corresponding boot environment path for a given
703  * dataset path, the constructed path is placed in 'result'.
704  *
705  * example: say our new boot environment name is 'bootenv' and
706  *          the dataset path is 'zroot/ROOT/default/data/set'.
707  *
708  * result should produce: 'zroot/ROOT/bootenv/data/set'
709  */
710 static int
be_get_path(struct libbe_deep_clone * ldc,const char * dspath,char * result,int result_size)711 be_get_path(struct libbe_deep_clone *ldc, const char *dspath, char *result, int result_size)
712 {
713 	char *pos;
714 	char *child_dataset;
715 
716 	/* match the root path for the boot environments */
717 	pos = strstr(dspath, ldc->lbh->root);
718 
719 	/* no match, different pools? */
720 	if (pos == NULL)
721 		return (BE_ERR_BADPATH);
722 
723 	/* root path of the new boot environment */
724 	snprintf(result, result_size, "%s/%s", ldc->lbh->root, ldc->bename);
725 
726         /* gets us to the parent dataset, the +1 consumes a trailing slash */
727 	pos += strlen(ldc->lbh->root) + 1;
728 
729 	/* skip the parent dataset */
730 	if ((child_dataset = strchr(pos, '/')) != NULL)
731 		strlcat(result, child_dataset, result_size);
732 
733 	return (BE_ERR_SUCCESS);
734 }
735 
736 static int
be_clone_cb(zfs_handle_t * ds,void * data)737 be_clone_cb(zfs_handle_t *ds, void *data)
738 {
739 	int err;
740 	char be_path[BE_MAXPATHLEN];
741 	char snap_path[BE_MAXPATHLEN];
742 	const char *dspath;
743 	zfs_handle_t *snap_hdl;
744 	nvlist_t *props;
745 	struct libbe_deep_clone *ldc;
746 	struct libbe_dccb dccb;
747 
748 	ldc = (struct libbe_deep_clone *)data;
749 	dspath = zfs_get_name(ds);
750 
751 	snprintf(snap_path, sizeof(snap_path), "%s@%s", dspath, ldc->snapname);
752 
753 	/* construct the boot environment path from the dataset we're cloning */
754 	if (be_get_path(ldc, dspath, be_path, sizeof(be_path)) != BE_ERR_SUCCESS)
755 		return (set_error(ldc->lbh, BE_ERR_UNKNOWN));
756 
757 	/* the dataset to be created (i.e. the boot environment) already exists */
758 	if (zfs_dataset_exists(ldc->lbh->lzh, be_path, ZFS_TYPE_DATASET))
759 		return (set_error(ldc->lbh, BE_ERR_EXISTS));
760 
761 	/* no snapshot found for this dataset, silently skip it */
762 	if (!zfs_dataset_exists(ldc->lbh->lzh, snap_path, ZFS_TYPE_SNAPSHOT))
763 		return (0);
764 
765 	if ((snap_hdl =
766 	    zfs_open(ldc->lbh->lzh, snap_path, ZFS_TYPE_SNAPSHOT)) == NULL)
767 		return (set_error(ldc->lbh, BE_ERR_ZFSOPEN));
768 
769 	nvlist_alloc(&props, NV_UNIQUE_NAME, KM_SLEEP);
770 	nvlist_add_string(props, "canmount", "noauto");
771 
772 	dccb.lbh = ldc->lbh;
773 	dccb.zhp = ds;
774 	dccb.props = props;
775 	if (zprop_iter(be_deep_clone_prop, &dccb, B_FALSE, B_FALSE,
776 	    ZFS_TYPE_FILESYSTEM) == ZPROP_INVAL)
777 		return (-1);
778 
779 	if ((err = zfs_clone(snap_hdl, be_path, props)) != 0)
780 		return (set_error(ldc->lbh, BE_ERR_ZFSCLONE));
781 
782 	nvlist_free(props);
783 	zfs_close(snap_hdl);
784 
785 	if (ldc->depth_limit == -1 || ldc->depth < ldc->depth_limit) {
786 		ldc->depth++;
787 		err = zfs_iter_filesystems(ds, be_clone_cb, ldc);
788 		ldc->depth--;
789 	}
790 
791 	return (set_error(ldc->lbh, err));
792 }
793 
794 /*
795  * Create a boot environment with a given name from a given snapshot.
796  * Snapshots can be in the format 'zroot/ROOT/default@snapshot' or
797  * 'default@snapshot'. In the latter case, 'default@snapshot' will be prepended
798  * with the root path that libbe was initailized with.
799 */
800 static int
be_clone(libbe_handle_t * lbh,const char * bename,const char * snapshot,int depth)801 be_clone(libbe_handle_t *lbh, const char *bename, const char *snapshot, int depth)
802 {
803 	int err;
804 	char snap_path[BE_MAXPATHLEN];
805 	char *parentname, *snapname;
806 	zfs_handle_t *parent_hdl;
807 	struct libbe_deep_clone ldc;
808 
809         /* ensure the boot environment name is valid */
810 	if ((err = be_validate_name(lbh, bename)) != 0)
811 		return (set_error(lbh, err));
812 
813 	/*
814 	 * prepend the boot environment root path if we're
815 	 * given a partial snapshot name.
816 	 */
817 	if ((err = be_root_concat(lbh, snapshot, snap_path)) != 0)
818 		return (set_error(lbh, err));
819 
820 	/* ensure the snapshot exists */
821 	if ((err = be_validate_snap(lbh, snap_path)) != 0)
822 		return (set_error(lbh, err));
823 
824         /* get a copy of the snapshot path so we can disect it */
825 	if ((parentname = strdup(snap_path)) == NULL)
826 		return (set_error(lbh, BE_ERR_UNKNOWN));
827 
828         /* split dataset name from snapshot name */
829 	snapname = strchr(parentname, '@');
830 	if (snapname == NULL) {
831 		free(parentname);
832 		return (set_error(lbh, BE_ERR_UNKNOWN));
833 	}
834 	*snapname = '\0';
835 	snapname++;
836 
837         /* set-up the boot environment */
838         ldc.lbh = lbh;
839         ldc.bename = bename;
840         ldc.snapname = snapname;
841 	ldc.depth = 0;
842 	ldc.depth_limit = depth;
843 
844         /* the boot environment will be cloned from this dataset */
845 	parent_hdl = zfs_open(lbh->lzh, parentname, ZFS_TYPE_DATASET);
846 
847         /* create the boot environment */
848 	err = be_clone_cb(parent_hdl, &ldc);
849 
850 	free(parentname);
851 	return (set_error(lbh, err));
852 }
853 
854 /*
855  * Create a boot environment from pre-existing snapshot, specifying a depth.
856  */
be_create_depth(libbe_handle_t * lbh,const char * bename,const char * snap,int depth)857 int be_create_depth(libbe_handle_t *lbh, const char *bename,
858 		    const char *snap, int depth)
859 {
860 	return (be_clone(lbh, bename, snap, depth));
861 }
862 
863 /*
864  * Create the boot environment from pre-existing snapshot
865  */
866 int
be_create_from_existing_snap(libbe_handle_t * lbh,const char * bename,const char * snap)867 be_create_from_existing_snap(libbe_handle_t *lbh, const char *bename,
868     const char *snap)
869 {
870 	return (be_clone(lbh, bename, snap, -1));
871 }
872 
873 
874 /*
875  * Create a boot environment from an existing boot environment
876  */
877 int
be_create_from_existing(libbe_handle_t * lbh,const char * bename,const char * old)878 be_create_from_existing(libbe_handle_t *lbh, const char *bename, const char *old)
879 {
880 	int err;
881 	char snap[BE_MAXPATHLEN];
882 
883 	if ((err = be_snapshot(lbh, old, NULL, true, snap)) != 0)
884 		return (set_error(lbh, err));
885 
886         err = be_clone(lbh, bename, snap, -1);
887 
888 	return (set_error(lbh, err));
889 }
890 
891 
892 /*
893  * Verifies that a snapshot has a valid name, exists, and has a mountpoint of
894  * '/'. Returns BE_ERR_SUCCESS (0), upon success, or the relevant BE_ERR_* upon
895  * failure. Does not set the internal library error state.
896  */
897 int
be_validate_snap(libbe_handle_t * lbh,const char * snap_name)898 be_validate_snap(libbe_handle_t *lbh, const char *snap_name)
899 {
900 
901 	if (strlen(snap_name) >= BE_MAXPATHLEN)
902 		return (BE_ERR_PATHLEN);
903 
904 	if (!zfs_name_valid(snap_name, ZFS_TYPE_SNAPSHOT))
905 		return (BE_ERR_INVALIDNAME);
906 
907 	if (!zfs_dataset_exists(lbh->lzh, snap_name,
908 	    ZFS_TYPE_SNAPSHOT))
909 		return (BE_ERR_NOENT);
910 
911 	return (BE_ERR_SUCCESS);
912 }
913 
914 
915 /*
916  * Idempotently appends the name argument to the root boot environment path
917  * and copies the resulting string into the result buffer (which is assumed
918  * to be at least BE_MAXPATHLEN characters long. Returns BE_ERR_SUCCESS upon
919  * success, BE_ERR_PATHLEN if the resulting path is longer than BE_MAXPATHLEN,
920  * or BE_ERR_INVALIDNAME if the name is a path that does not begin with
921  * zfs_be_root. Does not set internal library error state.
922  */
923 int
be_root_concat(libbe_handle_t * lbh,const char * name,char * result)924 be_root_concat(libbe_handle_t *lbh, const char *name, char *result)
925 {
926 	size_t name_len, root_len;
927 
928 	name_len = strlen(name);
929 	root_len = strlen(lbh->root);
930 
931 	/* Act idempotently; return be name if it is already a full path */
932 	if (strrchr(name, '/') != NULL) {
933 		if (strstr(name, lbh->root) != name)
934 			return (BE_ERR_INVALIDNAME);
935 
936 		if (name_len >= BE_MAXPATHLEN)
937 			return (BE_ERR_PATHLEN);
938 
939 		strlcpy(result, name, BE_MAXPATHLEN);
940 		return (BE_ERR_SUCCESS);
941 	} else if (name_len + root_len + 1 < BE_MAXPATHLEN) {
942 		snprintf(result, BE_MAXPATHLEN, "%s/%s", lbh->root,
943 		    name);
944 		return (BE_ERR_SUCCESS);
945 	}
946 
947 	return (BE_ERR_PATHLEN);
948 }
949 
950 
951 /*
952  * Verifies the validity of a boot environment name (A-Za-z0-9-_.). Returns
953  * BE_ERR_SUCCESS (0) if name is valid, otherwise returns BE_ERR_INVALIDNAME
954  * or BE_ERR_PATHLEN.
955  * Does not set internal library error state.
956  */
957 int
be_validate_name(libbe_handle_t * lbh,const char * name)958 be_validate_name(libbe_handle_t *lbh, const char *name)
959 {
960 
961 	/*
962 	 * Impose the additional restriction that the entire dataset name must
963 	 * not exceed the maximum length of a dataset, i.e. MAXNAMELEN.
964 	 */
965 	if (strlen(lbh->root) + 1 + strlen(name) > MAXNAMELEN)
966 		return (BE_ERR_PATHLEN);
967 
968 	if (!zfs_name_valid(name, ZFS_TYPE_DATASET))
969 		return (BE_ERR_INVALIDNAME);
970 
971 	/*
972 	 * ZFS allows spaces in boot environment names, but the kernel can't
973 	 * handle booting from such a dataset right now.  vfs.root.mountfrom
974 	 * is defined to be a space-separated list, and there's no protocol for
975 	 * escaping whitespace in the path component of a dev:path spec.  So
976 	 * while loader can handle this situation alright, it can't safely pass
977 	 * it on to mountroot.
978 	 */
979 	if (strchr(name, ' ') != NULL)
980 		return (BE_ERR_INVALIDNAME);
981 
982 	return (BE_ERR_SUCCESS);
983 }
984 
985 
986 /*
987  * usage
988  */
989 int
be_rename(libbe_handle_t * lbh,const char * old,const char * new)990 be_rename(libbe_handle_t *lbh, const char *old, const char *new)
991 {
992 	char full_old[BE_MAXPATHLEN];
993 	char full_new[BE_MAXPATHLEN];
994 	zfs_handle_t *zfs_hdl;
995 	int err;
996 
997 	/*
998 	 * be_validate_name is documented not to set error state, so we should
999 	 * do so here.
1000 	 */
1001 	if ((err = be_validate_name(lbh, new)) != 0)
1002 		return (set_error(lbh, err));
1003 	if ((err = be_root_concat(lbh, old, full_old)) != 0)
1004 		return (set_error(lbh, err));
1005 	if ((err = be_root_concat(lbh, new, full_new)) != 0)
1006 		return (set_error(lbh, err));
1007 
1008 	if (!zfs_dataset_exists(lbh->lzh, full_old, ZFS_TYPE_DATASET))
1009 		return (set_error(lbh, BE_ERR_NOENT));
1010 
1011 	if (zfs_dataset_exists(lbh->lzh, full_new, ZFS_TYPE_DATASET))
1012 		return (set_error(lbh, BE_ERR_EXISTS));
1013 
1014 	if ((zfs_hdl = zfs_open(lbh->lzh, full_old,
1015 	    ZFS_TYPE_FILESYSTEM)) == NULL)
1016 		return (set_error(lbh, BE_ERR_ZFSOPEN));
1017 
1018 	/* recurse, nounmount, forceunmount */
1019 	struct renameflags flags = {
1020 		.nounmount = 1,
1021 	};
1022 
1023 	err = zfs_rename(zfs_hdl, NULL, full_new, flags);
1024 
1025 	zfs_close(zfs_hdl);
1026 	if (err != 0)
1027 		return (set_error(lbh, BE_ERR_UNKNOWN));
1028 	return (0);
1029 }
1030 
1031 
1032 int
be_export(libbe_handle_t * lbh,const char * bootenv,int fd)1033 be_export(libbe_handle_t *lbh, const char *bootenv, int fd)
1034 {
1035 	char snap_name[BE_MAXPATHLEN];
1036 	char buf[BE_MAXPATHLEN];
1037 	zfs_handle_t *zfs;
1038 	sendflags_t flags = { 0 };
1039 	int err;
1040 
1041 	if ((err = be_snapshot(lbh, bootenv, NULL, true, snap_name)) != 0)
1042 		/* Use the error set by be_snapshot */
1043 		return (err);
1044 
1045 	be_root_concat(lbh, snap_name, buf);
1046 
1047 	if ((zfs = zfs_open(lbh->lzh, buf, ZFS_TYPE_DATASET)) == NULL)
1048 		return (set_error(lbh, BE_ERR_ZFSOPEN));
1049 
1050 	err = zfs_send_one(zfs, NULL, fd, flags);
1051 	zfs_close(zfs);
1052 
1053 	return (err);
1054 }
1055 
1056 
1057 int
be_import(libbe_handle_t * lbh,const char * bootenv,int fd)1058 be_import(libbe_handle_t *lbh, const char *bootenv, int fd)
1059 {
1060 	char buf[BE_MAXPATHLEN];
1061 	nvlist_t *props;
1062 	zfs_handle_t *zfs;
1063 	recvflags_t flags = { .nomount = 1 };
1064 	int err;
1065 
1066 	be_root_concat(lbh, bootenv, buf);
1067 
1068 	if ((err = zfs_receive(lbh->lzh, buf, NULL, &flags, fd, NULL)) != 0) {
1069 		switch (err) {
1070 		case EINVAL:
1071 			return (set_error(lbh, BE_ERR_NOORIGIN));
1072 		case ENOENT:
1073 			return (set_error(lbh, BE_ERR_NOENT));
1074 		case EIO:
1075 			return (set_error(lbh, BE_ERR_IO));
1076 		default:
1077 			return (set_error(lbh, BE_ERR_UNKNOWN));
1078 		}
1079 	}
1080 
1081 	if ((zfs = zfs_open(lbh->lzh, buf, ZFS_TYPE_FILESYSTEM)) == NULL)
1082 		return (set_error(lbh, BE_ERR_ZFSOPEN));
1083 
1084 	nvlist_alloc(&props, NV_UNIQUE_NAME, KM_SLEEP);
1085 	nvlist_add_string(props, "canmount", "noauto");
1086 	nvlist_add_string(props, "mountpoint", "none");
1087 
1088 	err = zfs_prop_set_list(zfs, props);
1089 	nvlist_free(props);
1090 
1091 	zfs_close(zfs);
1092 
1093 	if (err != 0)
1094 		return (set_error(lbh, BE_ERR_UNKNOWN));
1095 
1096 	return (0);
1097 }
1098 
1099 #if SOON
1100 static int
be_create_child_noent(libbe_handle_t * lbh,const char * active,const char * child_path)1101 be_create_child_noent(libbe_handle_t *lbh, const char *active,
1102     const char *child_path)
1103 {
1104 	nvlist_t *props;
1105 	zfs_handle_t *zfs;
1106 	int err;
1107 
1108 	nvlist_alloc(&props, NV_UNIQUE_NAME, KM_SLEEP);
1109 	nvlist_add_string(props, "canmount", "noauto");
1110 	nvlist_add_string(props, "mountpoint", child_path);
1111 
1112 	/* Create */
1113 	if ((err = zfs_create(lbh->lzh, active, ZFS_TYPE_DATASET,
1114 	    props)) != 0) {
1115 		switch (err) {
1116 		case EZFS_EXISTS:
1117 			return (set_error(lbh, BE_ERR_EXISTS));
1118 		case EZFS_NOENT:
1119 			return (set_error(lbh, BE_ERR_NOENT));
1120 		case EZFS_BADTYPE:
1121 		case EZFS_BADVERSION:
1122 			return (set_error(lbh, BE_ERR_NOPOOL));
1123 		case EZFS_BADPROP:
1124 		default:
1125 			/* We set something up wrong, probably... */
1126 			return (set_error(lbh, BE_ERR_UNKNOWN));
1127 		}
1128 	}
1129 	nvlist_free(props);
1130 
1131 	if ((zfs = zfs_open(lbh->lzh, active, ZFS_TYPE_DATASET)) == NULL)
1132 		return (set_error(lbh, BE_ERR_ZFSOPEN));
1133 
1134 	/* Set props */
1135 	if ((err = zfs_prop_set(zfs, "canmount", "noauto")) != 0) {
1136 		zfs_close(zfs);
1137 		/*
1138 		 * Similar to other cases, this shouldn't fail unless we've
1139 		 * done something wrong.  This is a new dataset that shouldn't
1140 		 * have been mounted anywhere between creation and now.
1141 		 */
1142 		if (err == EZFS_NOMEM)
1143 			return (set_error(lbh, BE_ERR_NOMEM));
1144 		return (set_error(lbh, BE_ERR_UNKNOWN));
1145 	}
1146 	zfs_close(zfs);
1147 	return (BE_ERR_SUCCESS);
1148 }
1149 
1150 static int
be_create_child_cloned(libbe_handle_t * lbh,const char * active)1151 be_create_child_cloned(libbe_handle_t *lbh, const char *active)
1152 {
1153 	char buf[BE_MAXPATHLEN], tmp[BE_MAXPATHLEN];;
1154 	zfs_handle_t *zfs;
1155 	int err;
1156 
1157 	/* XXX TODO ? */
1158 
1159 	/*
1160 	 * Establish if the existing path is a zfs dataset or just
1161 	 * the subdirectory of one
1162 	 */
1163 	strlcpy(tmp, "tmp/be_snap.XXXXX", sizeof(tmp));
1164 	if (mktemp(tmp) == NULL)
1165 		return (set_error(lbh, BE_ERR_UNKNOWN));
1166 
1167 	be_root_concat(lbh, tmp, buf);
1168 	printf("Here %s?\n", buf);
1169 	if ((err = zfs_snapshot(lbh->lzh, buf, false, NULL)) != 0) {
1170 		switch (err) {
1171 		case EZFS_INVALIDNAME:
1172 			return (set_error(lbh, BE_ERR_INVALIDNAME));
1173 
1174 		default:
1175 			/*
1176 			 * The other errors that zfs_ioc_snapshot might return
1177 			 * shouldn't happen if we've set things up properly, so
1178 			 * we'll gloss over them and call it UNKNOWN as it will
1179 			 * require further triage.
1180 			 */
1181 			if (errno == ENOTSUP)
1182 				return (set_error(lbh, BE_ERR_NOPOOL));
1183 			return (set_error(lbh, BE_ERR_UNKNOWN));
1184 		}
1185 	}
1186 
1187 	/* Clone */
1188 	if ((zfs = zfs_open(lbh->lzh, buf, ZFS_TYPE_SNAPSHOT)) == NULL)
1189 		return (BE_ERR_ZFSOPEN);
1190 
1191 	if ((err = zfs_clone(zfs, active, NULL)) != 0)
1192 		/* XXX TODO correct error */
1193 		return (set_error(lbh, BE_ERR_UNKNOWN));
1194 
1195 	/* set props */
1196 	zfs_close(zfs);
1197 	return (BE_ERR_SUCCESS);
1198 }
1199 
1200 int
be_add_child(libbe_handle_t * lbh,const char * child_path,bool cp_if_exists)1201 be_add_child(libbe_handle_t *lbh, const char *child_path, bool cp_if_exists)
1202 {
1203 	struct stat sb;
1204 	char active[BE_MAXPATHLEN], buf[BE_MAXPATHLEN];
1205 	nvlist_t *props;
1206 	const char *s;
1207 
1208 	/* Require absolute paths */
1209 	if (*child_path != '/')
1210 		return (set_error(lbh, BE_ERR_BADPATH));
1211 
1212 	strlcpy(active, be_active_path(lbh), BE_MAXPATHLEN);
1213 	strcpy(buf, active);
1214 
1215 	/* Create non-mountable parent dataset(s) */
1216 	s = child_path;
1217 	for (char *p; (p = strchr(s+1, '/')) != NULL; s = p) {
1218 		size_t len = p - s;
1219 		strncat(buf, s, len);
1220 
1221 		nvlist_alloc(&props, NV_UNIQUE_NAME, KM_SLEEP);
1222 		nvlist_add_string(props, "canmount", "off");
1223 		nvlist_add_string(props, "mountpoint", "none");
1224 		zfs_create(lbh->lzh, buf, ZFS_TYPE_DATASET, props);
1225 		nvlist_free(props);
1226 	}
1227 
1228 	/* Path does not exist as a descendent of / yet */
1229 	if (strlcat(active, child_path, BE_MAXPATHLEN) >= BE_MAXPATHLEN)
1230 		return (set_error(lbh, BE_ERR_PATHLEN));
1231 
1232 	if (stat(child_path, &sb) != 0) {
1233 		/* Verify that error is ENOENT */
1234 		if (errno != ENOENT)
1235 			return (set_error(lbh, BE_ERR_UNKNOWN));
1236 		return (be_create_child_noent(lbh, active, child_path));
1237 	} else if (cp_if_exists)
1238 		/* Path is already a descendent of / and should be copied */
1239 		return (be_create_child_cloned(lbh, active));
1240 	return (set_error(lbh, BE_ERR_EXISTS));
1241 }
1242 #endif	/* SOON */
1243 
1244 static int
be_set_nextboot(libbe_handle_t * lbh,nvlist_t * config,uint64_t pool_guid,const char * zfsdev)1245 be_set_nextboot(libbe_handle_t *lbh, nvlist_t *config, uint64_t pool_guid,
1246     const char *zfsdev)
1247 {
1248 	nvlist_t **child;
1249 	uint64_t vdev_guid;
1250 	int c, children;
1251 
1252 	if (nvlist_lookup_nvlist_array(config, ZPOOL_CONFIG_CHILDREN, &child,
1253 	    &children) == 0) {
1254 		for (c = 0; c < children; ++c)
1255 			if (be_set_nextboot(lbh, child[c], pool_guid, zfsdev) != 0)
1256 				return (1);
1257 		return (0);
1258 	}
1259 
1260 	if (nvlist_lookup_uint64(config, ZPOOL_CONFIG_GUID,
1261 	    &vdev_guid) != 0) {
1262 		return (1);
1263 	}
1264 
1265 	if (zpool_nextboot(lbh->lzh, pool_guid, vdev_guid, zfsdev) != 0) {
1266 		perror("ZFS_IOC_NEXTBOOT failed");
1267 		return (1);
1268 	}
1269 
1270 	return (0);
1271 }
1272 
1273 /*
1274  * Deactivate old BE dataset; currently just sets canmount=noauto
1275  */
1276 static int
be_deactivate(libbe_handle_t * lbh,const char * ds)1277 be_deactivate(libbe_handle_t *lbh, const char *ds)
1278 {
1279 	zfs_handle_t *zfs;
1280 
1281 	if ((zfs = zfs_open(lbh->lzh, ds, ZFS_TYPE_DATASET)) == NULL)
1282 		return (1);
1283 	if (zfs_prop_set(zfs, "canmount", "noauto") != 0)
1284 		return (1);
1285 	zfs_close(zfs);
1286 	return (0);
1287 }
1288 
1289 int
be_activate(libbe_handle_t * lbh,const char * bootenv,bool temporary)1290 be_activate(libbe_handle_t *lbh, const char *bootenv, bool temporary)
1291 {
1292 	char be_path[BE_MAXPATHLEN];
1293 	char buf[BE_MAXPATHLEN];
1294 	nvlist_t *config, *dsprops, *vdevs;
1295 	char *origin;
1296 	uint64_t pool_guid;
1297 	zfs_handle_t *zhp;
1298 	int err;
1299 
1300 	be_root_concat(lbh, bootenv, be_path);
1301 
1302 	/* Note: be_exists fails if mountpoint is not / */
1303 	if ((err = be_exists(lbh, be_path)) != 0)
1304 		return (set_error(lbh, err));
1305 
1306 	if (temporary) {
1307 		config = zpool_get_config(lbh->active_phandle, NULL);
1308 		if (config == NULL)
1309 			/* config should be fetchable... */
1310 			return (set_error(lbh, BE_ERR_UNKNOWN));
1311 
1312 		if (nvlist_lookup_uint64(config, ZPOOL_CONFIG_POOL_GUID,
1313 		    &pool_guid) != 0)
1314 			/* Similarly, it shouldn't be possible */
1315 			return (set_error(lbh, BE_ERR_UNKNOWN));
1316 
1317 		/* Expected format according to zfsbootcfg(8) man */
1318 		snprintf(buf, sizeof(buf), "zfs:%s:", be_path);
1319 
1320 		/* We have no config tree */
1321 		if (nvlist_lookup_nvlist(config, ZPOOL_CONFIG_VDEV_TREE,
1322 		    &vdevs) != 0)
1323 			return (set_error(lbh, BE_ERR_NOPOOL));
1324 
1325 		return (be_set_nextboot(lbh, vdevs, pool_guid, buf));
1326 	} else {
1327 		if (be_deactivate(lbh, lbh->bootfs) != 0)
1328 			return (-1);
1329 
1330 		/* Obtain bootenv zpool */
1331 		err = zpool_set_prop(lbh->active_phandle, "bootfs", be_path);
1332 		if (err)
1333 			return (-1);
1334 
1335 		zhp = zfs_open(lbh->lzh, be_path, ZFS_TYPE_FILESYSTEM);
1336 		if (zhp == NULL)
1337 			return (-1);
1338 
1339 		if (be_prop_list_alloc(&dsprops) != 0)
1340 			return (-1);
1341 
1342 		if (be_get_dataset_props(lbh, be_path, dsprops) != 0) {
1343 			nvlist_free(dsprops);
1344 			return (-1);
1345 		}
1346 
1347 		if (nvlist_lookup_string(dsprops, "origin", &origin) == 0)
1348 			err = zfs_promote(zhp);
1349 		nvlist_free(dsprops);
1350 
1351 		zfs_close(zhp);
1352 
1353 		if (err)
1354 			return (-1);
1355 	}
1356 
1357 	return (BE_ERR_SUCCESS);
1358 }
1359