1/* 	$NetBSD: refuse_opt.c,v 1.23 2022/01/22 07:58:32 pho Exp $	*/
2
3/*-
4 * Copyright (c) 2007 Juan Romero Pardines.
5 * All rights reserved.
6 *
7 * Redistribution and use in source and binary forms, with or without
8 * modification, are permitted provided that the following conditions
9 * are met:
10 * 1. Redistributions of source code must retain the above copyright
11 *    notice, this list of conditions and the following disclaimer.
12 * 2. Redistributions in binary form must reproduce the above copyright
13 *    notice, this list of conditions and the following disclaimer in the
14 *    documentation and/or other materials provided with the distribution.
15 *
16 * THIS SOFTWARE IS PROVIDED BY THE AUTHOR ``AS IS'' AND ANY EXPRESS OR
17 * IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES
18 * OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE DISCLAIMED.
19 * IN NO EVENT SHALL THE AUTHOR BE LIABLE FOR ANY DIRECT, INDIRECT,
20 * INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT
21 * NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE,
22 * DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY
23 * THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT
24 * (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF
25 * THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
26 */
27
28#include <sys/types.h>
29
30#include <err.h>
31#include <fuse_internal.h>
32#include <fuse_opt.h>
33#include <stdbool.h>
34#include <stdio.h>
35#include <stdlib.h>
36#include <string.h>
37
38#ifdef FUSE_OPT_DEBUG
39#define DPRINTF(x)	do { printf x; } while ( /* CONSTCOND */ 0)
40#else
41#define DPRINTF(x)
42#endif
43
44/*
45 * Public API.
46 */
47
48/* ARGSUSED */
49int
50fuse_opt_add_arg(struct fuse_args *args, const char *arg)
51{
52	struct fuse_args	*ap;
53
54	if (args->allocated == 0) {
55		ap = fuse_opt_deep_copy_args(args->argc, args->argv);
56		args->argv = ap->argv;
57		args->argc = ap->argc;
58		args->allocated = ap->allocated;
59		(void) free(ap);
60	} else if (args->allocated == args->argc) {
61		int na = args->allocated + 10;
62
63		if (reallocarr(&args->argv, (size_t)na, sizeof(*args->argv)) != 0)
64			return -1;
65
66		args->allocated = na;
67	}
68	DPRINTF(("%s: arguments passed: [arg:%s]\n", __func__, arg));
69	if ((args->argv[args->argc++] = strdup(arg)) == NULL)
70		err(1, "fuse_opt_add_arg");
71	args->argv[args->argc] = NULL;
72        return 0;
73}
74
75struct fuse_args *
76fuse_opt_deep_copy_args(int argc, char **argv)
77{
78	struct fuse_args	*ap;
79	int			 i;
80
81	if ((ap = malloc(sizeof(*ap))) == NULL)
82		err(1, "_fuse_deep_copy_args");
83	/* deep copy args structure into channel args */
84	ap->allocated = ((argc / 10) + 1) * 10;
85
86	if ((ap->argv = calloc((size_t)ap->allocated,
87	    sizeof(*ap->argv))) == NULL)
88		err(1, "_fuse_deep_copy_args");
89
90	for (i = 0; i < argc; i++) {
91		if ((ap->argv[i] = strdup(argv[i])) == NULL)
92			err(1, "_fuse_deep_copy_args");
93	}
94	ap->argv[ap->argc = i] = NULL;
95	return ap;
96}
97
98void
99fuse_opt_free_args(struct fuse_args *ap)
100{
101	if (ap) {
102		if (ap->allocated) {
103			int	i;
104			for (i = 0; i < ap->argc; i++) {
105				free(ap->argv[i]);
106			}
107			free(ap->argv);
108		}
109		ap->argv = NULL;
110		ap->allocated = ap->argc = 0;
111	}
112}
113
114/* ARGSUSED */
115int
116fuse_opt_insert_arg(struct fuse_args *args, int pos, const char *arg)
117{
118	int	i;
119	int	na;
120
121	DPRINTF(("%s: arguments passed: [pos=%d] [arg=%s]\n",
122	    __func__, pos, arg));
123	if (args->argv == NULL) {
124		na = 10;
125	} else {
126		na = args->allocated + 10;
127	}
128	if (reallocarr(&args->argv, (size_t)na, sizeof(*args->argv)) != 0) {
129		warn("fuse_opt_insert_arg");
130		return -1;
131	}
132	args->allocated = na;
133
134	for (i = args->argc++; i > pos; --i) {
135		args->argv[i] = args->argv[i - 1];
136	}
137	if ((args->argv[pos] = strdup(arg)) == NULL)
138		err(1, "fuse_opt_insert_arg");
139	args->argv[args->argc] = NULL;
140	return 0;
141}
142
143static int add_opt(char **opts, const char *opt, bool escape)
144{
145	const size_t orig_len = *opts == NULL ? 0 : strlen(*opts);
146	char* buf = realloc(*opts, orig_len + 1 + strlen(opt) * 2 + 1);
147
148	if (buf == NULL) {
149		return -1;
150	}
151	*opts = buf;
152
153	if (orig_len > 0) {
154		buf += orig_len;
155		*buf++ = ',';
156	}
157
158	for (; *opt; opt++) {
159		if (escape && (*opt == ',' || *opt == '\\')) {
160			*buf++ = '\\';
161		}
162		*buf++ = *opt;
163	}
164	*buf = '\0';
165
166	return 0;
167}
168
169int fuse_opt_add_opt(char **opts, const char *opt)
170{
171	DPRINTF(("%s: arguments passed: [opts=%s] [opt=%s]\n",
172	    __func__, *opts, opt));
173	return add_opt(opts, opt, false);
174}
175
176int fuse_opt_add_opt_escaped(char **opts, const char *opt)
177{
178	DPRINTF(("%s: arguments passed: [opts=%s] [opt=%s]\n",
179	    __func__, *opts, opt));
180	return add_opt(opts, opt, true);
181}
182
183static bool match_templ(const char *templ, const char *opt, ssize_t *sep_idx)
184{
185	const char *sep = strpbrk(templ, "= ");
186
187	if (sep != NULL && (sep[1] == '\0' || sep[1] == '%')) {
188		const size_t cmp_len =
189			(size_t)(sep[0] == '=' ? sep - templ + 1 : sep - templ);
190
191		if (strlen(opt) >= cmp_len && strncmp(templ, opt, cmp_len) == 0) {
192			if (sep_idx != NULL)
193				*sep_idx = (ssize_t)(sep - templ);
194			return true;
195		}
196		else {
197			return false;
198		}
199	}
200	else {
201		if (strcmp(templ, opt) == 0) {
202			if (sep_idx != NULL)
203				*sep_idx = -1;
204			return true;
205		}
206		else {
207			return false;
208		}
209	}
210}
211
212static const struct fuse_opt *
213find_opt(const struct fuse_opt *opts, const char *opt, ssize_t *sep_idx)
214{
215	for (; opts != NULL && opts->templ != NULL; opts++) {
216		if (match_templ(opts->templ, opt, sep_idx))
217			return opts;
218	}
219	return NULL;
220}
221
222/*
223 * Returns 1 if opt was matched with any option from opts,
224 * otherwise returns 0.
225 */
226int
227fuse_opt_match(const struct fuse_opt *opts, const char *opt)
228{
229	return find_opt(opts, opt, NULL) != NULL ? 1 : 0;
230}
231
232static int call_proc(fuse_opt_proc_t proc, void* data,
233		const char* arg, int key, struct fuse_args *outargs, bool is_opt)
234{
235	if (key == FUSE_OPT_KEY_DISCARD)
236		return 0;
237
238	if (key != FUSE_OPT_KEY_KEEP && proc != NULL) {
239		const int rv = proc(data, arg, key, outargs);
240
241		if (rv == -1 || /* error   */
242			rv ==  0    /* discard */)
243			return rv;
244	}
245
246	if (is_opt) {
247		/* Do we already have "-o" at the beginning of outargs? */
248		if (outargs->argc >= 3 && strcmp(outargs->argv[1], "-o") == 0) {
249			/* Append the option to the comma-separated list. */
250			if (fuse_opt_add_opt_escaped(&outargs->argv[2], arg) == -1)
251				return -1;
252		}
253		else {
254			/* Insert -o arg at the beginning. */
255			if (fuse_opt_insert_arg(outargs, 1, "-o") == -1)
256				return -1;
257			if (fuse_opt_insert_arg(outargs, 2, arg) == -1)
258				return -1;
259		}
260	}
261	else {
262		if (fuse_opt_add_arg(outargs, arg) == -1)
263			return -1;
264	}
265
266	return 0;
267}
268
269/* Skip the current argv if possible. */
270static int next_arg(const struct fuse_args *args, int *i)
271{
272	if (*i + 1 >= args->argc) {
273		(void)fprintf(stderr, "fuse: missing argument"
274				" after '%s'\n", args->argv[*i]);
275		return -1;
276	}
277	else {
278		*i += 1;
279		return 0;
280	}
281}
282
283/* Parse a single argument with a matched template. */
284static int
285parse_matched_arg(const char* arg, struct fuse_args *outargs,
286		const struct fuse_opt* opt, ssize_t sep_idx, void* data,
287		fuse_opt_proc_t proc, bool is_opt)
288{
289	if (opt->offset == -1) {
290		/* The option description does not want any variables to be
291		 * updated.*/
292		if (call_proc(proc, data, arg, opt->value, outargs, is_opt) == -1)
293			return -1;
294	}
295	else {
296		void *var = (char*)data + opt->offset;
297
298		if (sep_idx > 0 && opt->templ[sep_idx + 1] == '%') {
299			/* "foo=%y" or "-x %y" */
300			const char* param =
301				opt->templ[sep_idx] == '=' ? &arg[sep_idx + 1] : &arg[sep_idx];
302
303			if (opt->templ[sep_idx + 2] == 's') {
304				char* dup = strdup(param);
305				if (dup == NULL)
306					return -1;
307
308				*(char **)var = dup;
309			}
310			else {
311				/* The format string is not a literal. We all know
312				 * this is a bad idea but it's exactly what fuse_opt
313				 * wants to do... */
314#pragma GCC diagnostic push
315#pragma GCC diagnostic ignored "-Wformat-nonliteral"
316				if (sscanf(param, &opt->templ[sep_idx + 1], var) == -1) {
317#pragma GCC diagnostic pop
318					(void)fprintf(stderr, "fuse: '%s' is not a "
319								"valid parameter for option '%.*s'\n",
320								param, (int)sep_idx, opt->templ);
321					return -1;
322				}
323			}
324		}
325		else {
326			/* No parameter format is given. */
327			*(int *)var = opt->value;
328		}
329	}
330	return 0;
331}
332
333/* Parse a single argument with matching templates. */
334static int
335parse_arg(struct fuse_args* args, int *argi, const char* arg,
336		struct fuse_args *outargs, void *data,
337		const struct fuse_opt *opts, fuse_opt_proc_t proc, bool is_opt)
338{
339	ssize_t sep_idx;
340	const struct fuse_opt *opt = find_opt(opts, arg, &sep_idx);
341
342	if (opt) {
343		/* An argument can match to multiple templates. Process them
344		 * all. */
345		for (; opt != NULL && opt->templ != NULL;
346			opt = find_opt(++opt, arg, &sep_idx)) {
347
348			if (sep_idx > 0 && opt->templ[sep_idx] == ' ' &&
349				arg[sep_idx] == '\0') {
350				/* The template "-x %y" requests a separate
351				 * parameter "%y". Try to find one. */
352				char *new_arg;
353				int rv;
354
355				if (next_arg(args, argi) == -1)
356					return -1;
357
358				/* ...but processor callbacks expect a concatenated
359				 * argument "-xfoo". */
360				if ((new_arg = malloc((size_t)sep_idx +
361									strlen(args->argv[*argi]) + 1)) == NULL)
362					return -1;
363
364				strncpy(new_arg, arg, (size_t)sep_idx); /* -x */
365				strcpy(new_arg + sep_idx, args->argv[*argi]); /* foo */
366				rv = parse_matched_arg(new_arg, outargs, opt, sep_idx,
367									data, proc, is_opt);
368				free(new_arg);
369
370				if (rv == -1)
371					return -1;
372			}
373			else {
374				int rv;
375				rv = parse_matched_arg(arg, outargs, opt, sep_idx,
376									data, proc, is_opt);
377				if (rv == -1)
378					return -1;
379			}
380		}
381		return 0;
382	}
383	else {
384		/* No templates matched to it so just invoke the callback. */
385		return call_proc(proc, data, arg, FUSE_OPT_KEY_OPT, outargs, is_opt);
386	}
387}
388
389/* Parse a comma-separated list of options which possibly has escaped
390 * characters. */
391static int
392parse_opts(struct fuse_args *args, int *argi, const char* arg,
393		struct fuse_args *outargs, void *data,
394		const struct fuse_opt *opts, fuse_opt_proc_t proc)
395{
396	char *opt;
397	size_t i, opt_len = 0;
398
399	/* An unescaped option can never be longer than the original
400	 * list. */
401	if ((opt = malloc(strlen(arg) + 1)) == NULL)
402		return -1;
403
404	for (i = 0; i < strlen(arg); i++) {
405		if (arg[i] == ',') {
406			opt[opt_len] = '\0';
407			if (parse_arg(args, argi, opt, outargs,
408						data, opts, proc, true) == -1) {
409				free(opt);
410				return -1;
411			}
412			/* Start a new option. */
413			opt_len = 0;
414		}
415		else if (arg[i] == '\\' && arg[i+1] != '\0') {
416			/* Unescape it. */
417			opt[opt_len++] = arg[i+1];
418			i++;
419		}
420		else {
421			opt[opt_len++] = arg[i];
422		}
423	}
424
425	/* Parse the last option here. */
426	opt[opt_len] = '\0';
427	if (parse_arg(args, argi, opt, outargs, data, opts, proc, true) == -1) {
428		free(opt);
429		return -1;
430	}
431
432	free(opt);
433	return 0;
434}
435
436static int
437parse_all(struct fuse_args *args, struct fuse_args *outargs, void *data,
438		const struct fuse_opt *opts, fuse_opt_proc_t proc)
439{
440	bool nonopt = false; /* Have we seen the "--" marker? */
441	int i;
442
443	/* The first argument, the program name, is implicitly
444	 * FUSE_OPT_KEY_KEEP. */
445	if (args->argc > 0) {
446		if (fuse_opt_add_arg(outargs, args->argv[0]) == -1)
447			return -1;
448	}
449
450	/* the real loop to process the arguments */
451	for (i = 1; i < args->argc; i++) {
452		const char *arg = args->argv[i];
453
454		/* argvn != -foo... */
455		if (nonopt || arg[0] != '-') {
456			if (call_proc(proc, data, arg, FUSE_OPT_KEY_NONOPT,
457						outargs, false) == -1)
458				return -1;
459		}
460		/* -o or -ofoo */
461		else if (arg[1] == 'o') {
462			/* -oblah,foo... */
463			if (arg[2] != '\0') {
464				/* skip -o */
465				if (parse_opts(args, &i, arg + 2, outargs,
466							data, opts, proc) == -1)
467					return -1;
468			}
469			/* -o blah,foo... */
470			else {
471				if (next_arg(args, &i) == -1)
472					return -1;
473				if (parse_opts(args, &i, args->argv[i], outargs,
474							data, opts, proc) == -1)
475					return -1;
476			}
477		}
478		/* -- */
479		else if (arg[1] == '-' && arg[2] == '\0') {
480			if (fuse_opt_add_arg(outargs, arg) == -1)
481				return -1;
482			nonopt = true;
483		}
484		/* -foo */
485		else {
486			if (parse_arg(args, &i, arg, outargs,
487						data, opts, proc, false) == -1)
488				return -1;
489		}
490	}
491
492	/* The "--" marker at the last of outargs should be removed */
493	if (nonopt && strcmp(outargs->argv[outargs->argc - 1], "--") == 0) {
494		free(outargs->argv[outargs->argc - 1]);
495		outargs->argv[--outargs->argc] = NULL;
496	}
497
498	return 0;
499}
500
501int
502fuse_opt_parse(struct fuse_args *args, void *data,
503		const struct fuse_opt *opts, fuse_opt_proc_t proc)
504{
505	struct fuse_args outargs = FUSE_ARGS_INIT(0, NULL);
506	int rv;
507
508	if (!args || !args->argv || !args->argc)
509		return 0;
510
511	rv = parse_all(args, &outargs, data, opts, proc);
512	if (rv != -1) {
513		/* Succeeded. Swap the outargs and args. */
514		struct fuse_args tmp = *args;
515		*args = outargs;
516		outargs = tmp;
517	}
518
519	fuse_opt_free_args(&outargs);
520	return rv;
521}
522