xref: /freebsd/usr.sbin/autofs/automountd.c (revision 26a222dc0c048fc071b548eadad7b80405a1b126)
1 /*-
2  * Copyright (c) 2014 The FreeBSD Foundation
3  * All rights reserved.
4  *
5  * This software was developed by Edward Tomasz Napierala under sponsorship
6  * from the FreeBSD Foundation.
7  *
8  * Redistribution and use in source and binary forms, with or without
9  * modification, are permitted provided that the following conditions
10  * are met:
11  * 1. Redistributions of source code must retain the above copyright
12  *    notice, this list of conditions and the following disclaimer.
13  * 2. Redistributions in binary form must reproduce the above copyright
14  *    notice, this list of conditions and the following disclaimer in the
15  *    documentation and/or other materials provided with the distribution.
16  *
17  * THIS SOFTWARE IS PROVIDED BY THE AUTHOR AND CONTRIBUTORS ``AS IS'' AND
18  * ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
19  * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE
20  * ARE DISCLAIMED.  IN NO EVENT SHALL THE AUTHOR OR CONTRIBUTORS BE LIABLE
21  * FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL
22  * DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS
23  * OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION)
24  * HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT
25  * LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY
26  * OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF
27  * SUCH DAMAGE.
28  *
29  */
30 
31 #include <sys/cdefs.h>
32 __FBSDID("$FreeBSD$");
33 
34 #include <sys/types.h>
35 #include <sys/time.h>
36 #include <sys/ioctl.h>
37 #include <sys/param.h>
38 #include <sys/linker.h>
39 #include <sys/mount.h>
40 #include <sys/socket.h>
41 #include <sys/stat.h>
42 #include <sys/wait.h>
43 #include <sys/utsname.h>
44 #include <assert.h>
45 #include <ctype.h>
46 #include <errno.h>
47 #include <fcntl.h>
48 #include <libgen.h>
49 #include <netdb.h>
50 #include <signal.h>
51 #include <stdbool.h>
52 #include <stdint.h>
53 #include <stdio.h>
54 #include <stdlib.h>
55 #include <string.h>
56 #include <unistd.h>
57 
58 #include <libutil.h>
59 
60 #include "autofs_ioctl.h"
61 
62 #include "common.h"
63 
64 #define AUTOMOUNTD_PIDFILE	"/var/run/automountd.pid"
65 
66 static int nchildren = 0;
67 static int autofs_fd;
68 static int request_id;
69 
70 static void
71 done(int request_error, bool wildcards)
72 {
73 	struct autofs_daemon_done add;
74 	int error;
75 
76 	memset(&add, 0, sizeof(add));
77 	add.add_id = request_id;
78 	add.add_wildcards = wildcards;
79 	add.add_error = request_error;
80 
81 	log_debugx("completing request %d with error %d",
82 	    request_id, request_error);
83 
84 	error = ioctl(autofs_fd, AUTOFSDONE, &add);
85 	if (error != 0)
86 		log_warn("AUTOFSDONE");
87 }
88 
89 /*
90  * Remove "fstype=whatever" from optionsp and return the "whatever" part.
91  */
92 static char *
93 pick_option(const char *option, char **optionsp)
94 {
95 	char *tofree, *pair, *newoptions;
96 	char *picked = NULL;
97 	bool first = true;
98 
99 	tofree = *optionsp;
100 
101 	newoptions = calloc(strlen(*optionsp) + 1, 1);
102 	if (newoptions == NULL)
103 		log_err(1, "calloc");
104 
105 	while ((pair = strsep(optionsp, ",")) != NULL) {
106 		/*
107 		 * XXX: strncasecmp(3) perhaps?
108 		 */
109 		if (strncmp(pair, option, strlen(option)) == 0) {
110 			picked = checked_strdup(pair + strlen(option));
111 		} else {
112 			if (first == false)
113 				strcat(newoptions, ",");
114 			else
115 				first = false;
116 			strcat(newoptions, pair);
117 		}
118 	}
119 
120 	free(tofree);
121 	*optionsp = newoptions;
122 
123 	return (picked);
124 }
125 
126 static void
127 create_subtree(const struct node *node, bool incomplete)
128 {
129 	const struct node *child;
130 	char *path;
131 	bool wildcard_found = false;
132 
133 	/*
134 	 * Skip wildcard nodes.
135 	 */
136 	if (strcmp(node->n_key, "*") == 0)
137 		return;
138 
139 	path = node_path(node);
140 	log_debugx("creating subtree at %s", path);
141 	create_directory(path);
142 
143 	if (incomplete) {
144 		TAILQ_FOREACH(child, &node->n_children, n_next) {
145 			if (strcmp(child->n_key, "*") == 0) {
146 				wildcard_found = true;
147 				break;
148 			}
149 		}
150 
151 		if (wildcard_found) {
152 			log_debugx("node %s contains wildcard entry; "
153 			    "not creating its subdirectories due to -d flag",
154 			    path);
155 			free(path);
156 			return;
157 		}
158 	}
159 
160 	free(path);
161 
162 	TAILQ_FOREACH(child, &node->n_children, n_next)
163 		create_subtree(child, incomplete);
164 }
165 
166 static void
167 exit_callback(void)
168 {
169 
170 	done(EIO, true);
171 }
172 
173 static void
174 handle_request(const struct autofs_daemon_request *adr, char *cmdline_options,
175     bool incomplete_hierarchy)
176 {
177 	const char *map;
178 	struct node *root, *parent, *node;
179 	FILE *f;
180 	char *options, *fstype, *nobrowse, *retrycnt, *tmp;
181 	int error;
182 	bool wildcards;
183 
184 	log_debugx("got request %d: from %s, path %s, prefix \"%s\", "
185 	    "key \"%s\", options \"%s\"", adr->adr_id, adr->adr_from,
186 	    adr->adr_path, adr->adr_prefix, adr->adr_key, adr->adr_options);
187 
188 	/*
189 	 * Try to notify the kernel about any problems.
190 	 */
191 	request_id = adr->adr_id;
192 	atexit(exit_callback);
193 
194 	if (strncmp(adr->adr_from, "map ", 4) != 0) {
195 		log_errx(1, "invalid mountfrom \"%s\"; failing request",
196 		    adr->adr_from);
197 	}
198 
199 	map = adr->adr_from + 4; /* 4 for strlen("map "); */
200 	root = node_new_root();
201 	if (adr->adr_prefix[0] == '\0' || strcmp(adr->adr_prefix, "/") == 0) {
202 		parent = root;
203 	} else {
204 		parent = node_new_map(root, checked_strdup(adr->adr_prefix),
205 		    NULL,  checked_strdup(map),
206 		    checked_strdup("[kernel request]"), lineno);
207 	}
208 
209 	/*
210 	 * "Wildcards" here actually means "make autofs(4) request
211 	 * automountd(8) action if the node being looked up does not
212 	 * exist, even though the parent is marked as cached".  This
213 	 * needs to be done for maps with wildcard entries, but also
214 	 * for special and executable maps.
215 	 */
216 	parse_map(parent, map, adr->adr_key[0] != '\0' ? adr->adr_key : NULL,
217 	    &wildcards);
218 	if (!wildcards)
219 		wildcards = node_has_wildcards(parent);
220 	if (wildcards)
221 		log_debugx("map may contain wildcard entries");
222 	else
223 		log_debugx("map does not contain wildcard entries");
224 
225 	if (adr->adr_key[0] != '\0')
226 		node_expand_wildcard(root, adr->adr_key);
227 
228 	node = node_find(root, adr->adr_path);
229 	if (node == NULL) {
230 		log_errx(1, "map %s does not contain key for \"%s\"; "
231 		    "failing mount", map, adr->adr_path);
232 	}
233 
234 	options = node_options(node);
235 	options = concat(adr->adr_options, ',', options);
236 
237 	/*
238 	 * Prepend options passed via automountd(8) command line.
239 	 */
240 	if (cmdline_options != NULL)
241 		options = concat(cmdline_options, ',', options);
242 
243 	if (node->n_location == NULL) {
244 		log_debugx("found node defined at %s:%d; not a mountpoint",
245 		    node->n_config_file, node->n_config_line);
246 
247 		nobrowse = pick_option("nobrowse", &options);
248 		if (nobrowse != NULL && adr->adr_key[0] == '\0') {
249 			log_debugx("skipping map %s due to \"nobrowse\" "
250 			    "option; exiting", map);
251 			done(0, true);
252 
253 			/*
254 			 * Exit without calling exit_callback().
255 			 */
256 			quick_exit(0);
257 		}
258 
259 		/*
260 		 * Not a mountpoint; create directories in the autofs mount
261 		 * and complete the request.
262 		 */
263 		create_subtree(node, incomplete_hierarchy);
264 
265 		if (incomplete_hierarchy && adr->adr_key[0] != '\0') {
266 			/*
267 			 * We still need to create the single subdirectory
268 			 * user is trying to access.
269 			 */
270 			tmp = concat(adr->adr_path, '/', adr->adr_key);
271 			node = node_find(root, tmp);
272 			if (node != NULL)
273 				create_subtree(node, false);
274 		}
275 
276 		log_debugx("nothing to mount; exiting");
277 		done(0, wildcards);
278 
279 		/*
280 		 * Exit without calling exit_callback().
281 		 */
282 		quick_exit(0);
283 	}
284 
285 	log_debugx("found node defined at %s:%d; it is a mountpoint",
286 	    node->n_config_file, node->n_config_line);
287 
288 	node_expand_ampersand(node,
289 	    adr->adr_key[0] != '\0' ? adr->adr_key : NULL);
290 	error = node_expand_defined(node);
291 	if (error != 0) {
292 		log_errx(1, "variable expansion failed for %s; "
293 		    "failing mount", adr->adr_path);
294 	}
295 
296 	/*
297 	 * Append "automounted".
298 	 */
299 	options = concat(options, ',', "automounted");
300 
301 	/*
302 	 * Remove "nobrowse", mount(8) doesn't understand it.
303 	 */
304 	pick_option("nobrowse", &options);
305 
306 	/*
307 	 * Figure out fstype.
308 	 */
309 	fstype = pick_option("fstype=", &options);
310 	if (fstype == NULL) {
311 		log_debugx("fstype not specified in options; "
312 		    "defaulting to \"nfs\"");
313 		fstype = checked_strdup("nfs");
314 	}
315 
316 	if (strcmp(fstype, "nfs") == 0) {
317 		/*
318 		 * The mount_nfs(8) command defaults to retry undefinitely.
319 		 * We do not want that behaviour, because it leaves mount_nfs(8)
320 		 * instances and automountd(8) children hanging forever.
321 		 * Disable retries unless the option was passed explicitly.
322 		 */
323 		retrycnt = pick_option("retrycnt=", &options);
324 		if (retrycnt == NULL) {
325 			log_debugx("retrycnt not specified in options; "
326 			    "defaulting to 1");
327 			options = concat(options, ',', "retrycnt=1");
328 		} else {
329 			options = concat(options, ',',
330 			    concat("retrycnt", '=', retrycnt));
331 		}
332 	}
333 
334 	f = auto_popen("mount", "-t", fstype, "-o", options,
335 	    node->n_location, adr->adr_path, NULL);
336 	assert(f != NULL);
337 	error = auto_pclose(f);
338 	if (error != 0)
339 		log_errx(1, "mount failed");
340 
341 	log_debugx("mount done; exiting");
342 	done(0, wildcards);
343 
344 	/*
345 	 * Exit without calling exit_callback().
346 	 */
347 	quick_exit(0);
348 }
349 
350 static void
351 sigchld_handler(int dummy __unused)
352 {
353 
354 	/*
355 	 * The only purpose of this handler is to make SIGCHLD
356 	 * interrupt the AUTOFSREQUEST ioctl(2), so we can call
357 	 * wait_for_children().
358 	 */
359 }
360 
361 static void
362 register_sigchld(void)
363 {
364 	struct sigaction sa;
365 	int error;
366 
367 	bzero(&sa, sizeof(sa));
368 	sa.sa_handler = sigchld_handler;
369 	sigfillset(&sa.sa_mask);
370 	error = sigaction(SIGCHLD, &sa, NULL);
371 	if (error != 0)
372 		log_err(1, "sigaction");
373 
374 }
375 
376 
377 static int
378 wait_for_children(bool block)
379 {
380 	pid_t pid;
381 	int status;
382 	int num = 0;
383 
384 	for (;;) {
385 		/*
386 		 * If "block" is true, wait for at least one process.
387 		 */
388 		if (block && num == 0)
389 			pid = wait4(-1, &status, 0, NULL);
390 		else
391 			pid = wait4(-1, &status, WNOHANG, NULL);
392 		if (pid <= 0)
393 			break;
394 		if (WIFSIGNALED(status)) {
395 			log_warnx("child process %d terminated with signal %d",
396 			    pid, WTERMSIG(status));
397 		} else if (WEXITSTATUS(status) != 0) {
398 			log_debugx("child process %d terminated with exit status %d",
399 			    pid, WEXITSTATUS(status));
400 		} else {
401 			log_debugx("child process %d terminated gracefully", pid);
402 		}
403 		num++;
404 	}
405 
406 	return (num);
407 }
408 
409 static void
410 usage_automountd(void)
411 {
412 
413 	fprintf(stderr, "usage: automountd [-D name=value][-m maxproc]"
414 	    "[-o opts][-Tidv]\n");
415 	exit(1);
416 }
417 
418 int
419 main_automountd(int argc, char **argv)
420 {
421 	struct pidfh *pidfh;
422 	pid_t pid, otherpid;
423 	const char *pidfile_path = AUTOMOUNTD_PIDFILE;
424 	char *options = NULL;
425 	struct autofs_daemon_request request;
426 	int ch, debug = 0, error, maxproc = 30, retval, saved_errno;
427 	bool dont_daemonize = false, incomplete_hierarchy = false;
428 
429 	defined_init();
430 
431 	while ((ch = getopt(argc, argv, "D:Tdim:o:v")) != -1) {
432 		switch (ch) {
433 		case 'D':
434 			defined_parse_and_add(optarg);
435 			break;
436 		case 'T':
437 			/*
438 			 * For compatibility with other implementations,
439 			 * such as OS X.
440 			 */
441 			debug++;
442 			break;
443 		case 'd':
444 			dont_daemonize = true;
445 			debug++;
446 			break;
447 		case 'i':
448 			incomplete_hierarchy = true;
449 			break;
450 		case 'm':
451 			maxproc = atoi(optarg);
452 			break;
453 		case 'o':
454 			if (options == NULL) {
455 				options = checked_strdup(optarg);
456 			} else {
457 				options = concat(options, ',', optarg);
458 			}
459 			break;
460 		case 'v':
461 			debug++;
462 			break;
463 		case '?':
464 		default:
465 			usage_automountd();
466 		}
467 	}
468 	argc -= optind;
469 	if (argc != 0)
470 		usage_automountd();
471 
472 	log_init(debug);
473 
474 	pidfh = pidfile_open(pidfile_path, 0600, &otherpid);
475 	if (pidfh == NULL) {
476 		if (errno == EEXIST) {
477 			log_errx(1, "daemon already running, pid: %jd.",
478 			    (intmax_t)otherpid);
479 		}
480 		log_err(1, "cannot open or create pidfile \"%s\"",
481 		    pidfile_path);
482 	}
483 
484 	autofs_fd = open(AUTOFS_PATH, O_RDWR | O_CLOEXEC);
485 	if (autofs_fd < 0 && errno == ENOENT) {
486 		saved_errno = errno;
487 		retval = kldload("autofs");
488 		if (retval != -1)
489 			autofs_fd = open(AUTOFS_PATH, O_RDWR | O_CLOEXEC);
490 		else
491 			errno = saved_errno;
492 	}
493 	if (autofs_fd < 0)
494 		log_err(1, "failed to open %s", AUTOFS_PATH);
495 
496 	if (dont_daemonize == false) {
497 		if (daemon(0, 0) == -1) {
498 			log_warn("cannot daemonize");
499 			pidfile_remove(pidfh);
500 			exit(1);
501 		}
502 	} else {
503 		lesser_daemon();
504 	}
505 
506 	pidfile_write(pidfh);
507 
508 	register_sigchld();
509 
510 	for (;;) {
511 		log_debugx("waiting for request from the kernel");
512 
513 		memset(&request, 0, sizeof(request));
514 		error = ioctl(autofs_fd, AUTOFSREQUEST, &request);
515 		if (error != 0) {
516 			if (errno == EINTR) {
517 				nchildren -= wait_for_children(false);
518 				assert(nchildren >= 0);
519 				continue;
520 			}
521 
522 			log_err(1, "AUTOFSREQUEST");
523 		}
524 
525 		if (dont_daemonize) {
526 			log_debugx("not forking due to -d flag; "
527 			    "will exit after servicing a single request");
528 		} else {
529 			nchildren -= wait_for_children(false);
530 			assert(nchildren >= 0);
531 
532 			while (maxproc > 0 && nchildren >= maxproc) {
533 				log_debugx("maxproc limit of %d child processes hit; "
534 				    "waiting for child process to exit", maxproc);
535 				nchildren -= wait_for_children(true);
536 				assert(nchildren >= 0);
537 			}
538 			log_debugx("got request; forking child process #%d",
539 			    nchildren);
540 			nchildren++;
541 
542 			pid = fork();
543 			if (pid < 0)
544 				log_err(1, "fork");
545 			if (pid > 0)
546 				continue;
547 		}
548 
549 		pidfile_close(pidfh);
550 		handle_request(&request, options, incomplete_hierarchy);
551 	}
552 
553 	pidfile_close(pidfh);
554 
555 	return (0);
556 }
557 
558