xref: /freebsd/sbin/mount_fusefs/mount_fusefs.c (revision fac71e4e09885bb2afa3d984a0c239a52e1a7418)
1 /*-
2  * SPDX-License-Identifier: BSD-2-Clause
3  *
4  * Copyright (c) 2005 Jean-Sebastien Pedron
5  * Copyright (c) 2005 Csaba Henk
6  * All rights reserved.
7  *
8  * Copyright (c) 2019 The FreeBSD Foundation
9  *
10  * Portions of this software were developed by BFF Storage Systems under
11  * sponsorship from the FreeBSD Foundation.
12  *
13  * Redistribution and use in source and binary forms, with or without
14  * modification, are permitted provided that the following conditions
15  * are met:
16  * 1. Redistributions of source code must retain the above copyright
17  *    notice, this list of conditions and the following disclaimer.
18  * 2. Redistributions in binary form must reproduce the above copyright
19  *    notice, this list of conditions and the following disclaimer in the
20  *    documentation and/or other materials provided with the distribution.
21  *
22  * THIS SOFTWARE IS PROVIDED BY THE AUTHOR AND CONTRIBUTORS ``AS IS'' AND
23  * ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
24  * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE
25  * ARE DISCLAIMED.  IN NO EVENT SHALL THE AUTHOR OR CONTRIBUTORS BE LIABLE
26  * FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL
27  * DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS
28  * OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION)
29  * HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT
30  * LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY
31  * OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF
32  * SUCH DAMAGE.
33  *
34  */
35 
36 #include <sys/cdefs.h>
37 __FBSDID("$FreeBSD$");
38 
39 #include <sys/param.h>
40 #include <sys/mount.h>
41 #include <sys/uio.h>
42 #include <sys/stat.h>
43 #include <sys/sysctl.h>
44 
45 #include <err.h>
46 #include <stdio.h>
47 #include <stdlib.h>
48 #include <string.h>
49 #include <sysexits.h>
50 #include <unistd.h>
51 #include <fcntl.h>
52 #include <signal.h>
53 #include <getopt.h>
54 #include <limits.h>
55 #include <osreldate.h>
56 #include <paths.h>
57 
58 #include "mntopts.h"
59 
60 #ifndef FUSE4BSD_VERSION
61 #define	FUSE4BSD_VERSION	"0.3.9-pre1"
62 #endif
63 
64 void	__usage_short(void);
65 void	usage(void);
66 void	helpmsg(void);
67 void	showversion(void);
68 
69 static struct mntopt mopts[] = {
70 	#define ALTF_PRIVATE 0x01
71 	{ "private",             0, ALTF_PRIVATE, 1 },
72 	{ "neglect_shares",      0, 0x02, 1 },
73 	{ "push_symlinks_in",    0, 0x04, 1 },
74 	{ "allow_other",         0, 0x08, 1 },
75 	{ "default_permissions", 0, 0x10, 1 },
76 	#define ALTF_MAXREAD 0x20
77 	{ "max_read=",           0, ALTF_MAXREAD, 1 },
78 	#define ALTF_SUBTYPE 0x40
79 	{ "subtype=",            0, ALTF_SUBTYPE, 1 },
80 	#define ALTF_FSNAME 0x80
81 	{ "fsname=",             0, ALTF_FSNAME, 1 },
82 	/*
83 	 * MOPT_AUTOMOUNTED, included by MOPT_STDOPTS, does not fit into
84 	 * the 'flags' argument to nmount(2).  We have to abuse altflags
85 	 * to pass it, as string, via iovec.
86 	 */
87 	#define ALTF_AUTOMOUNTED 0x100
88 	{ "automounted",	0, ALTF_AUTOMOUNTED, 1 },
89 	#define ALTF_INTR 0x200
90 	{ "intr",		0, ALTF_INTR, 1 },
91 	/* Linux specific options, we silently ignore them */
92 	{ "fd=",                 0, 0x00, 1 },
93 	{ "rootmode=",           0, 0x00, 1 },
94 	{ "user_id=",            0, 0x00, 1 },
95 	{ "group_id=",           0, 0x00, 1 },
96 	{ "large_read",          0, 0x00, 1 },
97 	/* "nonempty", just the first two chars are stripped off during parsing */
98 	{ "nempty",              0, 0x00, 1 },
99 	{ "async",               0, MNT_ASYNC, 0},
100 	{ "noasync",             1, MNT_ASYNC, 0},
101 	MOPT_STDOPTS,
102 	MOPT_END
103 };
104 
105 struct mntval {
106 	int mv_flag;
107 	void *mv_value;
108 	int mv_len;
109 };
110 
111 static struct mntval mvals[] = {
112 	{ ALTF_MAXREAD, NULL, 0 },
113 	{ ALTF_SUBTYPE, NULL, 0 },
114 	{ ALTF_FSNAME, NULL, 0 },
115 	{ 0, NULL, 0 }
116 };
117 
118 #define DEFAULT_MOUNT_FLAGS ALTF_PRIVATE
119 
120 int
121 main(int argc, char *argv[])
122 {
123 	struct iovec *iov;
124 	int mntflags, iovlen, verbose = 0;
125 	char *dev = NULL, *dir = NULL, mntpath[MAXPATHLEN];
126 	char *devo = NULL, *diro = NULL;
127 	char ndev[128], fdstr[15];
128 	int i, done = 0, reject_allow_other = 0, safe_level = 0;
129 	int altflags = DEFAULT_MOUNT_FLAGS;
130 	int __altflags = DEFAULT_MOUNT_FLAGS;
131 	int ch = 0;
132 	struct mntopt *mo;
133 	struct mntval *mv;
134 	static struct option longopts[] = {
135 		{"reject-allow_other", no_argument, NULL, 'A'},
136 		{"safe", no_argument, NULL, 'S'},
137 		{"daemon", required_argument, NULL, 'D'},
138 		{"daemon_opts", required_argument, NULL, 'O'},
139 		{"special", required_argument, NULL, 's'},
140 		{"mountpath", required_argument, NULL, 'm'},
141 		{"version", no_argument, NULL, 'V'},
142 		{"help", no_argument, NULL, 'h'},
143 		{0,0,0,0}
144 	};
145 	int pid = 0;
146 	int fd = -1, fdx;
147 	char *ep;
148 	char *daemon_str = NULL, *daemon_opts = NULL;
149 
150 	/*
151 	 * We want a parsing routine which is not sensitive to
152 	 * the position of args/opts; it should extract the
153 	 * first two args and stop at the beginning of the rest.
154 	 * (This makes it easier to call mount_fusefs from external
155 	 * utils than it is with a strict "util flags args" syntax.)
156 	 */
157 
158 	iov = NULL;
159 	iovlen = 0;
160 	mntflags = 0;
161 	/* All in all, I feel it more robust this way... */
162 	unsetenv("POSIXLY_CORRECT");
163 	if (getenv("MOUNT_FUSEFS_IGNORE_UNKNOWN"))
164 		getmnt_silent = 1;
165 	if (getenv("MOUNT_FUSEFS_VERBOSE"))
166 		verbose = 1;
167 
168 	do {
169 		for (i = 0; i < 3; i++) {
170 			if (optind < argc && argv[optind][0] != '-') {
171 				if (dir) {
172 					done = 1;
173 					break;
174 				}
175 				if (dev)
176 					dir = argv[optind];
177 				else
178 					dev = argv[optind];
179 				optind++;
180 			}
181 		}
182 		switch(ch) {
183 		case 'A':
184 			reject_allow_other = 1;
185 			break;
186 		case 'S':
187 			safe_level = 1;
188 			break;
189 		case 'D':
190 			if (daemon_str)
191 				errx(1, "daemon specified inconsistently");
192 			daemon_str = optarg;
193 			break;
194 		case 'O':
195 			if (daemon_opts)
196 				errx(1, "daemon opts specified inconsistently");
197 			daemon_opts = optarg;
198 			break;
199 		case 'o':
200 			getmntopts(optarg, mopts, &mntflags, &altflags);
201 			for (mv = mvals; mv->mv_flag; ++mv) {
202 				if (! (altflags & mv->mv_flag))
203 					continue;
204 				for (mo = mopts; mo->m_flag; ++mo) {
205 					char *p, *q;
206 
207 					if (mo->m_flag != mv->mv_flag)
208 						continue;
209 					p = strstr(optarg, mo->m_option);
210 					if (p) {
211 						p += strlen(mo->m_option);
212 						q = p;
213 						while (*q != '\0' && *q != ',')
214 							q++;
215 						mv->mv_len = q - p + 1;
216 						mv->mv_value = malloc(mv->mv_len);
217 						if (mv->mv_value == NULL)
218 							err(1, "malloc");
219 						memcpy(mv->mv_value, p, mv->mv_len - 1);
220 						((char *)mv->mv_value)[mv->mv_len - 1] = '\0';
221 						break;
222 					}
223 				}
224 			}
225 			break;
226 		case 's':
227 			if (devo)
228 				errx(1, "special specified inconsistently");
229 			devo = optarg;
230 			break;
231 		case 'm':
232 			if (diro)
233 				errx(1, "mount path specified inconsistently");
234 			diro = optarg;
235 			break;
236 		case 'v':
237 			verbose = 1;
238 			break;
239 		case 'h':
240 			helpmsg();
241 			break;
242 		case 'V':
243 			showversion();
244 			break;
245 		case '\0':
246 			break;
247 		case '?':
248 		default:
249 			usage();
250 		}
251 		if (done)
252 			break;
253 	} while ((ch = getopt_long(argc, argv, "AvVho:SD:O:s:m:", longopts, NULL)) != -1);
254 
255 	argc -= optind;
256 	argv += optind;
257 
258 	if (devo) {
259 		if (dev)
260 			errx(1, "special specified inconsistently");
261 		dev = devo;
262 	} else if (diro)
263 		errx(1, "if mountpoint is given via an option, special should also be given via an option");
264 
265 	if (diro) {
266 		if (dir)
267 			errx(1, "mount path specified inconsistently");
268 		dir = diro;
269 	}
270 
271 	if ((! dev) && argc > 0) {
272 		dev = *argv++;
273 		argc--;
274 	}
275 
276 	if ((! dir) && argc > 0) {
277 		dir = *argv++;
278 		argc--;
279 	}
280 
281 	if (! (dev && dir))
282 		errx(1, "missing special and/or mountpoint");
283 
284 	for (mo = mopts; mo->m_flag; ++mo) {
285 		if (altflags & mo->m_flag) {
286 			int iov_done = 0;
287 
288 			if (reject_allow_other &&
289 			    strcmp(mo->m_option, "allow_other") == 0)
290 				/*
291 				 * reject_allow_other is stronger than a
292 				 * negative of allow_other: if this is set,
293 				 * allow_other is blocked, period.
294 				 */
295 				errx(1, "\"allow_other\" usage is banned by respective option");
296 
297 			for (mv = mvals; mv->mv_flag; ++mv) {
298 				if (mo->m_flag != mv->mv_flag)
299 					continue;
300 				if (mv->mv_value) {
301 					build_iovec(&iov, &iovlen, mo->m_option, mv->mv_value, mv->mv_len);
302 					iov_done = 1;
303 					break;
304 				}
305 			}
306 			if (! iov_done)
307 				build_iovec(&iov, &iovlen, mo->m_option,
308 				    __DECONST(void *, ""), -1);
309 		}
310 		if (__altflags & mo->m_flag) {
311 			char *uscore_opt;
312 
313 			if (asprintf(&uscore_opt, "__%s", mo->m_option) == -1)
314 				err(1, "failed to allocate memory");
315 			build_iovec(&iov, &iovlen, uscore_opt,
316 			    __DECONST(void *, ""), -1);
317 			free(uscore_opt);
318 		}
319 	}
320 
321 	if (getenv("MOUNT_FUSEFS_SAFE"))
322 		safe_level = 1;
323 
324 	if (safe_level > 0 && (argc > 0 || daemon_str || daemon_opts))
325 		errx(1, "safe mode, spawning daemon not allowed");
326 
327 	if ((argc > 0 && (daemon_str || daemon_opts)) ||
328 	    (daemon_opts && ! daemon_str))
329 		errx(1, "daemon specified inconsistently");
330 
331 	/*
332 	 * Resolve the mountpoint with realpath(3) and remove unnecessary
333 	 * slashes from the devicename if there are any.
334 	 */
335 	if (checkpath(dir, mntpath) != 0)
336 		err(1, "%s", mntpath);
337 	(void)rmslashes(dev, dev);
338 
339 	if (strcmp(dev, "auto") == 0)
340 		dev = __DECONST(char *, "/dev/fuse");
341 
342 	if (strcmp(dev, "/dev/fuse") == 0) {
343 		if (! (argc > 0 || daemon_str)) {
344 			fprintf(stderr, "Please also specify the fuse daemon to run when mounting via the multiplexer!\n");
345 			usage();
346 		}
347 		if ((fd = open(dev, O_RDWR)) < 0)
348 			err(1, "failed to open fuse device");
349 	} else {
350 		fdx = strtol(dev, &ep, 10);
351 		if (*ep == '\0')
352 			fd = fdx;
353 	}
354 
355 	/* Identifying device */
356 	if (fd >= 0) {
357 		struct stat sbuf;
358 		char *ndevbas, *lep;
359 
360 		if (fstat(fd, &sbuf) == -1)
361 			err(1, "cannot stat device file descriptor");
362 
363 		strcpy(ndev, _PATH_DEV);
364 		ndevbas = ndev + strlen(_PATH_DEV);
365 		devname_r(sbuf.st_rdev, S_IFCHR, ndevbas,
366 		          sizeof(ndev) - strlen(_PATH_DEV));
367 
368 		if (strncmp(ndevbas, "fuse", 4))
369 			errx(1, "mounting inappropriate device");
370 
371 		strtol(ndevbas + 4, &lep, 10);
372 		if (*lep != '\0')
373 			errx(1, "mounting inappropriate device");
374 
375 		dev = ndev;
376 	}
377 
378 	if (argc > 0 || daemon_str) {
379 		char *fds;
380 
381 		if (fd < 0 && (fd = open(dev, O_RDWR)) < 0)
382 			err(1, "failed to open fuse device");
383 
384 		if (asprintf(&fds, "%d", fd) == -1)
385 			err(1, "failed to allocate memory");
386 		setenv("FUSE_DEV_FD", fds, 1);
387 		free(fds);
388 		setenv("FUSE_NO_MOUNT", "1", 1);
389 
390 		if (daemon_str) {
391 			char *bgdaemon;
392 			int len;
393 
394 			if (! daemon_opts)
395 				daemon_opts = __DECONST(char *, "");
396 
397 			len =  strlen(daemon_str) + 1 + strlen(daemon_opts) +
398 			    2 + 1;
399 			bgdaemon = calloc(1, len);
400 
401 			if (! bgdaemon)
402 				err(1, "failed to allocate memory");
403 
404 			strlcpy(bgdaemon, daemon_str, len);
405 			strlcat(bgdaemon, " ", len);
406 			strlcat(bgdaemon, daemon_opts, len);
407 			strlcat(bgdaemon, " &", len);
408 
409 			if (system(bgdaemon))
410 				err(1, "failed to call fuse daemon");
411 		} else {
412 			if ((pid = fork()) < 0)
413 				err(1, "failed to fork for fuse daemon");
414 
415 			if (pid == 0) {
416 				execvp(argv[0], argv);
417 				err(1, "failed to exec fuse daemon");
418 			}
419 		}
420 	}
421 
422 	/* Prepare the options vector for nmount(). build_iovec() is declared
423 	 * in mntopts.h. */
424 	sprintf(fdstr, "%d", fd);
425 	build_iovec(&iov, &iovlen, "fstype", __DECONST(void *, "fusefs"), -1);
426 	build_iovec(&iov, &iovlen, "fspath", mntpath, -1);
427 	build_iovec(&iov, &iovlen, "from", dev, -1);
428 	build_iovec(&iov, &iovlen, "fd", fdstr, -1);
429 
430 	if (verbose)
431 		fprintf(stderr, "mounting fuse daemon on device %s\n", dev);
432 
433 	if (nmount(iov, iovlen, mntflags) < 0)
434 		err(EX_OSERR, "%s on %s", dev, mntpath);
435 
436 	exit(0);
437 }
438 
439 void
440 __usage_short(void) {
441 	fprintf(stderr,
442 	    "usage:\n%s [-A|-S|-v|-V|-h|-D daemon|-O args|-s special|-m node|-o option...] special node [daemon args...]\n\n",
443 	    getprogname());
444 }
445 
446 void
447 usage(void)
448 {
449 	struct mntopt *mo;
450 
451 	__usage_short();
452 
453 	fprintf(stderr, "known options:\n");
454 	for (mo = mopts; mo->m_flag; ++mo)
455 		fprintf(stderr, "\t%s\n", mo->m_option);
456 
457 	fprintf(stderr, "\n(use -h for a detailed description of these options)\n");
458 	exit(EX_USAGE);
459 }
460 
461 void
462 helpmsg(void)
463 {
464 	if (! getenv("MOUNT_FUSEFS_CALL_BY_LIB")) {
465 		__usage_short();
466 		fprintf(stderr, "description of options:\n");
467 	}
468 
469 	/*
470 	 * The main use case of this function is giving info embedded in general
471 	 * FUSE lib help output. Therefore the style and the content of the output
472 	 * tries to fit there as much as possible.
473 	 */
474 	fprintf(stderr,
475 	        "    -o allow_other         allow access to other users\n"
476 	        /* "    -o nonempty            allow mounts over non-empty file/dir\n" */
477 	        "    -o default_permissions enable permission checking by kernel\n"
478 		"    -o intr                interruptible mount\n"
479 	        "    -o fsname=NAME         set filesystem name\n"
480 		/*
481 	        "    -o large_read          issue large read requests (2.4 only)\n"
482 		 */
483 	        "    -o subtype=NAME        set filesystem type\n"
484 	        "    -o max_read=N          set maximum size of read requests\n"
485 	        "    -o noprivate           allow secondary mounting of the filesystem\n"
486 	        "    -o neglect_shares      don't report EBUSY when unmount attempted\n"
487 	        "                           in presence of secondary mounts\n"
488 	        "    -o push_symlinks_in    prefix absolute symlinks with mountpoint\n"
489 	        );
490 	exit(EX_USAGE);
491 }
492 
493 void
494 showversion(void)
495 {
496 	puts("mount_fusefs [fuse4bsd] version: " FUSE4BSD_VERSION);
497 	exit(EX_USAGE);
498 }
499