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