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