xref: /freebsd/tests/sys/fs/fusefs/utils.cc (revision c697fb7f)
1 /*-
2  * SPDX-License-Identifier: BSD-2-Clause-FreeBSD
3  *
4  * Copyright (c) 2019 The FreeBSD Foundation
5  *
6  * This software was developed by BFF Storage Systems, LLC under sponsorship
7  * from the FreeBSD Foundation.
8  *
9  * Redistribution and use in source and binary forms, with or without
10  * modification, are permitted provided that the following conditions
11  * are met:
12  * 1. Redistributions of source code must retain the above copyright
13  *    notice, this list of conditions and the following disclaimer.
14  * 2. Redistributions in binary form must reproduce the above copyright
15  *    notice, this list of conditions and the following disclaimer in the
16  *    documentation and/or other materials provided with the distribution.
17  *
18  * THIS SOFTWARE IS PROVIDED BY THE AUTHOR AND CONTRIBUTORS ``AS IS'' AND
19  * ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
20  * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE
21  * ARE DISCLAIMED. IN NO EVENT SHALL THE AUTHOR OR CONTRIBUTORS BE LIABLE
22  * FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL
23  * DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS
24  * OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION)
25  * HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT
26  * LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY
27  * OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF
28  * SUCH DAMAGE.
29  *
30  * $FreeBSD$
31  */
32 
33 extern "C" {
34 #include <sys/param.h>
35 #include <sys/mman.h>
36 #include <sys/module.h>
37 #include <sys/sysctl.h>
38 #include <sys/wait.h>
39 
40 #include <dirent.h>
41 #include <fcntl.h>
42 #include <grp.h>
43 #include <pwd.h>
44 #include <semaphore.h>
45 #include <unistd.h>
46 }
47 
48 #include <gtest/gtest.h>
49 
50 #include "mockfs.hh"
51 #include "utils.hh"
52 
53 using namespace testing;
54 
55 /*
56  * The default max_write is set to this formula in libfuse, though
57  * individual filesystems can lower it.  The "- 4096" was added in
58  * commit 154ffe2, with the commit message "fix".
59  */
60 const uint32_t libfuse_max_write = 32 * getpagesize() + 0x1000 - 4096;
61 
62 /*
63  * Set the default max_write to a distinct value from MAXPHYS to catch bugs
64  * that confuse the two.
65  */
66 const uint32_t default_max_write = MIN(libfuse_max_write, MAXPHYS / 2);
67 
68 
69 /* Check that fusefs(4) is accessible and the current user can mount(2) */
70 void check_environment()
71 {
72 	const char *devnode = "/dev/fuse";
73 	const char *usermount_node = "vfs.usermount";
74 	int usermount_val = 0;
75 	size_t usermount_size = sizeof(usermount_val);
76 	if (eaccess(devnode, R_OK | W_OK)) {
77 		if (errno == ENOENT) {
78 			GTEST_SKIP() << devnode << " does not exist";
79 		} else if (errno == EACCES) {
80 			GTEST_SKIP() << devnode <<
81 			    " is not accessible by the current user";
82 		} else {
83 			GTEST_SKIP() << strerror(errno);
84 		}
85 	}
86 	ASSERT_EQ(sysctlbyname(usermount_node, &usermount_val, &usermount_size,
87 			       NULL, 0),
88 		  0);;
89 	if (geteuid() != 0 && !usermount_val)
90 		GTEST_SKIP() << "current user is not allowed to mount";
91 }
92 
93 const char *cache_mode_to_s(enum cache_mode cm) {
94 	switch (cm) {
95 	case Uncached:
96 		return "Uncached";
97 	case Writethrough:
98 		return "Writethrough";
99 	case Writeback:
100 		return "Writeback";
101 	case WritebackAsync:
102 		return "WritebackAsync";
103 	default:
104 		return "Unknown";
105 	}
106 }
107 
108 bool is_unsafe_aio_enabled(void) {
109 	const char *node = "vfs.aio.enable_unsafe";
110 	int val = 0;
111 	size_t size = sizeof(val);
112 
113 	if (sysctlbyname(node, &val, &size, NULL, 0)) {
114 		perror("sysctlbyname");
115 		return (false);
116 	}
117 	return (val != 0);
118 }
119 
120 class FuseEnv: public Environment {
121 	virtual void SetUp() {
122 	}
123 };
124 
125 void FuseTest::SetUp() {
126 	const char *maxbcachebuf_node = "vfs.maxbcachebuf";
127 	const char *maxphys_node = "kern.maxphys";
128 	int val = 0;
129 	size_t size = sizeof(val);
130 
131 	/*
132 	 * XXX check_environment should be called from FuseEnv::SetUp, but
133 	 * can't due to https://github.com/google/googletest/issues/2189
134 	 */
135 	check_environment();
136 	if (IsSkipped())
137 		return;
138 
139 	ASSERT_EQ(0, sysctlbyname(maxbcachebuf_node, &val, &size, NULL, 0))
140 		<< strerror(errno);
141 	m_maxbcachebuf = val;
142 	ASSERT_EQ(0, sysctlbyname(maxphys_node, &val, &size, NULL, 0))
143 		<< strerror(errno);
144 	m_maxphys = val;
145 
146 	try {
147 		m_mock = new MockFS(m_maxreadahead, m_allow_other,
148 			m_default_permissions, m_push_symlinks_in, m_ro,
149 			m_pm, m_init_flags, m_kernel_minor_version,
150 			m_maxwrite, m_async, m_noclusterr, m_time_gran,
151 			m_nointr);
152 		/*
153 		 * FUSE_ACCESS is called almost universally.  Expecting it in
154 		 * each test case would be super-annoying.  Instead, set a
155 		 * default expectation for FUSE_ACCESS and return ENOSYS.
156 		 *
157 		 * Individual test cases can override this expectation since
158 		 * googlemock evaluates expectations in LIFO order.
159 		 */
160 		EXPECT_CALL(*m_mock, process(
161 			ResultOf([=](auto in) {
162 				return (in.header.opcode == FUSE_ACCESS);
163 			}, Eq(true)),
164 			_)
165 		).Times(AnyNumber())
166 		.WillRepeatedly(Invoke(ReturnErrno(ENOSYS)));
167 		/*
168 		 * FUSE_BMAP is called for most test cases that read data.  Set
169 		 * a default expectation and return ENOSYS.
170 		 *
171 		 * Individual test cases can override this expectation since
172 		 * googlemock evaluates expectations in LIFO order.
173 		 */
174 		EXPECT_CALL(*m_mock, process(
175 			ResultOf([=](auto in) {
176 				return (in.header.opcode == FUSE_BMAP);
177 			}, Eq(true)),
178 			_)
179 		).Times(AnyNumber())
180 		.WillRepeatedly(Invoke(ReturnErrno(ENOSYS)));
181 	} catch (std::system_error err) {
182 		FAIL() << err.what();
183 	}
184 }
185 
186 void
187 FuseTest::expect_access(uint64_t ino, mode_t access_mode, int error)
188 {
189 	EXPECT_CALL(*m_mock, process(
190 		ResultOf([=](auto in) {
191 			return (in.header.opcode == FUSE_ACCESS &&
192 				in.header.nodeid == ino &&
193 				in.body.access.mask == access_mode);
194 		}, Eq(true)),
195 		_)
196 	).WillOnce(Invoke(ReturnErrno(error)));
197 }
198 
199 void
200 FuseTest::expect_destroy(int error)
201 {
202 	EXPECT_CALL(*m_mock, process(
203 		ResultOf([=](auto in) {
204 			return (in.header.opcode == FUSE_DESTROY);
205 		}, Eq(true)),
206 		_)
207 	).WillOnce(Invoke( ReturnImmediate([&](auto in, auto& out) {
208 		m_mock->m_quit = true;
209 		out.header.len = sizeof(out.header);
210 		out.header.unique = in.header.unique;
211 		out.header.error = -error;
212 	})));
213 }
214 
215 void
216 FuseTest::expect_flush(uint64_t ino, int times, ProcessMockerT r)
217 {
218 	EXPECT_CALL(*m_mock, process(
219 		ResultOf([=](auto in) {
220 			return (in.header.opcode == FUSE_FLUSH &&
221 				in.header.nodeid == ino);
222 		}, Eq(true)),
223 		_)
224 	).Times(times)
225 	.WillRepeatedly(Invoke(r));
226 }
227 
228 void
229 FuseTest::expect_forget(uint64_t ino, uint64_t nlookup, sem_t *sem)
230 {
231 	EXPECT_CALL(*m_mock, process(
232 		ResultOf([=](auto in) {
233 			return (in.header.opcode == FUSE_FORGET &&
234 				in.header.nodeid == ino &&
235 				in.body.forget.nlookup == nlookup);
236 		}, Eq(true)),
237 		_)
238 	).WillOnce(Invoke([=](auto in __unused, auto &out __unused) {
239 		if (sem != NULL)
240 			sem_post(sem);
241 		/* FUSE_FORGET has no response! */
242 	}));
243 }
244 
245 void FuseTest::expect_getattr(uint64_t ino, uint64_t size)
246 {
247 	EXPECT_CALL(*m_mock, process(
248 		ResultOf([=](auto in) {
249 			return (in.header.opcode == FUSE_GETATTR &&
250 				in.header.nodeid == ino);
251 		}, Eq(true)),
252 		_)
253 	).WillOnce(Invoke(ReturnImmediate([=](auto i __unused, auto& out) {
254 		SET_OUT_HEADER_LEN(out, attr);
255 		out.body.attr.attr.ino = ino;	// Must match nodeid
256 		out.body.attr.attr.mode = S_IFREG | 0644;
257 		out.body.attr.attr.size = size;
258 		out.body.attr.attr_valid = UINT64_MAX;
259 	})));
260 }
261 
262 void FuseTest::expect_lookup(const char *relpath, uint64_t ino, mode_t mode,
263 	uint64_t size, int times, uint64_t attr_valid, uid_t uid, gid_t gid)
264 {
265 	EXPECT_LOOKUP(FUSE_ROOT_ID, relpath)
266 	.Times(times)
267 	.WillRepeatedly(Invoke(
268 		ReturnImmediate([=](auto in __unused, auto& out) {
269 		SET_OUT_HEADER_LEN(out, entry);
270 		out.body.entry.attr.mode = mode;
271 		out.body.entry.nodeid = ino;
272 		out.body.entry.attr.nlink = 1;
273 		out.body.entry.attr_valid = attr_valid;
274 		out.body.entry.attr.size = size;
275 		out.body.entry.attr.uid = uid;
276 		out.body.entry.attr.gid = gid;
277 	})));
278 }
279 
280 void FuseTest::expect_lookup_7_8(const char *relpath, uint64_t ino, mode_t mode,
281 	uint64_t size, int times, uint64_t attr_valid, uid_t uid, gid_t gid)
282 {
283 	EXPECT_LOOKUP(FUSE_ROOT_ID, relpath)
284 	.Times(times)
285 	.WillRepeatedly(Invoke(
286 		ReturnImmediate([=](auto in __unused, auto& out) {
287 		SET_OUT_HEADER_LEN(out, entry_7_8);
288 		out.body.entry.attr.mode = mode;
289 		out.body.entry.nodeid = ino;
290 		out.body.entry.attr.nlink = 1;
291 		out.body.entry.attr_valid = attr_valid;
292 		out.body.entry.attr.size = size;
293 		out.body.entry.attr.uid = uid;
294 		out.body.entry.attr.gid = gid;
295 	})));
296 }
297 
298 void FuseTest::expect_open(uint64_t ino, uint32_t flags, int times)
299 {
300 	EXPECT_CALL(*m_mock, process(
301 		ResultOf([=](auto in) {
302 			return (in.header.opcode == FUSE_OPEN &&
303 				in.header.nodeid == ino);
304 		}, Eq(true)),
305 		_)
306 	).Times(times)
307 	.WillRepeatedly(Invoke(
308 		ReturnImmediate([=](auto in __unused, auto& out) {
309 		out.header.len = sizeof(out.header);
310 		SET_OUT_HEADER_LEN(out, open);
311 		out.body.open.fh = FH;
312 		out.body.open.open_flags = flags;
313 	})));
314 }
315 
316 void FuseTest::expect_opendir(uint64_t ino)
317 {
318 	/* opendir(3) calls fstatfs */
319 	EXPECT_CALL(*m_mock, process(
320 		ResultOf([](auto in) {
321 			return (in.header.opcode == FUSE_STATFS);
322 		}, Eq(true)),
323 		_)
324 	).WillRepeatedly(Invoke(
325 	ReturnImmediate([=](auto i __unused, auto& out) {
326 		SET_OUT_HEADER_LEN(out, statfs);
327 	})));
328 
329 	EXPECT_CALL(*m_mock, process(
330 		ResultOf([=](auto in) {
331 			return (in.header.opcode == FUSE_OPENDIR &&
332 				in.header.nodeid == ino);
333 		}, Eq(true)),
334 		_)
335 	).WillOnce(Invoke(ReturnImmediate([=](auto in __unused, auto& out) {
336 		out.header.len = sizeof(out.header);
337 		SET_OUT_HEADER_LEN(out, open);
338 		out.body.open.fh = FH;
339 	})));
340 }
341 
342 void FuseTest::expect_read(uint64_t ino, uint64_t offset, uint64_t isize,
343 	uint64_t osize, const void *contents, int flags)
344 {
345 	EXPECT_CALL(*m_mock, process(
346 		ResultOf([=](auto in) {
347 			return (in.header.opcode == FUSE_READ &&
348 				in.header.nodeid == ino &&
349 				in.body.read.fh == FH &&
350 				in.body.read.offset == offset &&
351 				in.body.read.size == isize &&
352 				flags == -1 ?
353 					(in.body.read.flags == O_RDONLY ||
354 					 in.body.read.flags == O_RDWR)
355 				: in.body.read.flags == (uint32_t)flags);
356 		}, Eq(true)),
357 		_)
358 	).WillOnce(Invoke(ReturnImmediate([=](auto in __unused, auto& out) {
359 		out.header.len = sizeof(struct fuse_out_header) + osize;
360 		memmove(out.body.bytes, contents, osize);
361 	}))).RetiresOnSaturation();
362 }
363 
364 void FuseTest::expect_readdir(uint64_t ino, uint64_t off,
365 	std::vector<struct dirent> &ents)
366 {
367 	EXPECT_CALL(*m_mock, process(
368 		ResultOf([=](auto in) {
369 			return (in.header.opcode == FUSE_READDIR &&
370 				in.header.nodeid == ino &&
371 				in.body.readdir.fh == FH &&
372 				in.body.readdir.offset == off);
373 		}, Eq(true)),
374 		_)
375 	).WillRepeatedly(Invoke(ReturnImmediate([=](auto in, auto& out) {
376 		struct fuse_dirent *fde = (struct fuse_dirent*)&(out.body);
377 		int i = 0;
378 
379 		out.header.error = 0;
380 		out.header.len = 0;
381 
382 		for (const auto& it: ents) {
383 			size_t entlen, entsize;
384 
385 			fde->ino = it.d_fileno;
386 			fde->off = it.d_off;
387 			fde->type = it.d_type;
388 			fde->namelen = it.d_namlen;
389 			strncpy(fde->name, it.d_name, it.d_namlen);
390 			entlen = FUSE_NAME_OFFSET + fde->namelen;
391 			entsize = FUSE_DIRENT_SIZE(fde);
392 			/*
393 			 * The FUSE protocol does not require zeroing out the
394 			 * unused portion of the name.  But it's a good
395 			 * practice to prevent information disclosure to the
396 			 * FUSE client, even though the client is usually the
397 			 * kernel
398 			 */
399 			memset(fde->name + fde->namelen, 0, entsize - entlen);
400 			if (out.header.len + entsize > in.body.read.size) {
401 				printf("Overflow in readdir expectation: i=%d\n"
402 					, i);
403 				break;
404 			}
405 			out.header.len += entsize;
406 			fde = (struct fuse_dirent*)
407 				((intmax_t*)fde + entsize / sizeof(intmax_t));
408 			i++;
409 		}
410 		out.header.len += sizeof(out.header);
411 	})));
412 
413 }
414 void FuseTest::expect_release(uint64_t ino, uint64_t fh)
415 {
416 	EXPECT_CALL(*m_mock, process(
417 		ResultOf([=](auto in) {
418 			return (in.header.opcode == FUSE_RELEASE &&
419 				in.header.nodeid == ino &&
420 				in.body.release.fh == fh);
421 		}, Eq(true)),
422 		_)
423 	).WillOnce(Invoke(ReturnErrno(0)));
424 }
425 
426 void FuseTest::expect_releasedir(uint64_t ino, ProcessMockerT r)
427 {
428 	EXPECT_CALL(*m_mock, process(
429 		ResultOf([=](auto in) {
430 			return (in.header.opcode == FUSE_RELEASEDIR &&
431 				in.header.nodeid == ino &&
432 				in.body.release.fh == FH);
433 		}, Eq(true)),
434 		_)
435 	).WillOnce(Invoke(r));
436 }
437 
438 void FuseTest::expect_unlink(uint64_t parent, const char *path, int error)
439 {
440 	EXPECT_CALL(*m_mock, process(
441 		ResultOf([=](auto in) {
442 			return (in.header.opcode == FUSE_UNLINK &&
443 				0 == strcmp(path, in.body.unlink) &&
444 				in.header.nodeid == parent);
445 		}, Eq(true)),
446 		_)
447 	).WillOnce(Invoke(ReturnErrno(error)));
448 }
449 
450 void FuseTest::expect_write(uint64_t ino, uint64_t offset, uint64_t isize,
451 	uint64_t osize, uint32_t flags_set, uint32_t flags_unset,
452 	const void *contents)
453 {
454 	EXPECT_CALL(*m_mock, process(
455 		ResultOf([=](auto in) {
456 			const char *buf = (const char*)in.body.bytes +
457 				sizeof(struct fuse_write_in);
458 			bool pid_ok;
459 			uint32_t wf = in.body.write.write_flags;
460 
461 			if (wf & FUSE_WRITE_CACHE)
462 				pid_ok = true;
463 			else
464 				pid_ok = (pid_t)in.header.pid == getpid();
465 
466 			return (in.header.opcode == FUSE_WRITE &&
467 				in.header.nodeid == ino &&
468 				in.body.write.fh == FH &&
469 				in.body.write.offset == offset  &&
470 				in.body.write.size == isize &&
471 				pid_ok &&
472 				(wf & flags_set) == flags_set &&
473 				(wf & flags_unset) == 0 &&
474 				(in.body.write.flags == O_WRONLY ||
475 				 in.body.write.flags == O_RDWR) &&
476 				0 == bcmp(buf, contents, isize));
477 		}, Eq(true)),
478 		_)
479 	).WillOnce(Invoke(ReturnImmediate([=](auto in __unused, auto& out) {
480 		SET_OUT_HEADER_LEN(out, write);
481 		out.body.write.size = osize;
482 	})));
483 }
484 
485 void FuseTest::expect_write_7_8(uint64_t ino, uint64_t offset, uint64_t isize,
486 	uint64_t osize, const void *contents)
487 {
488 	EXPECT_CALL(*m_mock, process(
489 		ResultOf([=](auto in) {
490 			const char *buf = (const char*)in.body.bytes +
491 				FUSE_COMPAT_WRITE_IN_SIZE;
492 			bool pid_ok = (pid_t)in.header.pid == getpid();
493 			return (in.header.opcode == FUSE_WRITE &&
494 				in.header.nodeid == ino &&
495 				in.body.write.fh == FH &&
496 				in.body.write.offset == offset  &&
497 				in.body.write.size == isize &&
498 				pid_ok &&
499 				0 == bcmp(buf, contents, isize));
500 		}, Eq(true)),
501 		_)
502 	).WillOnce(Invoke(ReturnImmediate([=](auto in __unused, auto& out) {
503 		SET_OUT_HEADER_LEN(out, write);
504 		out.body.write.size = osize;
505 	})));
506 }
507 
508 void
509 get_unprivileged_id(uid_t *uid, gid_t *gid)
510 {
511 	struct passwd *pw;
512 	struct group *gr;
513 
514 	/*
515 	 * First try "tests", Kyua's default unprivileged user.  XXX after
516 	 * GoogleTest gains a proper Kyua wrapper, get this with the Kyua API
517 	 */
518 	pw = getpwnam("tests");
519 	if (pw == NULL) {
520 		/* Fall back to "nobody" */
521 		pw = getpwnam("nobody");
522 	}
523 	if (pw == NULL)
524 		GTEST_SKIP() << "Test requires an unprivileged user";
525 	/* Use group "nobody", which is Kyua's default unprivileged group */
526 	gr = getgrnam("nobody");
527 	if (gr == NULL)
528 		GTEST_SKIP() << "Test requires an unprivileged group";
529 	*uid = pw->pw_uid;
530 	*gid = gr->gr_gid;
531 }
532 
533 void
534 FuseTest::fork(bool drop_privs, int *child_status,
535 	std::function<void()> parent_func,
536 	std::function<int()> child_func)
537 {
538 	sem_t *sem;
539 	int mprot = PROT_READ | PROT_WRITE;
540 	int mflags = MAP_ANON | MAP_SHARED;
541 	pid_t child;
542 	uid_t uid;
543 	gid_t gid;
544 
545 	if (drop_privs) {
546 		get_unprivileged_id(&uid, &gid);
547 		if (IsSkipped())
548 			return;
549 	}
550 
551 	sem = (sem_t*)mmap(NULL, sizeof(*sem), mprot, mflags, -1, 0);
552 	ASSERT_NE(MAP_FAILED, sem) << strerror(errno);
553 	ASSERT_EQ(0, sem_init(sem, 1, 0)) << strerror(errno);
554 
555 	if ((child = ::fork()) == 0) {
556 		/* In child */
557 		int err = 0;
558 
559 		if (sem_wait(sem)) {
560 			perror("sem_wait");
561 			err = 1;
562 			goto out;
563 		}
564 
565 		if (drop_privs && 0 != setegid(gid)) {
566 			perror("setegid");
567 			err = 1;
568 			goto out;
569 		}
570 		if (drop_privs && 0 != setreuid(-1, uid)) {
571 			perror("setreuid");
572 			err = 1;
573 			goto out;
574 		}
575 		err = child_func();
576 
577 out:
578 		sem_destroy(sem);
579 		_exit(err);
580 	} else if (child > 0) {
581 		/*
582 		 * In parent.  Cleanup must happen here, because it's still
583 		 * privileged.
584 		 */
585 		m_mock->m_child_pid = child;
586 		ASSERT_NO_FATAL_FAILURE(parent_func());
587 
588 		/* Signal the child process to go */
589 		ASSERT_EQ(0, sem_post(sem)) << strerror(errno);
590 
591 		ASSERT_LE(0, wait(child_status)) << strerror(errno);
592 	} else {
593 		FAIL() << strerror(errno);
594 	}
595 	munmap(sem, sizeof(*sem));
596 	return;
597 }
598 
599 static void usage(char* progname) {
600 	fprintf(stderr, "Usage: %s [-v]\n\t-v increase verbosity\n", progname);
601 	exit(2);
602 }
603 
604 int main(int argc, char **argv) {
605 	int ch;
606 	FuseEnv *fuse_env = new FuseEnv;
607 
608 	InitGoogleTest(&argc, argv);
609 	AddGlobalTestEnvironment(fuse_env);
610 
611 	while ((ch = getopt(argc, argv, "v")) != -1) {
612 		switch (ch) {
613 			case 'v':
614 				verbosity++;
615 				break;
616 			default:
617 				usage(argv[0]);
618 				break;
619 		}
620 	}
621 
622 	return (RUN_ALL_TESTS());
623 }
624