]> CyberLeo.Net >> Repos - FreeBSD/FreeBSD.git/blob - tests/sys/fs/fusefs/utils.cc
fusefs: deduplicate code in the allow_other test
[FreeBSD/FreeBSD.git] / tests / sys / fs / fusefs / utils.cc
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
31 extern "C" {
32 #include <sys/param.h>
33 #include <sys/mman.h>
34 #include <sys/module.h>
35 #include <sys/sysctl.h>
36 #include <sys/wait.h>
37
38 #include <pwd.h>
39 #include <semaphore.h>
40 #include <unistd.h>
41 }
42
43 #include <gtest/gtest.h>
44
45 #include "mockfs.hh"
46 #include "utils.hh"
47
48 using namespace testing;
49
50 /* Check that fusefs(4) is accessible and the current user can mount(2) */
51 void check_environment()
52 {
53         const char *devnode = "/dev/fuse";
54         const char *usermount_node = "vfs.usermount";
55         int usermount_val = 0;
56         size_t usermount_size = sizeof(usermount_val);
57         if (eaccess(devnode, R_OK | W_OK)) {
58                 if (errno == ENOENT) {
59                         GTEST_SKIP() << devnode << " does not exist";
60                 } else if (errno == EACCES) {
61                         GTEST_SKIP() << devnode <<
62                             " is not accessible by the current user";
63                 } else {
64                         GTEST_SKIP() << strerror(errno);
65                 }
66         }
67         sysctlbyname(usermount_node, &usermount_val, &usermount_size,
68                      NULL, 0);
69         if (geteuid() != 0 && !usermount_val)
70                 GTEST_SKIP() << "current user is not allowed to mount";
71 }
72
73 class FuseEnv: public Environment {
74         virtual void SetUp() {
75         }
76 };
77
78 void FuseTest::SetUp() {
79         const char *node = "vfs.maxbcachebuf";
80         int val = 0;
81         size_t size = sizeof(val);
82
83         /*
84          * XXX check_environment should be called from FuseEnv::SetUp, but
85          * can't due to https://github.com/google/googletest/issues/2189
86          */
87         check_environment();
88         if (IsSkipped())
89                 return;
90
91         ASSERT_EQ(0, sysctlbyname(node, &val, &size, NULL, 0))
92                 << strerror(errno);
93         m_maxbcachebuf = val;
94
95         try {
96                 m_mock = new MockFS(m_maxreadahead, m_allow_other,
97                         m_default_permissions, m_push_symlinks_in,
98                         m_init_flags);
99         } catch (std::system_error err) {
100                 FAIL() << err.what();
101         }
102 }
103
104 void
105 FuseTest::expect_access(uint64_t ino, mode_t access_mode, int error)
106 {
107         EXPECT_CALL(*m_mock, process(
108                 ResultOf([=](auto in) {
109                         return (in->header.opcode == FUSE_ACCESS &&
110                                 in->header.nodeid == ino &&
111                                 in->body.access.mask == access_mode);
112                 }, Eq(true)),
113                 _)
114         ).WillOnce(Invoke(ReturnErrno(error)));
115 }
116
117 void FuseTest::expect_getattr(uint64_t ino, uint64_t size)
118 {
119         /* Until the attr cache is working, we may send an additional GETATTR */
120         EXPECT_CALL(*m_mock, process(
121                 ResultOf([=](auto in) {
122                         return (in->header.opcode == FUSE_GETATTR &&
123                                 in->header.nodeid == ino);
124                 }, Eq(true)),
125                 _)
126         ).WillRepeatedly(Invoke(ReturnImmediate([=](auto i __unused, auto out) {
127                 SET_OUT_HEADER_LEN(out, attr);
128                 out->body.attr.attr.ino = ino;  // Must match nodeid
129                 out->body.attr.attr.mode = S_IFREG | 0644;
130                 out->body.attr.attr.size = size;
131                 out->body.attr.attr_valid = UINT64_MAX;
132         })));
133 }
134
135 void FuseTest::expect_lookup(const char *relpath, uint64_t ino, mode_t mode,
136         uint64_t size, int times)
137 {
138         EXPECT_LOOKUP(1, relpath)
139         .Times(times)
140         .WillRepeatedly(Invoke(ReturnImmediate([=](auto in __unused, auto out) {
141                 SET_OUT_HEADER_LEN(out, entry);
142                 out->body.entry.attr.mode = mode;
143                 out->body.entry.nodeid = ino;
144                 out->body.entry.attr.nlink = 1;
145                 out->body.entry.attr_valid = UINT64_MAX;
146                 out->body.entry.attr.size = size;
147         })));
148 }
149
150 void FuseTest::expect_open(uint64_t ino, uint32_t flags, int times)
151 {
152         EXPECT_CALL(*m_mock, process(
153                 ResultOf([=](auto in) {
154                         return (in->header.opcode == FUSE_OPEN &&
155                                 in->header.nodeid == ino);
156                 }, Eq(true)),
157                 _)
158         ).Times(times)
159         .WillRepeatedly(Invoke(ReturnImmediate([=](auto in __unused, auto out) {
160                 out->header.len = sizeof(out->header);
161                 SET_OUT_HEADER_LEN(out, open);
162                 out->body.open.fh = FH;
163                 out->body.open.open_flags = flags;
164         })));
165 }
166
167 void FuseTest::expect_opendir(uint64_t ino)
168 {
169         EXPECT_CALL(*m_mock, process(
170                 ResultOf([](auto in) {
171                         return (in->header.opcode == FUSE_STATFS);
172                 }, Eq(true)),
173                 _)
174         ).WillRepeatedly(Invoke(ReturnImmediate([=](auto i __unused, auto out) {
175                 SET_OUT_HEADER_LEN(out, statfs);
176         })));
177
178         EXPECT_CALL(*m_mock, process(
179                 ResultOf([=](auto in) {
180                         return (in->header.opcode == FUSE_OPENDIR &&
181                                 in->header.nodeid == ino);
182                 }, Eq(true)),
183                 _)
184         ).WillOnce(Invoke(ReturnImmediate([=](auto in __unused, auto out) {
185                 out->header.len = sizeof(out->header);
186                 SET_OUT_HEADER_LEN(out, open);
187                 out->body.open.fh = FH;
188         })));
189 }
190
191 void FuseTest::expect_read(uint64_t ino, uint64_t offset, uint64_t isize,
192         uint64_t osize, const void *contents)
193 {
194         EXPECT_CALL(*m_mock, process(
195                 ResultOf([=](auto in) {
196                         return (in->header.opcode == FUSE_READ &&
197                                 in->header.nodeid == ino &&
198                                 in->body.read.fh == FH &&
199                                 in->body.read.offset == offset &&
200                                 in->body.read.size == isize);
201                 }, Eq(true)),
202                 _)
203         ).WillOnce(Invoke(ReturnImmediate([=](auto in __unused, auto out) {
204                 out->header.len = sizeof(struct fuse_out_header) + osize;
205                 memmove(out->body.bytes, contents, osize);
206         }))).RetiresOnSaturation();
207 }
208
209 void FuseTest::expect_release(uint64_t ino)
210 {
211         EXPECT_CALL(*m_mock, process(
212                 ResultOf([=](auto in) {
213                         return (in->header.opcode == FUSE_RELEASE &&
214                                 in->header.nodeid == ino &&
215                                 in->body.release.fh == FH);
216                 }, Eq(true)),
217                 _)
218         ).WillOnce(Invoke(ReturnErrno(0)));
219 }
220
221 void FuseTest::expect_write(uint64_t ino, uint64_t offset, uint64_t isize,
222         uint64_t osize, uint32_t flags, const void *contents)
223 {
224         EXPECT_CALL(*m_mock, process(
225                 ResultOf([=](auto in) {
226                         const char *buf = (const char*)in->body.bytes +
227                                 sizeof(struct fuse_write_in);
228                         bool pid_ok;
229
230                         if (in->body.write.write_flags & FUSE_WRITE_CACHE)
231                                 pid_ok = true;
232                         else
233                                 pid_ok = (pid_t)in->header.pid == getpid();
234
235                         return (in->header.opcode == FUSE_WRITE &&
236                                 in->header.nodeid == ino &&
237                                 in->body.write.fh == FH &&
238                                 in->body.write.offset == offset  &&
239                                 in->body.write.size == isize &&
240                                 pid_ok &&
241                                 in->body.write.write_flags == flags &&
242                                 0 == bcmp(buf, contents, isize));
243                 }, Eq(true)),
244                 _)
245         ).WillOnce(Invoke(ReturnImmediate([=](auto in __unused, auto out) {
246                 SET_OUT_HEADER_LEN(out, write);
247                 out->body.write.size = osize;
248         })));
249 }
250
251 static void
252 get_unprivileged_uid(uid_t *uid)
253 {
254         struct passwd *pw;
255
256         /* 
257          * First try "tests", Kyua's default unprivileged user.  XXX after
258          * GoogleTest gains a proper Kyua wrapper, get this with the Kyua API
259          */
260         pw = getpwnam("tests");
261         if (pw == NULL) {
262                 /* Fall back to "nobody" */
263                 pw = getpwnam("nobody");
264         }
265         if (pw == NULL)
266                 GTEST_SKIP() << "Test requires an unprivileged user";
267         *uid = pw->pw_uid;
268 }
269
270 void
271 FuseTest::fork(bool drop_privs, std::function<void()> parent_func,
272         std::function<int()> child_func)
273 {
274         sem_t *sem;
275         int mprot = PROT_READ | PROT_WRITE;
276         int mflags = MAP_ANON | MAP_SHARED;
277         pid_t child;
278         uid_t uid;
279         
280         if (drop_privs) {
281                 get_unprivileged_uid(&uid);
282                 if (IsSkipped())
283                         return;
284         }
285
286         sem = (sem_t*)mmap(NULL, sizeof(*sem), mprot, mflags, -1, 0);
287         ASSERT_NE(MAP_FAILED, sem) << strerror(errno);
288         ASSERT_EQ(0, sem_init(sem, 1, 0)) << strerror(errno);
289
290         if ((child = ::fork()) == 0) {
291                 /* In child */
292                 int err = 0;
293
294                 if (sem_wait(sem)) {
295                         perror("sem_wait");
296                         err = 1;
297                         goto out;
298                 }
299
300                 if (drop_privs && 0 != setreuid(-1, uid)) {
301                         perror("setreuid");
302                         err = 1;
303                         goto out;
304                 }
305                 err = child_func();
306
307 out:
308                 sem_destroy(sem);
309                 _exit(err);
310         } else if (child > 0) {
311                 int child_status;
312
313                 /* 
314                  * In parent.  Cleanup must happen here, because it's still
315                  * privileged.
316                  */
317                 m_mock->m_child_pid = child;
318                 ASSERT_NO_FATAL_FAILURE(parent_func());
319
320                 /* Signal the child process to go */
321                 ASSERT_EQ(0, sem_post(sem)) << strerror(errno);
322
323                 wait(&child_status);
324                 ASSERT_EQ(0, WEXITSTATUS(child_status));
325         } else {
326                 FAIL() << strerror(errno);
327         }
328         munmap(sem, sizeof(*sem));
329 }
330
331 static void usage(char* progname) {
332         fprintf(stderr, "Usage: %s [-v]\n\t-v increase verbosity\n", progname);
333         exit(2);
334 }
335
336 int main(int argc, char **argv) {
337         int ch;
338         FuseEnv *fuse_env = new FuseEnv;
339
340         InitGoogleTest(&argc, argv);
341         AddGlobalTestEnvironment(fuse_env);
342
343         while ((ch = getopt(argc, argv, "v")) != -1) {
344                 switch (ch) {
345                         case 'v':
346                                 verbosity++;
347                                 break;
348                         default:
349                                 usage(argv[0]);
350                                 break;
351                 }
352         }
353
354         return (RUN_ALL_TESTS());
355 }