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