1 /*
2  * CDDL HEADER START
3  *
4  * The contents of this file are subject to the terms of the
5  * Common Development and Distribution License (the "License").
6  * You may not use this file except in compliance with the License.
7  *
8  * You can obtain a copy of the license at usr/src/OPENSOLARIS.LICENSE
9  * or https://opensource.org/licenses/CDDL-1.0.
10  * See the License for the specific language governing permissions
11  * and limitations under the License.
12  *
13  * When distributing Covered Code, include this CDDL HEADER in each
14  * file and include the License file at usr/src/OPENSOLARIS.LICENSE.
15  * If applicable, add the following below this CDDL HEADER, with the
16  * fields enclosed by brackets "[]" replaced with your own identifying
17  * information: Portions Copyright [yyyy] [name of copyright owner]
18  *
19  * CDDL HEADER END
20  */
21 
22 /*
23  * Copyright (c) 2005, 2010, Oracle and/or its affiliates. All rights reserved.
24  * Copyright (c) 2013, 2019 by Delphix. All rights reserved.
25  * Copyright 2014 Nexenta Systems, Inc.  All rights reserved.
26  * Copyright (c) 2019 Datto Inc.
27  */
28 
29 #include <stdio.h>
30 #include <stdlib.h>
31 #include <string.h>
32 #include <unistd.h>
33 #include <stddef.h>
34 #include <libintl.h>
35 #include <libzfs.h>
36 #include <libzutil.h>
37 #include <sys/mntent.h>
38 
39 #include "libzfs_impl.h"
40 
41 static int
42 zfs_iter_clones(zfs_handle_t *zhp, zfs_iter_f func, void *data)
43 {
44 	nvlist_t *nvl = zfs_get_clones_nvl(zhp);
45 	nvpair_t *pair;
46 
47 	if (nvl == NULL)
48 		return (0);
49 
50 	for (pair = nvlist_next_nvpair(nvl, NULL); pair != NULL;
51 	    pair = nvlist_next_nvpair(nvl, pair)) {
52 		zfs_handle_t *clone = zfs_open(zhp->zfs_hdl, nvpair_name(pair),
53 		    ZFS_TYPE_FILESYSTEM | ZFS_TYPE_VOLUME);
54 		if (clone != NULL) {
55 			int err = func(clone, data);
56 			if (err != 0)
57 				return (err);
58 		}
59 	}
60 	return (0);
61 }
62 
63 static int
64 zfs_do_list_ioctl(zfs_handle_t *zhp, int arg, zfs_cmd_t *zc)
65 {
66 	int rc;
67 	uint64_t	orig_cookie;
68 
69 	orig_cookie = zc->zc_cookie;
70 top:
71 	(void) strlcpy(zc->zc_name, zhp->zfs_name, sizeof (zc->zc_name));
72 	rc = zfs_ioctl(zhp->zfs_hdl, arg, zc);
73 
74 	if (rc == -1) {
75 		switch (errno) {
76 		case ENOMEM:
77 			/* expand nvlist memory and try again */
78 			zcmd_expand_dst_nvlist(zhp->zfs_hdl, zc);
79 			zc->zc_cookie = orig_cookie;
80 			goto top;
81 		/*
82 		 * An errno value of ESRCH indicates normal completion.
83 		 * If ENOENT is returned, then the underlying dataset
84 		 * has been removed since we obtained the handle.
85 		 */
86 		case ESRCH:
87 		case ENOENT:
88 			rc = 1;
89 			break;
90 		default:
91 			rc = zfs_standard_error(zhp->zfs_hdl, errno,
92 			    dgettext(TEXT_DOMAIN,
93 			    "cannot iterate filesystems"));
94 			break;
95 		}
96 	}
97 	return (rc);
98 }
99 
100 /*
101  * Iterate over all child filesystems
102  */
103 int
104 zfs_iter_filesystems(zfs_handle_t *zhp, zfs_iter_f func, void *data)
105 {
106 	zfs_cmd_t zc = {"\0"};
107 	zfs_handle_t *nzhp;
108 	int ret;
109 
110 	if (zhp->zfs_type != ZFS_TYPE_FILESYSTEM)
111 		return (0);
112 
113 	zcmd_alloc_dst_nvlist(zhp->zfs_hdl, &zc, 0);
114 
115 	while ((ret = zfs_do_list_ioctl(zhp, ZFS_IOC_DATASET_LIST_NEXT,
116 	    &zc)) == 0) {
117 		/*
118 		 * Silently ignore errors, as the only plausible explanation is
119 		 * that the pool has since been removed.
120 		 */
121 		if ((nzhp = make_dataset_handle_zc(zhp->zfs_hdl,
122 		    &zc)) == NULL) {
123 			continue;
124 		}
125 
126 		if ((ret = func(nzhp, data)) != 0) {
127 			zcmd_free_nvlists(&zc);
128 			return (ret);
129 		}
130 	}
131 	zcmd_free_nvlists(&zc);
132 	return ((ret < 0) ? ret : 0);
133 }
134 
135 /*
136  * Iterate over all snapshots
137  */
138 int
139 zfs_iter_snapshots(zfs_handle_t *zhp, boolean_t simple, zfs_iter_f func,
140     void *data, uint64_t min_txg, uint64_t max_txg)
141 {
142 	zfs_cmd_t zc = {"\0"};
143 	zfs_handle_t *nzhp;
144 	int ret;
145 	nvlist_t *range_nvl = NULL;
146 
147 	if (zhp->zfs_type == ZFS_TYPE_SNAPSHOT ||
148 	    zhp->zfs_type == ZFS_TYPE_BOOKMARK)
149 		return (0);
150 
151 	zc.zc_simple = simple;
152 
153 	zcmd_alloc_dst_nvlist(zhp->zfs_hdl, &zc, 0);
154 
155 	if (min_txg != 0) {
156 		range_nvl = fnvlist_alloc();
157 		fnvlist_add_uint64(range_nvl, SNAP_ITER_MIN_TXG, min_txg);
158 	}
159 	if (max_txg != 0) {
160 		if (range_nvl == NULL)
161 			range_nvl = fnvlist_alloc();
162 		fnvlist_add_uint64(range_nvl, SNAP_ITER_MAX_TXG, max_txg);
163 	}
164 
165 	if (range_nvl != NULL)
166 		zcmd_write_src_nvlist(zhp->zfs_hdl, &zc, range_nvl);
167 
168 	while ((ret = zfs_do_list_ioctl(zhp, ZFS_IOC_SNAPSHOT_LIST_NEXT,
169 	    &zc)) == 0) {
170 
171 		if (simple)
172 			nzhp = make_dataset_simple_handle_zc(zhp, &zc);
173 		else
174 			nzhp = make_dataset_handle_zc(zhp->zfs_hdl, &zc);
175 		if (nzhp == NULL)
176 			continue;
177 
178 		if ((ret = func(nzhp, data)) != 0) {
179 			zcmd_free_nvlists(&zc);
180 			fnvlist_free(range_nvl);
181 			return (ret);
182 		}
183 	}
184 	zcmd_free_nvlists(&zc);
185 	fnvlist_free(range_nvl);
186 	return ((ret < 0) ? ret : 0);
187 }
188 
189 /*
190  * Iterate over all bookmarks
191  */
192 int
193 zfs_iter_bookmarks(zfs_handle_t *zhp, zfs_iter_f func, void *data)
194 {
195 	zfs_handle_t *nzhp;
196 	nvlist_t *props = NULL;
197 	nvlist_t *bmarks = NULL;
198 	int err;
199 	nvpair_t *pair;
200 
201 	if ((zfs_get_type(zhp) & (ZFS_TYPE_SNAPSHOT | ZFS_TYPE_BOOKMARK)) != 0)
202 		return (0);
203 
204 	/* Setup the requested properties nvlist. */
205 	props = fnvlist_alloc();
206 	for (zfs_prop_t p = 0; p < ZFS_NUM_PROPS; p++) {
207 		if (zfs_prop_valid_for_type(p, ZFS_TYPE_BOOKMARK, B_FALSE)) {
208 			fnvlist_add_boolean(props, zfs_prop_to_name(p));
209 		}
210 	}
211 	fnvlist_add_boolean(props, "redact_complete");
212 
213 	if ((err = lzc_get_bookmarks(zhp->zfs_name, props, &bmarks)) != 0)
214 		goto out;
215 
216 	for (pair = nvlist_next_nvpair(bmarks, NULL);
217 	    pair != NULL; pair = nvlist_next_nvpair(bmarks, pair)) {
218 		char name[ZFS_MAX_DATASET_NAME_LEN];
219 		char *bmark_name;
220 		nvlist_t *bmark_props;
221 
222 		bmark_name = nvpair_name(pair);
223 		bmark_props = fnvpair_value_nvlist(pair);
224 
225 		if (snprintf(name, sizeof (name), "%s#%s", zhp->zfs_name,
226 		    bmark_name) >= sizeof (name)) {
227 			err = EINVAL;
228 			goto out;
229 		}
230 
231 		nzhp = make_bookmark_handle(zhp, name, bmark_props);
232 		if (nzhp == NULL)
233 			continue;
234 
235 		if ((err = func(nzhp, data)) != 0)
236 			goto out;
237 	}
238 
239 out:
240 	fnvlist_free(props);
241 	fnvlist_free(bmarks);
242 
243 	return (err);
244 }
245 
246 /*
247  * Routines for dealing with the sorted snapshot functionality
248  */
249 typedef struct zfs_node {
250 	zfs_handle_t	*zn_handle;
251 	avl_node_t	zn_avlnode;
252 } zfs_node_t;
253 
254 static int
255 zfs_sort_snaps(zfs_handle_t *zhp, void *data)
256 {
257 	avl_tree_t *avl = data;
258 	zfs_node_t *node;
259 	zfs_node_t search;
260 
261 	search.zn_handle = zhp;
262 	node = avl_find(avl, &search, NULL);
263 	if (node) {
264 		/*
265 		 * If this snapshot was renamed while we were creating the
266 		 * AVL tree, it's possible that we already inserted it under
267 		 * its old name. Remove the old handle before adding the new
268 		 * one.
269 		 */
270 		zfs_close(node->zn_handle);
271 		avl_remove(avl, node);
272 		free(node);
273 	}
274 
275 	node = zfs_alloc(zhp->zfs_hdl, sizeof (zfs_node_t));
276 	node->zn_handle = zhp;
277 	avl_add(avl, node);
278 
279 	return (0);
280 }
281 
282 static int
283 zfs_snapshot_compare(const void *larg, const void *rarg)
284 {
285 	zfs_handle_t *l = ((zfs_node_t *)larg)->zn_handle;
286 	zfs_handle_t *r = ((zfs_node_t *)rarg)->zn_handle;
287 	uint64_t lcreate, rcreate;
288 
289 	/*
290 	 * Sort them according to creation time.  We use the hidden
291 	 * CREATETXG property to get an absolute ordering of snapshots.
292 	 */
293 	lcreate = zfs_prop_get_int(l, ZFS_PROP_CREATETXG);
294 	rcreate = zfs_prop_get_int(r, ZFS_PROP_CREATETXG);
295 
296 	return (TREE_CMP(lcreate, rcreate));
297 }
298 
299 int
300 zfs_iter_snapshots_sorted(zfs_handle_t *zhp, zfs_iter_f callback, void *data,
301     uint64_t min_txg, uint64_t max_txg)
302 {
303 	int ret = 0;
304 	zfs_node_t *node;
305 	avl_tree_t avl;
306 	void *cookie = NULL;
307 
308 	avl_create(&avl, zfs_snapshot_compare,
309 	    sizeof (zfs_node_t), offsetof(zfs_node_t, zn_avlnode));
310 
311 	ret = zfs_iter_snapshots(zhp, B_FALSE, zfs_sort_snaps, &avl, min_txg,
312 	    max_txg);
313 
314 	for (node = avl_first(&avl); node != NULL; node = AVL_NEXT(&avl, node))
315 		ret |= callback(node->zn_handle, data);
316 
317 	while ((node = avl_destroy_nodes(&avl, &cookie)) != NULL)
318 		free(node);
319 
320 	avl_destroy(&avl);
321 
322 	return (ret);
323 }
324 
325 typedef struct {
326 	char *ssa_first;
327 	char *ssa_last;
328 	boolean_t ssa_seenfirst;
329 	boolean_t ssa_seenlast;
330 	zfs_iter_f ssa_func;
331 	void *ssa_arg;
332 } snapspec_arg_t;
333 
334 static int
335 snapspec_cb(zfs_handle_t *zhp, void *arg)
336 {
337 	snapspec_arg_t *ssa = arg;
338 	const char *shortsnapname;
339 	int err = 0;
340 
341 	if (ssa->ssa_seenlast)
342 		return (0);
343 
344 	shortsnapname = strchr(zfs_get_name(zhp), '@') + 1;
345 	if (!ssa->ssa_seenfirst && strcmp(shortsnapname, ssa->ssa_first) == 0)
346 		ssa->ssa_seenfirst = B_TRUE;
347 	if (strcmp(shortsnapname, ssa->ssa_last) == 0)
348 		ssa->ssa_seenlast = B_TRUE;
349 
350 	if (ssa->ssa_seenfirst) {
351 		err = ssa->ssa_func(zhp, ssa->ssa_arg);
352 	} else {
353 		zfs_close(zhp);
354 	}
355 
356 	return (err);
357 }
358 
359 /*
360  * spec is a string like "A,B%C,D"
361  *
362  * <snaps>, where <snaps> can be:
363  *      <snap>          (single snapshot)
364  *      <snap>%<snap>   (range of snapshots, inclusive)
365  *      %<snap>         (range of snapshots, starting with earliest)
366  *      <snap>%         (range of snapshots, ending with last)
367  *      %               (all snapshots)
368  *      <snaps>[,...]   (comma separated list of the above)
369  *
370  * If a snapshot can not be opened, continue trying to open the others, but
371  * return ENOENT at the end.
372  */
373 int
374 zfs_iter_snapspec(zfs_handle_t *fs_zhp, const char *spec_orig,
375     zfs_iter_f func, void *arg)
376 {
377 	char *buf, *comma_separated, *cp;
378 	int err = 0;
379 	int ret = 0;
380 
381 	buf = zfs_strdup(fs_zhp->zfs_hdl, spec_orig);
382 	cp = buf;
383 
384 	while ((comma_separated = strsep(&cp, ",")) != NULL) {
385 		char *pct = strchr(comma_separated, '%');
386 		if (pct != NULL) {
387 			snapspec_arg_t ssa = { 0 };
388 			ssa.ssa_func = func;
389 			ssa.ssa_arg = arg;
390 
391 			if (pct == comma_separated)
392 				ssa.ssa_seenfirst = B_TRUE;
393 			else
394 				ssa.ssa_first = comma_separated;
395 			*pct = '\0';
396 			ssa.ssa_last = pct + 1;
397 
398 			/*
399 			 * If there is a lastname specified, make sure it
400 			 * exists.
401 			 */
402 			if (ssa.ssa_last[0] != '\0') {
403 				char snapname[ZFS_MAX_DATASET_NAME_LEN];
404 				(void) snprintf(snapname, sizeof (snapname),
405 				    "%s@%s", zfs_get_name(fs_zhp),
406 				    ssa.ssa_last);
407 				if (!zfs_dataset_exists(fs_zhp->zfs_hdl,
408 				    snapname, ZFS_TYPE_SNAPSHOT)) {
409 					ret = ENOENT;
410 					continue;
411 				}
412 			}
413 
414 			err = zfs_iter_snapshots_sorted(fs_zhp,
415 			    snapspec_cb, &ssa, 0, 0);
416 			if (ret == 0)
417 				ret = err;
418 			if (ret == 0 && (!ssa.ssa_seenfirst ||
419 			    (ssa.ssa_last[0] != '\0' && !ssa.ssa_seenlast))) {
420 				ret = ENOENT;
421 			}
422 		} else {
423 			char snapname[ZFS_MAX_DATASET_NAME_LEN];
424 			zfs_handle_t *snap_zhp;
425 			(void) snprintf(snapname, sizeof (snapname), "%s@%s",
426 			    zfs_get_name(fs_zhp), comma_separated);
427 			snap_zhp = make_dataset_handle(fs_zhp->zfs_hdl,
428 			    snapname);
429 			if (snap_zhp == NULL) {
430 				ret = ENOENT;
431 				continue;
432 			}
433 			err = func(snap_zhp, arg);
434 			if (ret == 0)
435 				ret = err;
436 		}
437 	}
438 
439 	free(buf);
440 	return (ret);
441 }
442 
443 /*
444  * Iterate over all children, snapshots and filesystems
445  * Process snapshots before filesystems because they are nearer the input
446  * handle: this is extremely important when used with zfs_iter_f functions
447  * looking for data, following the logic that we would like to find it as soon
448  * and as close as possible.
449  */
450 int
451 zfs_iter_children(zfs_handle_t *zhp, zfs_iter_f func, void *data)
452 {
453 	int ret;
454 
455 	if ((ret = zfs_iter_snapshots(zhp, B_FALSE, func, data, 0, 0)) != 0)
456 		return (ret);
457 
458 	return (zfs_iter_filesystems(zhp, func, data));
459 }
460 
461 
462 typedef struct iter_stack_frame {
463 	struct iter_stack_frame *next;
464 	zfs_handle_t *zhp;
465 } iter_stack_frame_t;
466 
467 typedef struct iter_dependents_arg {
468 	boolean_t first;
469 	boolean_t allowrecursion;
470 	iter_stack_frame_t *stack;
471 	zfs_iter_f func;
472 	void *data;
473 } iter_dependents_arg_t;
474 
475 static int
476 iter_dependents_cb(zfs_handle_t *zhp, void *arg)
477 {
478 	iter_dependents_arg_t *ida = arg;
479 	int err = 0;
480 	boolean_t first = ida->first;
481 	ida->first = B_FALSE;
482 
483 	if (zhp->zfs_type == ZFS_TYPE_SNAPSHOT) {
484 		err = zfs_iter_clones(zhp, iter_dependents_cb, ida);
485 	} else if (zhp->zfs_type != ZFS_TYPE_BOOKMARK) {
486 		iter_stack_frame_t isf;
487 		iter_stack_frame_t *f;
488 
489 		/*
490 		 * check if there is a cycle by seeing if this fs is already
491 		 * on the stack.
492 		 */
493 		for (f = ida->stack; f != NULL; f = f->next) {
494 			if (f->zhp->zfs_dmustats.dds_guid ==
495 			    zhp->zfs_dmustats.dds_guid) {
496 				if (ida->allowrecursion) {
497 					zfs_close(zhp);
498 					return (0);
499 				} else {
500 					zfs_error_aux(zhp->zfs_hdl,
501 					    dgettext(TEXT_DOMAIN,
502 					    "recursive dependency at '%s'"),
503 					    zfs_get_name(zhp));
504 					err = zfs_error(zhp->zfs_hdl,
505 					    EZFS_RECURSIVE,
506 					    dgettext(TEXT_DOMAIN,
507 					    "cannot determine dependent "
508 					    "datasets"));
509 					zfs_close(zhp);
510 					return (err);
511 				}
512 			}
513 		}
514 
515 		isf.zhp = zhp;
516 		isf.next = ida->stack;
517 		ida->stack = &isf;
518 		err = zfs_iter_filesystems(zhp, iter_dependents_cb, ida);
519 		if (err == 0)
520 			err = zfs_iter_snapshots(zhp, B_FALSE,
521 			    iter_dependents_cb, ida, 0, 0);
522 		ida->stack = isf.next;
523 	}
524 
525 	if (!first && err == 0)
526 		err = ida->func(zhp, ida->data);
527 	else
528 		zfs_close(zhp);
529 
530 	return (err);
531 }
532 
533 int
534 zfs_iter_dependents(zfs_handle_t *zhp, boolean_t allowrecursion,
535     zfs_iter_f func, void *data)
536 {
537 	iter_dependents_arg_t ida;
538 	ida.allowrecursion = allowrecursion;
539 	ida.stack = NULL;
540 	ida.func = func;
541 	ida.data = data;
542 	ida.first = B_TRUE;
543 	return (iter_dependents_cb(zfs_handle_dup(zhp), &ida));
544 }
545 
546 /*
547  * Iterate over mounted children of the specified dataset
548  */
549 int
550 zfs_iter_mounted(zfs_handle_t *zhp, zfs_iter_f func, void *data)
551 {
552 	char mnt_prop[ZFS_MAXPROPLEN];
553 	struct mnttab entry;
554 	zfs_handle_t *mtab_zhp;
555 	size_t namelen = strlen(zhp->zfs_name);
556 	FILE *mnttab;
557 	int err = 0;
558 
559 	if ((mnttab = fopen(MNTTAB, "re")) == NULL)
560 		return (ENOENT);
561 
562 	while (err == 0 && getmntent(mnttab, &entry) == 0) {
563 		/* Ignore non-ZFS entries */
564 		if (strcmp(entry.mnt_fstype, MNTTYPE_ZFS) != 0)
565 			continue;
566 
567 		/* Ignore datasets not within the provided dataset */
568 		if (strncmp(entry.mnt_special, zhp->zfs_name, namelen) != 0 ||
569 		    entry.mnt_special[namelen] != '/')
570 			continue;
571 
572 		/* Skip snapshot of any child dataset */
573 		if (strchr(entry.mnt_special, '@') != NULL)
574 			continue;
575 
576 		if ((mtab_zhp = zfs_open(zhp->zfs_hdl, entry.mnt_special,
577 		    ZFS_TYPE_FILESYSTEM)) == NULL)
578 			continue;
579 
580 		/* Ignore legacy mounts as they are user managed */
581 		verify(zfs_prop_get(mtab_zhp, ZFS_PROP_MOUNTPOINT, mnt_prop,
582 		    sizeof (mnt_prop), NULL, NULL, 0, B_FALSE) == 0);
583 		if (strcmp(mnt_prop, "legacy") == 0) {
584 			zfs_close(mtab_zhp);
585 			continue;
586 		}
587 
588 		err = func(mtab_zhp, data);
589 	}
590 
591 	fclose(mnttab);
592 
593 	return (err);
594 }
595