xref: /freebsd/tests/sys/fs/fusefs/utils.cc (revision 2f513db72b034fd5ef7f080b11be5c711c15186a)
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 bool is_unsafe_aio_enabled(void) {
94 	const char *node = "vfs.aio.enable_unsafe";
95 	int val = 0;
96 	size_t size = sizeof(val);
97 
98 	if (sysctlbyname(node, &val, &size, NULL, 0)) {
99 		perror("sysctlbyname");
100 		return (false);
101 	}
102 	return (val != 0);
103 }
104 
105 class FuseEnv: public Environment {
106 	virtual void SetUp() {
107 	}
108 };
109 
110 void FuseTest::SetUp() {
111 	const char *maxbcachebuf_node = "vfs.maxbcachebuf";
112 	const char *maxphys_node = "kern.maxphys";
113 	int val = 0;
114 	size_t size = sizeof(val);
115 
116 	/*
117 	 * XXX check_environment should be called from FuseEnv::SetUp, but
118 	 * can't due to https://github.com/google/googletest/issues/2189
119 	 */
120 	check_environment();
121 	if (IsSkipped())
122 		return;
123 
124 	ASSERT_EQ(0, sysctlbyname(maxbcachebuf_node, &val, &size, NULL, 0))
125 		<< strerror(errno);
126 	m_maxbcachebuf = val;
127 	ASSERT_EQ(0, sysctlbyname(maxphys_node, &val, &size, NULL, 0))
128 		<< strerror(errno);
129 	m_maxphys = val;
130 
131 	try {
132 		m_mock = new MockFS(m_maxreadahead, m_allow_other,
133 			m_default_permissions, m_push_symlinks_in, m_ro,
134 			m_pm, m_init_flags, m_kernel_minor_version,
135 			m_maxwrite, m_async, m_noclusterr, m_time_gran,
136 			m_nointr);
137 		/*
138 		 * FUSE_ACCESS is called almost universally.  Expecting it in
139 		 * each test case would be super-annoying.  Instead, set a
140 		 * default expectation for FUSE_ACCESS and return ENOSYS.
141 		 *
142 		 * Individual test cases can override this expectation since
143 		 * googlemock evaluates expectations in LIFO order.
144 		 */
145 		EXPECT_CALL(*m_mock, process(
146 			ResultOf([=](auto in) {
147 				return (in.header.opcode == FUSE_ACCESS);
148 			}, Eq(true)),
149 			_)
150 		).Times(AnyNumber())
151 		.WillRepeatedly(Invoke(ReturnErrno(ENOSYS)));
152 		/*
153 		 * FUSE_BMAP is called for most test cases that read data.  Set
154 		 * a default expectation and return ENOSYS.
155 		 *
156 		 * Individual test cases can override this expectation since
157 		 * googlemock evaluates expectations in LIFO order.
158 		 */
159 		EXPECT_CALL(*m_mock, process(
160 			ResultOf([=](auto in) {
161 				return (in.header.opcode == FUSE_BMAP);
162 			}, Eq(true)),
163 			_)
164 		).Times(AnyNumber())
165 		.WillRepeatedly(Invoke(ReturnErrno(ENOSYS)));
166 	} catch (std::system_error err) {
167 		FAIL() << err.what();
168 	}
169 }
170 
171 void
172 FuseTest::expect_access(uint64_t ino, mode_t access_mode, int error)
173 {
174 	EXPECT_CALL(*m_mock, process(
175 		ResultOf([=](auto in) {
176 			return (in.header.opcode == FUSE_ACCESS &&
177 				in.header.nodeid == ino &&
178 				in.body.access.mask == access_mode);
179 		}, Eq(true)),
180 		_)
181 	).WillOnce(Invoke(ReturnErrno(error)));
182 }
183 
184 void
185 FuseTest::expect_destroy(int error)
186 {
187 	EXPECT_CALL(*m_mock, process(
188 		ResultOf([=](auto in) {
189 			return (in.header.opcode == FUSE_DESTROY);
190 		}, Eq(true)),
191 		_)
192 	).WillOnce(Invoke( ReturnImmediate([&](auto in, auto& out) {
193 		m_mock->m_quit = true;
194 		out.header.len = sizeof(out.header);
195 		out.header.unique = in.header.unique;
196 		out.header.error = -error;
197 	})));
198 }
199 
200 void
201 FuseTest::expect_flush(uint64_t ino, int times, ProcessMockerT r)
202 {
203 	EXPECT_CALL(*m_mock, process(
204 		ResultOf([=](auto in) {
205 			return (in.header.opcode == FUSE_FLUSH &&
206 				in.header.nodeid == ino);
207 		}, Eq(true)),
208 		_)
209 	).Times(times)
210 	.WillRepeatedly(Invoke(r));
211 }
212 
213 void
214 FuseTest::expect_forget(uint64_t ino, uint64_t nlookup, sem_t *sem)
215 {
216 	EXPECT_CALL(*m_mock, process(
217 		ResultOf([=](auto in) {
218 			return (in.header.opcode == FUSE_FORGET &&
219 				in.header.nodeid == ino &&
220 				in.body.forget.nlookup == nlookup);
221 		}, Eq(true)),
222 		_)
223 	).WillOnce(Invoke([=](auto in __unused, auto &out __unused) {
224 		if (sem != NULL)
225 			sem_post(sem);
226 		/* FUSE_FORGET has no response! */
227 	}));
228 }
229 
230 void FuseTest::expect_getattr(uint64_t ino, uint64_t size)
231 {
232 	EXPECT_CALL(*m_mock, process(
233 		ResultOf([=](auto in) {
234 			return (in.header.opcode == FUSE_GETATTR &&
235 				in.header.nodeid == ino);
236 		}, Eq(true)),
237 		_)
238 	).WillOnce(Invoke(ReturnImmediate([=](auto i __unused, auto& out) {
239 		SET_OUT_HEADER_LEN(out, attr);
240 		out.body.attr.attr.ino = ino;	// Must match nodeid
241 		out.body.attr.attr.mode = S_IFREG | 0644;
242 		out.body.attr.attr.size = size;
243 		out.body.attr.attr_valid = UINT64_MAX;
244 	})));
245 }
246 
247 void FuseTest::expect_lookup(const char *relpath, uint64_t ino, mode_t mode,
248 	uint64_t size, int times, uint64_t attr_valid, uid_t uid, gid_t gid)
249 {
250 	EXPECT_LOOKUP(FUSE_ROOT_ID, relpath)
251 	.Times(times)
252 	.WillRepeatedly(Invoke(
253 		ReturnImmediate([=](auto in __unused, auto& out) {
254 		SET_OUT_HEADER_LEN(out, entry);
255 		out.body.entry.attr.mode = mode;
256 		out.body.entry.nodeid = ino;
257 		out.body.entry.attr.nlink = 1;
258 		out.body.entry.attr_valid = attr_valid;
259 		out.body.entry.attr.size = size;
260 		out.body.entry.attr.uid = uid;
261 		out.body.entry.attr.gid = gid;
262 	})));
263 }
264 
265 void FuseTest::expect_lookup_7_8(const char *relpath, uint64_t ino, mode_t mode,
266 	uint64_t size, int times, uint64_t attr_valid, uid_t uid, gid_t gid)
267 {
268 	EXPECT_LOOKUP(FUSE_ROOT_ID, relpath)
269 	.Times(times)
270 	.WillRepeatedly(Invoke(
271 		ReturnImmediate([=](auto in __unused, auto& out) {
272 		SET_OUT_HEADER_LEN(out, entry_7_8);
273 		out.body.entry.attr.mode = mode;
274 		out.body.entry.nodeid = ino;
275 		out.body.entry.attr.nlink = 1;
276 		out.body.entry.attr_valid = attr_valid;
277 		out.body.entry.attr.size = size;
278 		out.body.entry.attr.uid = uid;
279 		out.body.entry.attr.gid = gid;
280 	})));
281 }
282 
283 void FuseTest::expect_open(uint64_t ino, uint32_t flags, int times)
284 {
285 	EXPECT_CALL(*m_mock, process(
286 		ResultOf([=](auto in) {
287 			return (in.header.opcode == FUSE_OPEN &&
288 				in.header.nodeid == ino);
289 		}, Eq(true)),
290 		_)
291 	).Times(times)
292 	.WillRepeatedly(Invoke(
293 		ReturnImmediate([=](auto in __unused, auto& out) {
294 		out.header.len = sizeof(out.header);
295 		SET_OUT_HEADER_LEN(out, open);
296 		out.body.open.fh = FH;
297 		out.body.open.open_flags = flags;
298 	})));
299 }
300 
301 void FuseTest::expect_opendir(uint64_t ino)
302 {
303 	/* opendir(3) calls fstatfs */
304 	EXPECT_CALL(*m_mock, process(
305 		ResultOf([](auto in) {
306 			return (in.header.opcode == FUSE_STATFS);
307 		}, Eq(true)),
308 		_)
309 	).WillRepeatedly(Invoke(
310 	ReturnImmediate([=](auto i __unused, auto& out) {
311 		SET_OUT_HEADER_LEN(out, statfs);
312 	})));
313 
314 	EXPECT_CALL(*m_mock, process(
315 		ResultOf([=](auto in) {
316 			return (in.header.opcode == FUSE_OPENDIR &&
317 				in.header.nodeid == ino);
318 		}, Eq(true)),
319 		_)
320 	).WillOnce(Invoke(ReturnImmediate([=](auto in __unused, auto& out) {
321 		out.header.len = sizeof(out.header);
322 		SET_OUT_HEADER_LEN(out, open);
323 		out.body.open.fh = FH;
324 	})));
325 }
326 
327 void FuseTest::expect_read(uint64_t ino, uint64_t offset, uint64_t isize,
328 	uint64_t osize, const void *contents, int flags)
329 {
330 	EXPECT_CALL(*m_mock, process(
331 		ResultOf([=](auto in) {
332 			return (in.header.opcode == FUSE_READ &&
333 				in.header.nodeid == ino &&
334 				in.body.read.fh == FH &&
335 				in.body.read.offset == offset &&
336 				in.body.read.size == isize &&
337 				flags == -1 ?
338 					(in.body.read.flags == O_RDONLY ||
339 					 in.body.read.flags == O_RDWR)
340 				: in.body.read.flags == (uint32_t)flags);
341 		}, Eq(true)),
342 		_)
343 	).WillOnce(Invoke(ReturnImmediate([=](auto in __unused, auto& out) {
344 		out.header.len = sizeof(struct fuse_out_header) + osize;
345 		memmove(out.body.bytes, contents, osize);
346 	}))).RetiresOnSaturation();
347 }
348 
349 void FuseTest::expect_readdir(uint64_t ino, uint64_t off,
350 	std::vector<struct dirent> &ents)
351 {
352 	EXPECT_CALL(*m_mock, process(
353 		ResultOf([=](auto in) {
354 			return (in.header.opcode == FUSE_READDIR &&
355 				in.header.nodeid == ino &&
356 				in.body.readdir.fh == FH &&
357 				in.body.readdir.offset == off);
358 		}, Eq(true)),
359 		_)
360 	).WillRepeatedly(Invoke(ReturnImmediate([=](auto in, auto& out) {
361 		struct fuse_dirent *fde = (struct fuse_dirent*)&(out.body);
362 		int i = 0;
363 
364 		out.header.error = 0;
365 		out.header.len = 0;
366 
367 		for (const auto& it: ents) {
368 			size_t entlen, entsize;
369 
370 			fde->ino = it.d_fileno;
371 			fde->off = it.d_off;
372 			fde->type = it.d_type;
373 			fde->namelen = it.d_namlen;
374 			strncpy(fde->name, it.d_name, it.d_namlen);
375 			entlen = FUSE_NAME_OFFSET + fde->namelen;
376 			entsize = FUSE_DIRENT_SIZE(fde);
377 			/*
378 			 * The FUSE protocol does not require zeroing out the
379 			 * unused portion of the name.  But it's a good
380 			 * practice to prevent information disclosure to the
381 			 * FUSE client, even though the client is usually the
382 			 * kernel
383 			 */
384 			memset(fde->name + fde->namelen, 0, entsize - entlen);
385 			if (out.header.len + entsize > in.body.read.size) {
386 				printf("Overflow in readdir expectation: i=%d\n"
387 					, i);
388 				break;
389 			}
390 			out.header.len += entsize;
391 			fde = (struct fuse_dirent*)
392 				((intmax_t*)fde + entsize / sizeof(intmax_t));
393 			i++;
394 		}
395 		out.header.len += sizeof(out.header);
396 	})));
397 
398 }
399 void FuseTest::expect_release(uint64_t ino, uint64_t fh)
400 {
401 	EXPECT_CALL(*m_mock, process(
402 		ResultOf([=](auto in) {
403 			return (in.header.opcode == FUSE_RELEASE &&
404 				in.header.nodeid == ino &&
405 				in.body.release.fh == fh);
406 		}, Eq(true)),
407 		_)
408 	).WillOnce(Invoke(ReturnErrno(0)));
409 }
410 
411 void FuseTest::expect_releasedir(uint64_t ino, ProcessMockerT r)
412 {
413 	EXPECT_CALL(*m_mock, process(
414 		ResultOf([=](auto in) {
415 			return (in.header.opcode == FUSE_RELEASEDIR &&
416 				in.header.nodeid == ino &&
417 				in.body.release.fh == FH);
418 		}, Eq(true)),
419 		_)
420 	).WillOnce(Invoke(r));
421 }
422 
423 void FuseTest::expect_unlink(uint64_t parent, const char *path, int error)
424 {
425 	EXPECT_CALL(*m_mock, process(
426 		ResultOf([=](auto in) {
427 			return (in.header.opcode == FUSE_UNLINK &&
428 				0 == strcmp(path, in.body.unlink) &&
429 				in.header.nodeid == parent);
430 		}, Eq(true)),
431 		_)
432 	).WillOnce(Invoke(ReturnErrno(error)));
433 }
434 
435 void FuseTest::expect_write(uint64_t ino, uint64_t offset, uint64_t isize,
436 	uint64_t osize, uint32_t flags_set, uint32_t flags_unset,
437 	const void *contents)
438 {
439 	EXPECT_CALL(*m_mock, process(
440 		ResultOf([=](auto in) {
441 			const char *buf = (const char*)in.body.bytes +
442 				sizeof(struct fuse_write_in);
443 			bool pid_ok;
444 			uint32_t wf = in.body.write.write_flags;
445 
446 			if (wf & FUSE_WRITE_CACHE)
447 				pid_ok = true;
448 			else
449 				pid_ok = (pid_t)in.header.pid == getpid();
450 
451 			return (in.header.opcode == FUSE_WRITE &&
452 				in.header.nodeid == ino &&
453 				in.body.write.fh == FH &&
454 				in.body.write.offset == offset  &&
455 				in.body.write.size == isize &&
456 				pid_ok &&
457 				(wf & flags_set) == flags_set &&
458 				(wf & flags_unset) == 0 &&
459 				(in.body.write.flags == O_WRONLY ||
460 				 in.body.write.flags == O_RDWR) &&
461 				0 == bcmp(buf, contents, isize));
462 		}, Eq(true)),
463 		_)
464 	).WillOnce(Invoke(ReturnImmediate([=](auto in __unused, auto& out) {
465 		SET_OUT_HEADER_LEN(out, write);
466 		out.body.write.size = osize;
467 	})));
468 }
469 
470 void FuseTest::expect_write_7_8(uint64_t ino, uint64_t offset, uint64_t isize,
471 	uint64_t osize, const void *contents)
472 {
473 	EXPECT_CALL(*m_mock, process(
474 		ResultOf([=](auto in) {
475 			const char *buf = (const char*)in.body.bytes +
476 				FUSE_COMPAT_WRITE_IN_SIZE;
477 			bool pid_ok = (pid_t)in.header.pid == getpid();
478 			return (in.header.opcode == FUSE_WRITE &&
479 				in.header.nodeid == ino &&
480 				in.body.write.fh == FH &&
481 				in.body.write.offset == offset  &&
482 				in.body.write.size == isize &&
483 				pid_ok &&
484 				0 == bcmp(buf, contents, isize));
485 		}, Eq(true)),
486 		_)
487 	).WillOnce(Invoke(ReturnImmediate([=](auto in __unused, auto& out) {
488 		SET_OUT_HEADER_LEN(out, write);
489 		out.body.write.size = osize;
490 	})));
491 }
492 
493 void
494 get_unprivileged_id(uid_t *uid, gid_t *gid)
495 {
496 	struct passwd *pw;
497 	struct group *gr;
498 
499 	/*
500 	 * First try "tests", Kyua's default unprivileged user.  XXX after
501 	 * GoogleTest gains a proper Kyua wrapper, get this with the Kyua API
502 	 */
503 	pw = getpwnam("tests");
504 	if (pw == NULL) {
505 		/* Fall back to "nobody" */
506 		pw = getpwnam("nobody");
507 	}
508 	if (pw == NULL)
509 		GTEST_SKIP() << "Test requires an unprivileged user";
510 	/* Use group "nobody", which is Kyua's default unprivileged group */
511 	gr = getgrnam("nobody");
512 	if (gr == NULL)
513 		GTEST_SKIP() << "Test requires an unprivileged group";
514 	*uid = pw->pw_uid;
515 	*gid = gr->gr_gid;
516 }
517 
518 void
519 FuseTest::fork(bool drop_privs, int *child_status,
520 	std::function<void()> parent_func,
521 	std::function<int()> child_func)
522 {
523 	sem_t *sem;
524 	int mprot = PROT_READ | PROT_WRITE;
525 	int mflags = MAP_ANON | MAP_SHARED;
526 	pid_t child;
527 	uid_t uid;
528 	gid_t gid;
529 
530 	if (drop_privs) {
531 		get_unprivileged_id(&uid, &gid);
532 		if (IsSkipped())
533 			return;
534 	}
535 
536 	sem = (sem_t*)mmap(NULL, sizeof(*sem), mprot, mflags, -1, 0);
537 	ASSERT_NE(MAP_FAILED, sem) << strerror(errno);
538 	ASSERT_EQ(0, sem_init(sem, 1, 0)) << strerror(errno);
539 
540 	if ((child = ::fork()) == 0) {
541 		/* In child */
542 		int err = 0;
543 
544 		if (sem_wait(sem)) {
545 			perror("sem_wait");
546 			err = 1;
547 			goto out;
548 		}
549 
550 		if (drop_privs && 0 != setegid(gid)) {
551 			perror("setegid");
552 			err = 1;
553 			goto out;
554 		}
555 		if (drop_privs && 0 != setreuid(-1, uid)) {
556 			perror("setreuid");
557 			err = 1;
558 			goto out;
559 		}
560 		err = child_func();
561 
562 out:
563 		sem_destroy(sem);
564 		_exit(err);
565 	} else if (child > 0) {
566 		/*
567 		 * In parent.  Cleanup must happen here, because it's still
568 		 * privileged.
569 		 */
570 		m_mock->m_child_pid = child;
571 		ASSERT_NO_FATAL_FAILURE(parent_func());
572 
573 		/* Signal the child process to go */
574 		ASSERT_EQ(0, sem_post(sem)) << strerror(errno);
575 
576 		ASSERT_LE(0, wait(child_status)) << strerror(errno);
577 	} else {
578 		FAIL() << strerror(errno);
579 	}
580 	munmap(sem, sizeof(*sem));
581 	return;
582 }
583 
584 static void usage(char* progname) {
585 	fprintf(stderr, "Usage: %s [-v]\n\t-v increase verbosity\n", progname);
586 	exit(2);
587 }
588 
589 int main(int argc, char **argv) {
590 	int ch;
591 	FuseEnv *fuse_env = new FuseEnv;
592 
593 	InitGoogleTest(&argc, argv);
594 	AddGlobalTestEnvironment(fuse_env);
595 
596 	while ((ch = getopt(argc, argv, "v")) != -1) {
597 		switch (ch) {
598 			case 'v':
599 				verbosity++;
600 				break;
601 			default:
602 				usage(argv[0]);
603 				break;
604 		}
605 	}
606 
607 	return (RUN_ALL_TESTS());
608 }
609