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
57void	__usage_short(void);
58void	usage(void);
59void	helpmsg(void);
60void	showversion(void);
61int	init_backgrounded(void);
62
63static 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	/* Linux specific options, we silently ignore them */
77	{ "fsname=",             0, 0x00, 1 },
78	{ "fd=",                 0, 0x00, 1 },
79	{ "rootmode=",           0, 0x00, 1 },
80	{ "user_id=",            0, 0x00, 1 },
81	{ "group_id=",           0, 0x00, 1 },
82	{ "large_read",          0, 0x00, 1 },
83	/* "nonempty", just the first two chars are stripped off during parsing */
84	{ "nempty",              0, 0x00, 1 },
85	MOPT_STDOPTS,
86	MOPT_END
87};
88
89struct mntval {
90	int mv_flag;
91	void *mv_value;
92	int mv_len;
93};
94
95static struct mntval mvals[] = {
96	{ ALTF_MAXREAD, NULL, 0 },
97	{ ALTF_SUBTYPE, NULL, 0 },
98	{ 0, NULL, 0 }
99};
100
101#define DEFAULT_MOUNT_FLAGS ALTF_PRIVATE | ALTF_SYNC_UNMOUNT
102
103int
104main(int argc, char *argv[])
105{
106	struct iovec *iov;
107	int mntflags, iovlen, verbose = 0;
108	char *dev = NULL, *dir = NULL, mntpath[MAXPATHLEN];
109	char *devo = NULL, *diro = NULL;
110	char ndev[128], fdstr[15];
111	int i, done = 0, reject_allow_other = 0, safe_level = 0;
112	int altflags = DEFAULT_MOUNT_FLAGS;
113	int __altflags = DEFAULT_MOUNT_FLAGS;
114	int ch = 0;
115	struct mntopt *mo;
116	struct mntval *mv;
117	static struct option longopts[] = {
118		{"reject-allow_other", no_argument, NULL, 'A'},
119		{"safe", no_argument, NULL, 'S'},
120		{"daemon", required_argument, NULL, 'D'},
121		{"daemon_opts", required_argument, NULL, 'O'},
122		{"special", required_argument, NULL, 's'},
123		{"mountpath", required_argument, NULL, 'm'},
124		{"version", no_argument, NULL, 'V'},
125		{"help", no_argument, NULL, 'h'},
126		{0,0,0,0}
127	};
128	int pid = 0;
129	int fd = -1, fdx;
130	char *ep;
131	char *daemon_str = NULL, *daemon_opts = NULL;
132
133	/*
134	 * We want a parsing routine which is not sensitive to
135	 * the position of args/opts; it should extract the
136	 * first two args and stop at the beginning of the rest.
137	 * (This makes it easier to call mount_fusefs from external
138	 * utils than it is with a strict "util flags args" syntax.)
139	 */
140
141	iov = NULL;
142	iovlen = 0;
143	mntflags = 0;
144	/* All in all, I feel it more robust this way... */
145	unsetenv("POSIXLY_CORRECT");
146	if (getenv("MOUNT_FUSEFS_IGNORE_UNKNOWN"))
147		getmnt_silent = 1;
148	if (getenv("MOUNT_FUSEFS_VERBOSE"))
149		verbose = 1;
150
151	do {
152		for (i = 0; i < 3; i++) {
153			if (optind < argc && argv[optind][0] != '-') {
154				if (dir) {
155					done = 1;
156					break;
157				}
158				if (dev)
159					dir = argv[optind];
160				else
161					dev = argv[optind];
162				optind++;
163			}
164		}
165		switch(ch) {
166		case 'A':
167			reject_allow_other = 1;
168			break;
169		case 'S':
170			safe_level = 1;
171			break;
172		case 'D':
173			if (daemon_str)
174				errx(1, "daemon specified inconsistently");
175			daemon_str = optarg;
176			break;
177		case 'O':
178			if (daemon_opts)
179				errx(1, "daemon opts specified inconsistently");
180			daemon_opts = optarg;
181			break;
182		case 'o':
183			getmntopts(optarg, mopts, &mntflags, &altflags);
184			for (mv = mvals; mv->mv_flag; ++mv) {
185				if (! (altflags & mv->mv_flag))
186					continue;
187				for (mo = mopts; mo->m_flag; ++mo) {
188					char *p, *q;
189
190					if (mo->m_flag != mv->mv_flag)
191						continue;
192					p = strstr(optarg, mo->m_option);
193					if (p) {
194						p += strlen(mo->m_option);
195						q = p;
196						while (*q != '\0' && *q != ',')
197							q++;
198						mv->mv_len = q - p + 1;
199						mv->mv_value = malloc(mv->mv_len);
200						memcpy(mv->mv_value, p, mv->mv_len - 1);
201						((char *)mv->mv_value)[mv->mv_len - 1] = '\0';
202						break;
203					}
204				}
205			}
206			break;
207		case 's':
208			if (devo)
209				errx(1, "special specified inconsistently");
210			devo = optarg;
211			break;
212		case 'm':
213			if (diro)
214				errx(1, "mount path specified inconsistently");
215			diro = optarg;
216			break;
217		case 'v':
218			verbose = 1;
219			break;
220		case 'h':
221			helpmsg();
222			break;
223		case 'V':
224			showversion();
225			break;
226		case '\0':
227			break;
228		case '?':
229		default:
230			usage();
231		}
232		if (done)
233			break;
234	} while ((ch = getopt_long(argc, argv, "AvVho:SD:O:s:m:", longopts, NULL)) != -1);
235
236	argc -= optind;
237	argv += optind;
238
239	if (devo) {
240		if (dev)
241			errx(1, "special specified inconsistently");
242		dev = devo;
243	} else if (diro)
244		errx(1, "if mountpoint is given via an option, special should also be given via an option");
245
246	if (diro) {
247		if (dir)
248			errx(1, "mount path specified inconsistently");
249		dir = diro;
250	}
251
252	if ((! dev) && argc > 0) {
253		dev = *argv++;
254		argc--;
255	}
256
257	if ((! dir) && argc > 0) {
258		dir = *argv++;
259		argc--;
260	}
261
262	if (! (dev && dir))
263		errx(1, "missing special and/or mountpoint");
264
265	for (mo = mopts; mo->m_flag; ++mo) {
266		if (altflags & mo->m_flag) {
267			int iov_done = 0;
268
269			if (reject_allow_other &&
270			    strcmp(mo->m_option, "allow_other") == 0)
271				/*
272				 * reject_allow_other is stronger than a
273				 * negative of allow_other: if this is set,
274				 * allow_other is blocked, period.
275				 */
276				errx(1, "\"allow_other\" usage is banned by respective option");
277
278			for (mv = mvals; mv->mv_flag; ++mv) {
279				if (mo->m_flag != mv->mv_flag)
280					continue;
281				if (mv->mv_value) {
282					build_iovec(&iov, &iovlen, mo->m_option, mv->mv_value, mv->mv_len);
283					iov_done = 1;
284					break;
285				}
286			}
287			if (! iov_done)
288				build_iovec(&iov, &iovlen, mo->m_option,
289				    __DECONST(void *, ""), -1);
290		}
291		if (__altflags & mo->m_flag) {
292			char *uscore_opt;
293
294			if (asprintf(&uscore_opt, "__%s", mo->m_option) == -1)
295				err(1, "failed to allocate memory");
296			build_iovec(&iov, &iovlen, uscore_opt,
297			    __DECONST(void *, ""), -1);
298			free(uscore_opt);
299		}
300	}
301
302	if (getenv("MOUNT_FUSEFS_SAFE"))
303		safe_level = 1;
304
305	if (safe_level > 0 && (argc > 0 || daemon_str || daemon_opts))
306		errx(1, "safe mode, spawning daemon not allowed");
307
308	if ((argc > 0 && (daemon_str || daemon_opts)) ||
309	    (daemon_opts && ! daemon_str))
310		errx(1, "daemon specified inconsistently");
311
312	/*
313	 * Resolve the mountpoint with realpath(3) and remove unnecessary
314	 * slashes from the devicename if there are any.
315	 */
316	if (checkpath(dir, mntpath) != 0)
317		err(1, "%s", mntpath);
318	(void)rmslashes(dev, dev);
319
320	if (strcmp(dev, "auto") == 0)
321		dev = __DECONST(char *, "/dev/fuse");
322
323	if (strcmp(dev, "/dev/fuse") == 0) {
324		if (! (argc > 0 || daemon_str)) {
325			fprintf(stderr, "Please also specify the fuse daemon to run when mounting via the multiplexer!\n");
326			usage();
327		}
328		if ((fd = open(dev, O_RDWR)) < 0)
329			err(1, "failed to open fuse device");
330	} else {
331		fdx = strtol(dev, &ep, 10);
332		if (*ep == '\0')
333			fd = fdx;
334	}
335
336	/* Identifying device */
337	if (fd >= 0) {
338		struct stat sbuf;
339		char *ndevbas, *lep;
340
341		if (fstat(fd, &sbuf) == -1)
342			err(1, "cannot stat device file descriptor");
343
344		strcpy(ndev, _PATH_DEV);
345		ndevbas = ndev + strlen(_PATH_DEV);
346		devname_r(sbuf.st_rdev, S_IFCHR, ndevbas,
347		          sizeof(ndev) - strlen(_PATH_DEV));
348
349		if (strncmp(ndevbas, "fuse", 4))
350			errx(1, "mounting inappropriate device");
351
352		strtol(ndevbas + 4, &lep, 10);
353		if (*lep != '\0')
354			errx(1, "mounting inappropriate device");
355
356		dev = ndev;
357	}
358
359	if (argc > 0 || daemon_str) {
360		char *fds;
361
362		if (fd < 0 && (fd = open(dev, O_RDWR)) < 0)
363			err(1, "failed to open fuse device");
364
365		if (asprintf(&fds, "%d", fd) == -1)
366			err(1, "failed to allocate memory");
367		setenv("FUSE_DEV_FD", fds, 1);
368		free(fds);
369		setenv("FUSE_NO_MOUNT", "1", 1);
370
371		if (daemon_str) {
372			char *bgdaemon;
373			int len;
374
375			if (! daemon_opts)
376				daemon_opts = __DECONST(char *, "");
377
378			len =  strlen(daemon_str) + 1 + strlen(daemon_opts) +
379			    2 + 1;
380			bgdaemon = calloc(1, len);
381
382			if (! bgdaemon)
383				err(1, "failed to allocate memory");
384
385			strlcpy(bgdaemon, daemon_str, len);
386			strlcat(bgdaemon, " ", len);
387			strlcat(bgdaemon, daemon_opts, len);
388			strlcat(bgdaemon, " &", len);
389
390			if (system(bgdaemon))
391				err(1, "failed to call fuse daemon");
392		} else {
393			if ((pid = fork()) < 0)
394				err(1, "failed to fork for fuse daemon");
395
396			if (pid == 0) {
397				execvp(argv[0], argv);
398				err(1, "failed to exec fuse daemon");
399			}
400		}
401	}
402
403	if (fd >= 0 && ! init_backgrounded() && close(fd) < 0) {
404		if (pid)
405			kill(pid, SIGKILL);
406		err(1, "failed to close fuse device");
407	}
408
409	/* Prepare the options vector for nmount(). build_iovec() is declared
410	 * in mntopts.h. */
411	sprintf(fdstr, "%d", fd);
412	build_iovec(&iov, &iovlen, "fstype", __DECONST(void *, "fusefs"), -1);
413	build_iovec(&iov, &iovlen, "fspath", mntpath, -1);
414	build_iovec(&iov, &iovlen, "from", dev, -1);
415	build_iovec(&iov, &iovlen, "fd", fdstr, -1);
416
417	if (verbose)
418		fprintf(stderr, "mounting fuse daemon on device %s\n", dev);
419
420	if (nmount(iov, iovlen, mntflags) < 0)
421		err(EX_OSERR, "%s on %s", dev, mntpath);
422
423	exit(0);
424}
425
426void
427__usage_short(void) {
428	fprintf(stderr,
429	    "usage:\n%s [-A|-S|-v|-V|-h|-D daemon|-O args|-s special|-m node|-o option...] special node [daemon args...]\n\n",
430	    getprogname());
431}
432
433void
434usage(void)
435{
436	struct mntopt *mo;
437
438	__usage_short();
439
440	fprintf(stderr, "known options:\n");
441	for (mo = mopts; mo->m_flag; ++mo)
442		fprintf(stderr, "\t%s\n", mo->m_option);
443
444	fprintf(stderr, "\n(use -h for a detailed description of these options)\n");
445	exit(EX_USAGE);
446}
447
448void
449helpmsg(void)
450{
451	if (! getenv("MOUNT_FUSEFS_CALL_BY_LIB")) {
452		__usage_short();
453		fprintf(stderr, "description of options:\n");
454	}
455
456	/*
457	 * The main use case of this function is giving info embedded in general
458	 * FUSE lib help output. Therefore the style and the content of the output
459	 * tries to fit there as much as possible.
460	 */
461	fprintf(stderr,
462	        "    -o allow_other         allow access to other users\n"
463	        /* "    -o nonempty            allow mounts over non-empty file/dir\n" */
464	        "    -o default_permissions enable permission checking by kernel\n"
465		/*
466	        "    -o fsname=NAME         set filesystem name\n"
467	        "    -o large_read          issue large read requests (2.4 only)\n"
468		 */
469	        "    -o subtype=NAME        set filesystem type\n"
470	        "    -o max_read=N          set maximum size of read requests\n"
471	        "    -o noprivate           allow secondary mounting of the filesystem\n"
472	        "    -o neglect_shares      don't report EBUSY when unmount attempted\n"
473	        "                           in presence of secondary mounts\n"
474	        "    -o push_symlinks_in    prefix absolute symlinks with mountpoint\n"
475	        "    -o sync_unmount        do unmount synchronously\n"
476	        );
477	exit(EX_USAGE);
478}
479
480void
481showversion(void)
482{
483	puts("mount_fusefs [fuse4bsd] version: " FUSE4BSD_VERSION);
484	exit(EX_USAGE);
485}
486
487int
488init_backgrounded(void)
489{
490	int ibg;
491	size_t len;
492
493	len = sizeof(ibg);
494
495	if (sysctlbyname("vfs.fuse.init_backgrounded", &ibg, &len, NULL, 0))
496		return (0);
497
498	return (ibg);
499}
500