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