xref: /netbsd-src/usr.sbin/nfsd/nfsd.c (revision 6cd39ddb8550f6fa1bff3fed32053d7f19fd0453)
1 /*	$NetBSD: nfsd.c,v 1.65 2015/12/23 18:41:54 christos Exp $	*/
2 
3 /*
4  * Copyright (c) 1989, 1993, 1994
5  *	The Regents of the University of California.  All rights reserved.
6  *
7  * This code is derived from software contributed to Berkeley by
8  * Rick Macklem at The University of Guelph.
9  *
10  * Redistribution and use in source and binary forms, with or without
11  * modification, are permitted provided that the following conditions
12  * are met:
13  * 1. Redistributions of source code must retain the above copyright
14  *    notice, this list of conditions and the following disclaimer.
15  * 2. Redistributions in binary form must reproduce the above copyright
16  *    notice, this list of conditions and the following disclaimer in the
17  *    documentation and/or other materials provided with the distribution.
18  * 3. Neither the name of the University nor the names of its contributors
19  *    may be used to endorse or promote products derived from this software
20  *    without specific prior written permission.
21  *
22  * THIS SOFTWARE IS PROVIDED BY THE REGENTS 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 REGENTS 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 #include <sys/cdefs.h>
36 #ifndef lint
37 __COPYRIGHT("@(#) Copyright (c) 1989, 1993, 1994\
38  The Regents of the University of California.  All rights reserved.");
39 #endif /* not lint */
40 
41 #ifndef lint
42 #if 0
43 static char sccsid[] = "@(#)nfsd.c	8.9 (Berkeley) 3/29/95";
44 #else
45 __RCSID("$NetBSD: nfsd.c,v 1.65 2015/12/23 18:41:54 christos Exp $");
46 #endif
47 #endif /* not lint */
48 
49 #include <sys/param.h>
50 #include <sys/ioctl.h>
51 #include <sys/stat.h>
52 #include <sys/wait.h>
53 #include <sys/uio.h>
54 #include <sys/ucred.h>
55 #include <sys/mount.h>
56 #include <sys/socket.h>
57 #include <sys/socketvar.h>
58 #include <poll.h>
59 
60 #include <rpc/rpc.h>
61 #include <rpc/pmap_clnt.h>
62 #include <rpc/pmap_prot.h>
63 
64 #include <nfs/rpcv2.h>
65 #include <nfs/nfsproto.h>
66 #include <nfs/nfs.h>
67 
68 #include <err.h>
69 #include <errno.h>
70 #include <fcntl.h>
71 #include <grp.h>
72 #include <paths.h>
73 #include <pwd.h>
74 #include <pthread.h>
75 #include <signal.h>
76 #include <stdio.h>
77 #include <stdlib.h>
78 #include <string.h>
79 #include <syslog.h>
80 #include <unistd.h>
81 #include <netdb.h>
82 
83 #ifdef NFSD_RUMP
84 #include <rump/rump.h>
85 #include <rump/rump_syscalls.h>
86 
87 #define nfssvc(a, b) rump_sys_nfssvc((a), (b))
88 #define close(a)	rump_sys_close(a)
89 #define poll(a, b, c) rump_sys_poll((a), (b), (c))
90 #if 0
91 #define socket(a, b, c) rump_sys_socket((a), (b), (c))
92 #define setsockopt(a, b, c, d, e) rump_sys_setsockopt((a), (b), (c), (d), (e))
93 #define bind(a, b, c) rump_sys_bind((a), (b), (c))
94 #define listen(a, b) rump_sys_listen((a), (b))
95 #define accept(a, b, c) rump_sys_accept((a), (b), (c))
96 #endif
97 #define main nfsd_main
98 int nfsd_main(int, char *[]);
99 #endif
100 
101 /* Global defs */
102 #if defined(DEBUG) || defined(NFSD_RUMP)
103 #define	syslog(e, s, args...)						\
104 do {									\
105     fprintf(stderr,(s), ## args);					\
106     fprintf(stderr, "\n");						\
107 } while (/*CONSTCOND*/0)
108 static int	debug = 1;
109 #else
110 static int	debug = 0;
111 #endif
112 
113 static void	nonfs(int);
114 __dead static void	usage(void);
115 
116 static void *
117 worker(void *dummy)
118 {
119 	struct	nfsd_srvargs nsd;
120 	int nfssvc_flag;
121 
122 	pthread_setname_np(pthread_self(), "slave", NULL);
123 	nfssvc_flag = NFSSVC_NFSD;
124 	memset(&nsd, 0, sizeof(nsd));
125 	while (nfssvc(nfssvc_flag, &nsd) < 0) {
126 		if (errno != ENEEDAUTH) {
127 			syslog(LOG_ERR, "nfssvc: %s", strerror(errno));
128 			exit(1);
129 		}
130 		nfssvc_flag = NFSSVC_NFSD | NFSSVC_AUTHINFAIL;
131 	}
132 
133 	return NULL;
134 }
135 
136 struct conf {
137 	struct addrinfo *ai;
138 	struct netconfig *nc;
139 	struct netbuf nb;
140 	struct pollfd pfd;
141 };
142 
143 #define NFS_UDP4	0
144 #define NFS_TCP4	1
145 #define NFS_UDP6	2
146 #define NFS_TCP6	3
147 
148 static int cfg_family[] = { PF_INET, PF_INET, PF_INET6, PF_INET6 };
149 static const char *cfg_netconf[] = { "udp", "tcp", "udp6", "tcp6" };
150 static int cfg_socktype[] = {
151     SOCK_DGRAM, SOCK_STREAM, SOCK_DGRAM, SOCK_STREAM };
152 static int cfg_protocol[] = {
153     IPPROTO_UDP, IPPROTO_TCP, IPPROTO_UDP, IPPROTO_TCP };
154 
155 static int
156 tryconf(struct conf *cfg, int t, int reregister)
157 {
158 	struct addrinfo hints;
159 	int ecode;
160 
161 	memset(&hints, 0, sizeof hints);
162 	hints.ai_flags = AI_PASSIVE;
163 	hints.ai_family = cfg_family[t];
164 	hints.ai_socktype = cfg_socktype[t];
165 	hints.ai_protocol = cfg_protocol[t];
166 
167 	ecode = getaddrinfo(NULL, "nfs", &hints, &cfg->ai);
168 	if (ecode != 0) {
169 		syslog(LOG_ERR, "getaddrinfo %s: %s", cfg_netconf[t],
170 		    gai_strerror(ecode));
171 		return -1;
172 	}
173 
174 	cfg->nc = getnetconfigent(cfg_netconf[t]);
175 
176 	if (cfg->nc == NULL) {
177 		syslog(LOG_ERR, "getnetconfigent %s failed: %s",
178 		    cfg_netconf[t], strerror(errno));
179 		goto out;
180 	}
181 
182 	cfg->nb.buf = cfg->ai->ai_addr;
183 	cfg->nb.len = cfg->nb.maxlen = cfg->ai->ai_addrlen;
184 	if (reregister)
185 		if (!rpcb_set(RPCPROG_NFS, 2, cfg->nc, &cfg->nb)) {
186 			syslog(LOG_ERR, "rpcb_set %s failed", cfg_netconf[t]);
187 			goto out1;
188 		}
189 	return 0;
190 out1:
191 	freenetconfigent(cfg->nc);
192 	cfg->nc = NULL;
193 out:
194 	freeaddrinfo(cfg->ai);
195 	cfg->ai = NULL;
196 	return -1;
197 }
198 
199 static int
200 setupsock(struct conf *cfg, struct pollfd *set, int p)
201 {
202 	int sock;
203 	struct nfsd_args nfsdargs;
204 	struct addrinfo *ai = cfg->ai;
205 	int on = 1;
206 
207 	sock = socket(ai->ai_family, ai->ai_socktype, ai->ai_protocol);
208 
209 	if (sock == -1) {
210 		syslog(LOG_ERR, "can't create %s socket: %s", cfg_netconf[p],
211 		    strerror(errno));
212 		return -1;
213 	}
214 	if (cfg_family[p] == PF_INET6) {
215 		if (setsockopt(sock, IPPROTO_IPV6, IPV6_V6ONLY, &on,
216 		    sizeof(on)) == -1) {
217 			syslog(LOG_ERR, "can't set v6-only binding for %s "
218 			    "socket: %s", cfg_netconf[p], strerror(errno));
219 			goto out;
220 		}
221 	}
222 
223 	if (cfg_protocol[p] == IPPROTO_TCP) {
224 		if (setsockopt(sock, SOL_SOCKET, SO_REUSEADDR, &on,
225 		    sizeof(on)) == -1) {
226 			syslog(LOG_ERR, "setsockopt SO_REUSEADDR for %s: %s",
227 			    cfg_netconf[p], strerror(errno));
228 			goto out;
229 		}
230 	}
231 
232 	if (bind(sock, ai->ai_addr, ai->ai_addrlen) == -1) {
233 		syslog(LOG_ERR, "can't bind %s addr: %s", cfg_netconf[p],
234 		    strerror(errno));
235 		goto out;
236 	}
237 
238 	if (cfg_protocol[p] == IPPROTO_TCP) {
239 		if (listen(sock, 5) == -1) {
240 			syslog(LOG_ERR, "listen failed");
241 			goto out;
242 		}
243 	}
244 
245 	if (!rpcb_set(RPCPROG_NFS, 2, cfg->nc, &cfg->nb) ||
246 	    !rpcb_set(RPCPROG_NFS, 3, cfg->nc, &cfg->nb)) {
247 		syslog(LOG_ERR, "can't register with %s portmap",
248 		    cfg_netconf[p]);
249 		goto out;
250 	}
251 
252 
253 	if (cfg_protocol[p] == IPPROTO_TCP)
254 		set->fd = sock;
255 	else {
256 		nfsdargs.sock = sock;
257 		nfsdargs.name = NULL;
258 		nfsdargs.namelen = 0;
259 		if (nfssvc(NFSSVC_ADDSOCK, &nfsdargs) < 0) {
260 			syslog(LOG_ERR, "can't add %s socket: %s",
261 			    cfg_netconf[p], strerror(errno));
262 			goto out;
263 		}
264 		(void)close(sock);
265 	}
266 	return 0;
267 out:
268 	(void)close(sock);
269 	return -1;
270 }
271 
272 /*
273  * The functions daemon2_fork() and daemon2_detach() below provide
274  * functionality similar to daemon(3) but split into two phases.
275  * daemon2_fork() is called early, before creating resources that
276  * cannot be inherited across a fork, such as threads or kqueues.
277  * When the daemon is ready to provide service, daemon2_detach()
278  * is called to complete the daemonization and signal the parent
279  * process to exit.
280  *
281  * These functions could potentially be moved to a library and
282  * shared by other daemons.
283  *
284  * The return value from daemon2_fork() is a file descriptor to
285  * be passed as the first argument to daemon2_detach().
286  */
287 
288 static int
289 daemon2_fork(void)
290 {
291 	 int i;
292 	 int fd;
293 	 int r;
294 	 pid_t pid;
295 	 int detach_msg_pipe[2];
296 
297 	 /*
298 	  * Set up a pipe for signalling the parent, making sure the
299 	  * write end does not get allocated one of the file
300 	  * descriptors that may be closed in daemon2_detach().  The
301 	  * read end does not need such protection.
302 	  */
303 	 for (i = 0; i < 3; i++) {
304 		 r = pipe2(detach_msg_pipe, O_CLOEXEC|O_NOSIGPIPE);
305 		 if (r < 0)
306 			 return -1;
307 		 if (detach_msg_pipe[1] <= STDERR_FILENO &&
308 		     (fd = open(_PATH_DEVNULL, O_RDWR, 0)) != -1) {
309 			 (void)dup2(fd, detach_msg_pipe[0]);
310 			 (void)dup2(fd, detach_msg_pipe[1]);
311 			 if (fd > STDERR_FILENO)
312 				 (void)close(fd);
313 			 continue;
314 		 }
315 		 break;
316 	 }
317 
318 	 pid = fork();
319 	 switch (pid) {
320 	 case -1:
321 		 return -1;
322 	 case 0:
323 		 /* child */
324 		 (void)close(detach_msg_pipe[0]);
325 		 return detach_msg_pipe[1];
326 	 default:
327 		 break;
328 	}
329 
330 	/* Parent */
331 	(void)close(detach_msg_pipe[1]);
332 
333 	for (;;) {
334 		ssize_t nread;
335 		char dummy;
336 		nread = read(detach_msg_pipe[0], &dummy, 1);
337 		if (nread < 0) {
338 			if (errno == EINTR)
339 				continue;
340 			_exit(1);
341 		} else if (nread == 0) {
342 			_exit(1);
343 		} else { /* nread > 0 */
344 			_exit(0);
345 		}
346 	}
347 }
348 
349 static int
350 daemon2_detach(int parentfd, int nochdir, int noclose)
351 {
352 	int fd;
353 
354 	if (setsid() == -1)
355 		return -1;
356 
357 	if (!nochdir)
358 		(void)chdir("/");
359 
360 	if (!noclose && (fd = open(_PATH_DEVNULL, O_RDWR, 0)) != -1) {
361 		(void)dup2(fd, STDIN_FILENO);
362 		(void)dup2(fd, STDOUT_FILENO);
363 		(void)dup2(fd, STDERR_FILENO);
364 		if (fd > STDERR_FILENO)
365 			(void)close(fd);
366 	}
367 
368 	while (1) {
369 		ssize_t r = write(parentfd, "", 1);
370 		if (r < 0) {
371 			if (errno == EINTR)
372 				continue;
373 			else if (errno == EPIPE)
374 				break;
375 			else
376 				return -1;
377 		} else if (r == 0) {
378 			/* Should not happen */
379 			return -1;
380 		} else {
381 			break;
382 		}
383 	}
384 
385 	(void)close(parentfd);
386 
387 	return 0;
388 }
389 
390 /*
391  * Nfs server daemon mostly just a user context for nfssvc()
392  *
393  * 1 - do file descriptor and signal cleanup
394  * 2 - create the nfsd thread(s)
395  * 3 - create server socket(s)
396  * 4 - register socket with portmap
397  *
398  * For connectionless protocols, just pass the socket into the kernel via
399  * nfssvc().
400  * For connection based sockets, loop doing accepts. When you get a new
401  * socket from accept, pass the msgsock into the kernel via nfssvc().
402  * The arguments are:
403  *	-r - reregister with portmapper
404  *	-t - support only tcp nfs clients
405  *	-u - support only udp nfs clients
406  *	-n num how many threads to create.
407  *	-4 - use only ipv4
408  *	-6 - use only ipv6
409  */
410 int
411 main(int argc, char *argv[])
412 {
413 	struct conf cfg[4];
414 	struct pollfd set[__arraycount(cfg)];
415 	int ch, connect_type_cnt;
416 	size_t i, nfsdcnt;
417 	int reregister;
418 	int tcpflag, udpflag;
419 	int ip6flag, ip4flag;
420 	int s, compat;
421 	int parent_fd = -1;
422 
423 #define	DEFNFSDCNT	 4
424 	nfsdcnt = DEFNFSDCNT;
425 	compat = reregister = 0;
426 	tcpflag = udpflag = 1;
427 	ip6flag = ip4flag = 1;
428 #define	GETOPT	"46n:rtu"
429 #define	USAGE	"[-46rtu] [-n num_servers]"
430 	while ((ch = getopt(argc, argv, GETOPT)) != -1) {
431 		switch (ch) {
432 		case '6':
433 			ip6flag = 1;
434 			ip4flag = 0;
435 			s = socket(PF_INET6, SOCK_DGRAM, IPPROTO_UDP);
436 			if (s < 0 && (errno == EPROTONOSUPPORT ||
437 			    errno == EPFNOSUPPORT || errno == EAFNOSUPPORT))
438 				ip6flag = 0;
439 			else
440 				close(s);
441 			break;
442 		case '4':
443 			ip6flag = 0;
444 			ip4flag = 1;
445 			s = socket(PF_INET, SOCK_DGRAM, IPPROTO_UDP);
446 			if (s < 0 && (errno == EPROTONOSUPPORT ||
447 			    errno == EPFNOSUPPORT || errno == EAFNOSUPPORT))
448 				ip4flag = 0;
449 			else
450 				close(s);
451 			break;
452 		case 'n':
453 			nfsdcnt = atoi(optarg);
454 			if (nfsdcnt < 1) {
455 				warnx("nfsd count %zu; reset to %d", nfsdcnt,
456 				    DEFNFSDCNT);
457 				nfsdcnt = DEFNFSDCNT;
458 			}
459 			break;
460 		case 'r':
461 			reregister = 1;
462 			break;
463 		case 't':
464 			compat |= 2;
465 			tcpflag = 1;
466 			udpflag = 0;
467 			break;
468 		case 'u':
469 			compat |= 1;
470 			tcpflag = 0;
471 			udpflag = 1;
472 			break;
473 		default:
474 		case '?':
475 			usage();
476 		}
477 	}
478 	argv += optind;
479 	argc -= optind;
480 
481 	if (compat == 3) {
482 		warnx("Old -tu options detected; enabling both udp and tcp.");
483 		warnx("This is the default behavior now and you can remove");
484 		warnx("all options.");
485 		tcpflag = udpflag = 1;
486 		if (ip6flag == 1 && ip4flag == 0)
487 			ip4flag = 1;
488 	}
489 
490 	if (debug == 0) {
491 		parent_fd = daemon2_fork();
492 	}
493 
494 	openlog("nfsd", LOG_PID, LOG_DAEMON);
495 
496 	memset(cfg, 0, sizeof(cfg));
497 	for (i = 0; i < __arraycount(cfg); i++) {
498 		if (ip4flag == 0 && cfg_family[i] == PF_INET)
499 			continue;
500 		if (ip6flag == 0 && cfg_family[i] == PF_INET6)
501 			continue;
502 		if (tcpflag == 0 && cfg_protocol[i] == IPPROTO_TCP)
503 			continue;
504 		if (udpflag == 0 && cfg_protocol[i] == IPPROTO_UDP)
505 			continue;
506 		tryconf(&cfg[i], i, reregister);
507 	}
508 
509 	for (i = 0; i < nfsdcnt; i++) {
510 		pthread_t t;
511 		int error;
512 
513 		error = pthread_create(&t, NULL, worker, NULL);
514 		if (error) {
515 			errno = error;
516 			syslog(LOG_ERR, "pthread_create: %s", strerror(errno));
517 			exit(1);
518 		}
519 	}
520 
521 	connect_type_cnt = 0;
522 	for (i = 0; i < __arraycount(cfg); i++) {
523 		set[i].fd = -1;
524 		set[i].events = POLLIN;
525 		set[i].revents = 0;
526 
527 		if (cfg[i].nc == NULL)
528 			continue;
529 
530 		setupsock(&cfg[i], &set[i], i);
531 		if (set[i].fd != -1)
532 			connect_type_cnt++;
533 
534 	}
535 
536 	if (connect_type_cnt == 0)
537 		exit(0);
538 
539 	pthread_setname_np(pthread_self(), "master", NULL);
540 
541 	if (debug == 0) {
542 		daemon2_detach(parent_fd, 0, 0);
543 		(void)signal(SIGHUP, SIG_IGN);
544 		(void)signal(SIGINT, SIG_IGN);
545 		(void)signal(SIGQUIT, SIG_IGN);
546 		(void)signal(SIGSYS, nonfs);
547 	}
548 
549 	/*
550 	 * Loop forever accepting connections and passing the sockets
551 	 * into the kernel for the mounts.
552 	 */
553 	for (;;) {
554 		if (poll(set, __arraycount(set), INFTIM) == -1) {
555 			syslog(LOG_ERR, "poll failed: %s", strerror(errno));
556 			exit(1);
557 		}
558 
559 		for (i = 0; i < __arraycount(set); i++) {
560 			struct nfsd_args nfsdargs;
561 			struct sockaddr_storage ss;
562 			socklen_t len;
563 			int msgsock;
564 			int on = 1;
565 
566 			if ((set[i].revents & POLLIN) == 0)
567 				continue;
568 			len = sizeof(ss);
569 			if ((msgsock = accept(set[i].fd,
570 			    (struct sockaddr *)&ss, &len)) == -1) {
571 				int serrno = errno;
572 				syslog(LOG_ERR, "accept failed: %s",
573 				    strerror(errno));
574 				if (serrno == EINTR || serrno == ECONNABORTED)
575 					continue;
576 				exit(1);
577 			}
578 			if (setsockopt(msgsock, SOL_SOCKET, SO_KEEPALIVE, &on,
579 			    sizeof(on)) == -1)
580 				syslog(LOG_ERR, "setsockopt SO_KEEPALIVE: %s",
581 				    strerror(errno));
582 			nfsdargs.sock = msgsock;
583 			nfsdargs.name = (void *)&ss;
584 			nfsdargs.namelen = len;
585 			nfssvc(NFSSVC_ADDSOCK, &nfsdargs);
586 			(void)close(msgsock);
587 		}
588 	}
589 }
590 
591 static void
592 usage(void)
593 {
594 	(void)fprintf(stderr, "Usage: %s %s\n", getprogname(), USAGE);
595 	exit(1);
596 }
597 
598 static void
599 nonfs(int signo)
600 {
601 	syslog(LOG_ERR, "missing system call: NFS not available.");
602 }
603