xref: /freebsd-14.2/usr.sbin/nfsd/nfsd.c (revision 5a2cd24c)
1 /*-
2  * SPDX-License-Identifier: BSD-3-Clause
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 #ifndef lint
36 static const char copyright[] =
37 "@(#) Copyright (c) 1989, 1993, 1994\n\
38 	The Regents of the University of California.  All rights reserved.\n";
39 #endif /* not lint */
40 
41 #ifndef lint
42 #if 0
43 static char sccsid[] = "@(#)nfsd.c	8.9 (Berkeley) 3/29/95";
44 #endif
45 #endif /* not lint */
46 
47 #include <sys/param.h>
48 #include <sys/syslog.h>
49 #include <sys/wait.h>
50 #include <sys/mount.h>
51 #include <sys/fcntl.h>
52 #include <sys/linker.h>
53 #include <sys/module.h>
54 #include <sys/types.h>
55 #include <sys/stat.h>
56 #include <sys/sysctl.h>
57 #include <sys/ucred.h>
58 
59 #include <rpc/rpc.h>
60 #include <rpc/pmap_clnt.h>
61 #include <rpcsvc/nfs_prot.h>
62 
63 #include <netdb.h>
64 #include <arpa/inet.h>
65 #include <nfs/nfssvc.h>
66 
67 #include <fs/nfs/nfsproto.h>
68 #include <fs/nfs/nfskpiport.h>
69 #include <fs/nfs/nfs.h>
70 
71 #include <err.h>
72 #include <errno.h>
73 #include <signal.h>
74 #include <stdio.h>
75 #include <stdlib.h>
76 #include <string.h>
77 #include <unistd.h>
78 #include <sysexits.h>
79 
80 #include <getopt.h>
81 
82 static int	debug = 0;
83 
84 #define	NFSD_STABLERESTART	"/var/db/nfs-stablerestart"
85 #define	NFSD_STABLEBACKUP	"/var/db/nfs-stablerestart.bak"
86 #define	MAXNFSDCNT	256
87 #define	DEFNFSDCNT	 4
88 #define	NFS_VER2	 2
89 #define NFS_VER3	 3
90 #define NFS_VER4	 4
91 static pid_t children[MAXNFSDCNT]; /* PIDs of children */
92 static pid_t masterpid;		   /* PID of master/parent */
93 static int nfsdcnt;		/* number of children */
94 static int nfsdcnt_set;
95 static int minthreads;
96 static int maxthreads;
97 static int nfssvc_nfsd;		/* Set to correct NFSSVC_xxx flag */
98 static int stablefd = -1;	/* Fd for the stable restart file */
99 static int backupfd;		/* Fd for the backup stable restart file */
100 static const char *getopt_shortopts;
101 static const char *getopt_usage;
102 static int nfs_minvers = NFS_VER2;
103 
104 static int minthreads_set;
105 static int maxthreads_set;
106 
107 static struct option longopts[] = {
108 	{ "debug", no_argument, &debug, 1 },
109 	{ "minthreads", required_argument, &minthreads_set, 1 },
110 	{ "maxthreads", required_argument, &maxthreads_set, 1 },
111 	{ "pnfs", required_argument, NULL, 'p' },
112 	{ "mirror", required_argument, NULL, 'm' },
113 	{ NULL, 0, NULL, 0}
114 };
115 
116 static void	cleanup(int);
117 static void	child_cleanup(int);
118 static void	killchildren(void);
119 static void	nfsd_exit(int);
120 static void	nonfs(int);
121 static void	reapchild(int);
122 static int	setbindhost(struct addrinfo **ia, const char *bindhost,
123 		    struct addrinfo hints);
124 static void	start_server(int, struct nfsd_nfsd_args *, const char *vhost);
125 static void	unregistration(void);
126 static void	usage(void);
127 static void	open_stable(int *, int *);
128 static void	copy_stable(int, int);
129 static void	backup_stable(int);
130 static void	set_nfsdcnt(int);
131 static void	parse_dsserver(const char *, struct nfsd_nfsd_args *);
132 
133 /*
134  * Nfs server daemon mostly just a user context for nfssvc()
135  *
136  * 1 - do file descriptor and signal cleanup
137  * 2 - fork the nfsd(s)
138  * 3 - create server socket(s)
139  * 4 - register socket with rpcbind
140  *
141  * For connectionless protocols, just pass the socket into the kernel via.
142  * nfssvc().
143  * For connection based sockets, loop doing accepts. When you get a new
144  * socket from accept, pass the msgsock into the kernel via. nfssvc().
145  * The arguments are:
146  *	-r - reregister with rpcbind
147  *	-d - unregister with rpcbind
148  *	-t - support tcp nfs clients
149  *	-u - support udp nfs clients
150  *	-e - forces it to run a server that supports nfsv4
151  *	-p - enable a pNFS service
152  *	-m - set the mirroring level for a pNFS service
153  * followed by "n" which is the number of nfsds' to fork off
154  */
155 int
main(int argc,char ** argv)156 main(int argc, char **argv)
157 {
158 	struct nfsd_addsock_args addsockargs;
159 	struct addrinfo *ai_udp, *ai_tcp, *ai_udp6, *ai_tcp6, hints;
160 	struct netconfig *nconf_udp, *nconf_tcp, *nconf_udp6, *nconf_tcp6;
161 	struct netbuf nb_udp, nb_tcp, nb_udp6, nb_tcp6;
162 	struct sockaddr_storage peer;
163 	fd_set ready, sockbits;
164 	int ch, connect_type_cnt, i, maxsock, msgsock;
165 	socklen_t len;
166 	int on = 1, unregister, reregister, sock;
167 	int tcp6sock, ip6flag, tcpflag, tcpsock;
168 	int udpflag, ecode, error, s;
169 	int bindhostc, bindanyflag, rpcbreg, rpcbregcnt;
170 	int nfssvc_addsock;
171 	int jailed, longindex = 0;
172 	size_t jailed_size, nfs_minvers_size;
173 	const char *lopt;
174 	char **bindhost = NULL;
175 	pid_t pid;
176 	struct nfsd_nfsd_args nfsdargs;
177 	const char *vhostname = NULL;
178 
179 	nfsdargs.mirrorcnt = 1;
180 	nfsdargs.addr = NULL;
181 	nfsdargs.addrlen = 0;
182 	nfsdcnt = DEFNFSDCNT;
183 	unregister = reregister = tcpflag = maxsock = 0;
184 	bindanyflag = udpflag = connect_type_cnt = bindhostc = 0;
185 	getopt_shortopts = "ah:n:rdtuep:m:V:";
186 	getopt_usage =
187 	    "usage:\n"
188 	    "  nfsd [-ardtue] [-h bindip]\n"
189 	    "       [-n numservers] [--minthreads #] [--maxthreads #]\n"
190 	    "       [-p/--pnfs dsserver0:/dsserver0-mounted-on-dir,...,"
191 	    "dsserverN:/dsserverN-mounted-on-dir] [-m mirrorlevel]\n"
192 	    "       [-V virtual_hostname]\n";
193 	while ((ch = getopt_long(argc, argv, getopt_shortopts, longopts,
194 		    &longindex)) != -1)
195 		switch (ch) {
196 		case 'V':
197 			if (strlen(optarg) <= MAXHOSTNAMELEN)
198 				vhostname = optarg;
199 			else
200 				warnx("Virtual host name (%s) is too long",
201 				    optarg);
202 			break;
203 		case 'a':
204 			bindanyflag = 1;
205 			break;
206 		case 'n':
207 			set_nfsdcnt(atoi(optarg));
208 			break;
209 		case 'h':
210 			bindhostc++;
211 			bindhost = realloc(bindhost,sizeof(char *)*bindhostc);
212 			if (bindhost == NULL)
213 				errx(1, "Out of memory");
214 			bindhost[bindhostc-1] = strdup(optarg);
215 			if (bindhost[bindhostc-1] == NULL)
216 				errx(1, "Out of memory");
217 			break;
218 		case 'r':
219 			reregister = 1;
220 			break;
221 		case 'd':
222 			unregister = 1;
223 			break;
224 		case 't':
225 			tcpflag = 1;
226 			break;
227 		case 'u':
228 			udpflag = 1;
229 			break;
230 		case 'e':
231 			/* now a no-op, since this is the default */
232 			break;
233 		case 'p':
234 			/* Parse out the DS server host names and mount pts. */
235 			parse_dsserver(optarg, &nfsdargs);
236 			break;
237 		case 'm':
238 			/* Set the mirror level for a pNFS service. */
239 			i = atoi(optarg);
240 			if (i < 2 || i > NFSDEV_MAXMIRRORS)
241 				errx(1, "Mirror level out of range 2<-->%d",
242 				    NFSDEV_MAXMIRRORS);
243 			nfsdargs.mirrorcnt = i;
244 			break;
245 		case 0:
246 			lopt = longopts[longindex].name;
247 			if (!strcmp(lopt, "minthreads")) {
248 				minthreads = atoi(optarg);
249 			} else if (!strcmp(lopt, "maxthreads")) {
250 				maxthreads = atoi(optarg);
251 			}
252 			break;
253 		default:
254 		case '?':
255 			usage();
256 		}
257 	if (!tcpflag && !udpflag)
258 		udpflag = 1;
259 	argv += optind;
260 	argc -= optind;
261 	if (minthreads_set && maxthreads_set && minthreads > maxthreads)
262 		errx(EX_USAGE,
263 		    "error: minthreads(%d) can't be greater than "
264 		    "maxthreads(%d)", minthreads, maxthreads);
265 
266 	/*
267 	 * XXX
268 	 * Backward compatibility, trailing number is the count of daemons.
269 	 */
270 	if (argc > 1)
271 		usage();
272 	if (argc == 1)
273 		set_nfsdcnt(atoi(argv[0]));
274 
275 	/*
276 	 * Unless the "-o" option was specified, try and run "nfsd".
277 	 * If "-o" was specified, try and run "nfsserver".
278 	 */
279 	if (modfind("nfsd") < 0) {
280 		/* Not present in kernel, try loading it */
281 		if (kldload("nfsd") < 0 || modfind("nfsd") < 0)
282 			errx(1, "NFS server is not available");
283 	}
284 
285 	ip6flag = 1;
286 	s = socket(AF_INET6, SOCK_DGRAM, IPPROTO_UDP);
287 	if (s == -1) {
288 		if (errno != EPROTONOSUPPORT && errno != EAFNOSUPPORT)
289 			err(1, "socket");
290 		ip6flag = 0;
291 	} else if (getnetconfigent("udp6") == NULL ||
292 		getnetconfigent("tcp6") == NULL) {
293 		ip6flag = 0;
294 	}
295 	if (s != -1)
296 		close(s);
297 
298 	if (bindhostc == 0 || bindanyflag) {
299 		bindhostc++;
300 		bindhost = realloc(bindhost,sizeof(char *)*bindhostc);
301 		if (bindhost == NULL)
302 			errx(1, "Out of memory");
303 		bindhost[bindhostc-1] = strdup("*");
304 		if (bindhost[bindhostc-1] == NULL)
305 			errx(1, "Out of memory");
306 	}
307 
308 	if (unregister) {
309 		/*
310 		 * Unregister before setting nfs_minvers, in case the
311 		 * value of vfs.nfsd.server_min_nfsvers has changed
312 		 * since registering with rpcbind.
313 		 */
314 		unregistration();
315 		exit (0);
316 	}
317 
318 	nfs_minvers_size = sizeof(nfs_minvers);
319 	error = sysctlbyname("vfs.nfsd.server_min_nfsvers", &nfs_minvers,
320 	    &nfs_minvers_size, NULL, 0);
321 	if (error != 0 || nfs_minvers < NFS_VER2 || nfs_minvers > NFS_VER4) {
322 		warnx("sysctlbyname(vfs.nfsd.server_min_nfsvers) failed,"
323 		    " defaulting to NFSv2");
324 		nfs_minvers = NFS_VER2;
325 	}
326 
327 	if (reregister) {
328 		if (udpflag) {
329 			memset(&hints, 0, sizeof hints);
330 			hints.ai_flags = AI_PASSIVE;
331 			hints.ai_family = AF_INET;
332 			hints.ai_socktype = SOCK_DGRAM;
333 			hints.ai_protocol = IPPROTO_UDP;
334 			ecode = getaddrinfo(NULL, "nfs", &hints, &ai_udp);
335 			if (ecode != 0)
336 				err(1, "getaddrinfo udp: %s", gai_strerror(ecode));
337 			nconf_udp = getnetconfigent("udp");
338 			if (nconf_udp == NULL)
339 				err(1, "getnetconfigent udp failed");
340 			nb_udp.buf = ai_udp->ai_addr;
341 			nb_udp.len = nb_udp.maxlen = ai_udp->ai_addrlen;
342 			if (nfs_minvers == NFS_VER2)
343 				if (!rpcb_set(NFS_PROGRAM, 2, nconf_udp,
344 				    &nb_udp))
345 					err(1, "rpcb_set udp failed");
346 			if (nfs_minvers <= NFS_VER3)
347 				if (!rpcb_set(NFS_PROGRAM, 3, nconf_udp,
348 				    &nb_udp))
349 					err(1, "rpcb_set udp failed");
350 			freeaddrinfo(ai_udp);
351 		}
352 		if (udpflag && ip6flag) {
353 			memset(&hints, 0, sizeof hints);
354 			hints.ai_flags = AI_PASSIVE;
355 			hints.ai_family = AF_INET6;
356 			hints.ai_socktype = SOCK_DGRAM;
357 			hints.ai_protocol = IPPROTO_UDP;
358 			ecode = getaddrinfo(NULL, "nfs", &hints, &ai_udp6);
359 			if (ecode != 0)
360 				err(1, "getaddrinfo udp6: %s", gai_strerror(ecode));
361 			nconf_udp6 = getnetconfigent("udp6");
362 			if (nconf_udp6 == NULL)
363 				err(1, "getnetconfigent udp6 failed");
364 			nb_udp6.buf = ai_udp6->ai_addr;
365 			nb_udp6.len = nb_udp6.maxlen = ai_udp6->ai_addrlen;
366 			if (nfs_minvers == NFS_VER2)
367 				if (!rpcb_set(NFS_PROGRAM, 2, nconf_udp6,
368 				    &nb_udp6))
369 					err(1, "rpcb_set udp6 failed");
370 			if (nfs_minvers <= NFS_VER3)
371 				if (!rpcb_set(NFS_PROGRAM, 3, nconf_udp6,
372 				    &nb_udp6))
373 					err(1, "rpcb_set udp6 failed");
374 			freeaddrinfo(ai_udp6);
375 		}
376 		if (tcpflag) {
377 			memset(&hints, 0, sizeof hints);
378 			hints.ai_flags = AI_PASSIVE;
379 			hints.ai_family = AF_INET;
380 			hints.ai_socktype = SOCK_STREAM;
381 			hints.ai_protocol = IPPROTO_TCP;
382 			ecode = getaddrinfo(NULL, "nfs", &hints, &ai_tcp);
383 			if (ecode != 0)
384 				err(1, "getaddrinfo tcp: %s", gai_strerror(ecode));
385 			nconf_tcp = getnetconfigent("tcp");
386 			if (nconf_tcp == NULL)
387 				err(1, "getnetconfigent tcp failed");
388 			nb_tcp.buf = ai_tcp->ai_addr;
389 			nb_tcp.len = nb_tcp.maxlen = ai_tcp->ai_addrlen;
390 			if (nfs_minvers == NFS_VER2)
391 				if (!rpcb_set(NFS_PROGRAM, 2, nconf_tcp,
392 				    &nb_tcp))
393 					err(1, "rpcb_set tcp failed");
394 			if (nfs_minvers <= NFS_VER3)
395 				if (!rpcb_set(NFS_PROGRAM, 3, nconf_tcp,
396 				    &nb_tcp))
397 					err(1, "rpcb_set tcp failed");
398 			freeaddrinfo(ai_tcp);
399 		}
400 		if (tcpflag && ip6flag) {
401 			memset(&hints, 0, sizeof hints);
402 			hints.ai_flags = AI_PASSIVE;
403 			hints.ai_family = AF_INET6;
404 			hints.ai_socktype = SOCK_STREAM;
405 			hints.ai_protocol = IPPROTO_TCP;
406 			ecode = getaddrinfo(NULL, "nfs", &hints, &ai_tcp6);
407 			if (ecode != 0)
408 				err(1, "getaddrinfo tcp6: %s", gai_strerror(ecode));
409 			nconf_tcp6 = getnetconfigent("tcp6");
410 			if (nconf_tcp6 == NULL)
411 				err(1, "getnetconfigent tcp6 failed");
412 			nb_tcp6.buf = ai_tcp6->ai_addr;
413 			nb_tcp6.len = nb_tcp6.maxlen = ai_tcp6->ai_addrlen;
414 			if (nfs_minvers == NFS_VER2)
415 				if (!rpcb_set(NFS_PROGRAM, 2, nconf_tcp6,
416 				    &nb_tcp6))
417 					err(1, "rpcb_set tcp6 failed");
418 			if (nfs_minvers <= NFS_VER3)
419 				if (!rpcb_set(NFS_PROGRAM, 3, nconf_tcp6,
420 				   &nb_tcp6))
421 					err(1, "rpcb_set tcp6 failed");
422 			freeaddrinfo(ai_tcp6);
423 		}
424 		exit (0);
425 	}
426 	if (debug == 0) {
427 		daemon(0, 0);
428 		(void)signal(SIGHUP, SIG_IGN);
429 		(void)signal(SIGINT, SIG_IGN);
430 		/*
431 		 * nfsd sits in the kernel most of the time.  It needs
432 		 * to ignore SIGTERM/SIGQUIT in order to stay alive as long
433 		 * as possible during a shutdown, otherwise loopback
434 		 * mounts will not be able to unmount.
435 		 */
436 		(void)signal(SIGTERM, SIG_IGN);
437 		(void)signal(SIGQUIT, SIG_IGN);
438 	}
439 	(void)signal(SIGSYS, nonfs);
440 	(void)signal(SIGCHLD, reapchild);
441 	(void)signal(SIGUSR2, backup_stable);
442 
443 	openlog("nfsd", LOG_PID | (debug ? LOG_PERROR : 0), LOG_DAEMON);
444 
445 	/*
446 	 * For V4, we open the stablerestart file and call nfssvc()
447 	 * to get it loaded. This is done before the daemons do the
448 	 * regular nfssvc() call to service NFS requests.
449 	 * (This way the file remains open until the last nfsd is killed
450 	 *  off.)
451 	 * It and the backup copy will be created as empty files
452 	 * the first time this nfsd is started and should never be
453 	 * deleted/replaced if at all possible. It should live on a
454 	 * local, non-volatile storage device that does not do hardware
455 	 * level write-back caching. (See SCSI doc for more information
456 	 * on how to prevent write-back caching on SCSI disks.)
457 	 */
458 	open_stable(&stablefd, &backupfd);
459 	if (stablefd < 0) {
460 		syslog(LOG_ERR, "Can't open %s: %m\n", NFSD_STABLERESTART);
461 		exit(1);
462 	}
463 	/* This system call will fail for old kernels, but that's ok. */
464 	nfssvc(NFSSVC_BACKUPSTABLE, NULL);
465 	if (nfssvc(NFSSVC_STABLERESTART, (caddr_t)&stablefd) < 0) {
466 		if (errno == EPERM) {
467 			jailed = 0;
468 			jailed_size = sizeof(jailed);
469 			sysctlbyname("security.jail.jailed", &jailed,
470 			    &jailed_size, NULL, 0);
471 			if (jailed != 0)
472 				syslog(LOG_ERR, "nfssvc stablerestart failed: "
473 				    "allow.nfsd might not be configured");
474 			else
475 				syslog(LOG_ERR, "nfssvc stablerestart failed");
476 		} else if (errno == ENXIO)
477 			syslog(LOG_ERR, "nfssvc stablerestart failed: is nfsd "
478 			    "already running?");
479 		else
480 			syslog(LOG_ERR, "Can't read stable storage file: %m\n");
481 		exit(1);
482 	}
483 	nfssvc_addsock = NFSSVC_NFSDADDSOCK;
484 	nfssvc_nfsd = NFSSVC_NFSDNFSD | NFSSVC_NEWSTRUCT;
485 
486 	if (tcpflag) {
487 		/*
488 		 * For TCP mode, we fork once to start the first
489 		 * kernel nfsd thread. The kernel will add more
490 		 * threads as needed.
491 		 */
492 		masterpid = getpid();
493 		pid = fork();
494 		if (pid == -1) {
495 			syslog(LOG_ERR, "fork: %m");
496 			nfsd_exit(1);
497 		}
498 		if (pid) {
499 			children[0] = pid;
500 		} else {
501 			(void)signal(SIGUSR1, child_cleanup);
502 			setproctitle("server");
503 			start_server(0, &nfsdargs, vhostname);
504 		}
505 	}
506 
507 	(void)signal(SIGUSR1, cleanup);
508 	FD_ZERO(&sockbits);
509 
510 	rpcbregcnt = 0;
511 	/* Set up the socket for udp and rpcb register it. */
512 	if (udpflag) {
513 		rpcbreg = 0;
514 		for (i = 0; i < bindhostc; i++) {
515 			memset(&hints, 0, sizeof hints);
516 			hints.ai_flags = AI_PASSIVE;
517 			hints.ai_family = AF_INET;
518 			hints.ai_socktype = SOCK_DGRAM;
519 			hints.ai_protocol = IPPROTO_UDP;
520 			if (setbindhost(&ai_udp, bindhost[i], hints) == 0) {
521 				rpcbreg = 1;
522 				rpcbregcnt++;
523 				if ((sock = socket(ai_udp->ai_family,
524 				    ai_udp->ai_socktype,
525 				    ai_udp->ai_protocol)) < 0) {
526 					syslog(LOG_ERR,
527 					    "can't create udp socket");
528 					nfsd_exit(1);
529 				}
530 				if (bind(sock, ai_udp->ai_addr,
531 				    ai_udp->ai_addrlen) < 0) {
532 					syslog(LOG_ERR,
533 					    "can't bind udp addr %s: %m",
534 					    bindhost[i]);
535 					nfsd_exit(1);
536 				}
537 				freeaddrinfo(ai_udp);
538 				addsockargs.sock = sock;
539 				addsockargs.name = NULL;
540 				addsockargs.namelen = 0;
541 				if (nfssvc(nfssvc_addsock, &addsockargs) < 0) {
542 					syslog(LOG_ERR, "can't Add UDP socket");
543 					nfsd_exit(1);
544 				}
545 				(void)close(sock);
546 			}
547 		}
548 		if (rpcbreg == 1) {
549 			memset(&hints, 0, sizeof hints);
550 			hints.ai_flags = AI_PASSIVE;
551 			hints.ai_family = AF_INET;
552 			hints.ai_socktype = SOCK_DGRAM;
553 			hints.ai_protocol = IPPROTO_UDP;
554 			ecode = getaddrinfo(NULL, "nfs", &hints, &ai_udp);
555 			if (ecode != 0) {
556 				syslog(LOG_ERR, "getaddrinfo udp: %s",
557 				   gai_strerror(ecode));
558 				nfsd_exit(1);
559 			}
560 			nconf_udp = getnetconfigent("udp");
561 			if (nconf_udp == NULL) {
562 				syslog(LOG_ERR, "getnetconfigent udp failed");
563 				nfsd_exit(1);
564 			}
565 			nb_udp.buf = ai_udp->ai_addr;
566 			nb_udp.len = nb_udp.maxlen = ai_udp->ai_addrlen;
567 			if (nfs_minvers == NFS_VER2)
568 				if (!rpcb_set(NFS_PROGRAM, 2, nconf_udp,
569 				    &nb_udp)) {
570 					syslog(LOG_ERR, "rpcb_set udp failed");
571 					nfsd_exit(1);
572 				}
573 			if (nfs_minvers <= NFS_VER3)
574 				if (!rpcb_set(NFS_PROGRAM, 3, nconf_udp,
575 				    &nb_udp)) {
576 					syslog(LOG_ERR, "rpcb_set udp failed");
577 					nfsd_exit(1);
578 				}
579 			freeaddrinfo(ai_udp);
580 		}
581 	}
582 
583 	/* Set up the socket for udp6 and rpcb register it. */
584 	if (udpflag && ip6flag) {
585 		rpcbreg = 0;
586 		for (i = 0; i < bindhostc; i++) {
587 			memset(&hints, 0, sizeof hints);
588 			hints.ai_flags = AI_PASSIVE;
589 			hints.ai_family = AF_INET6;
590 			hints.ai_socktype = SOCK_DGRAM;
591 			hints.ai_protocol = IPPROTO_UDP;
592 			if (setbindhost(&ai_udp6, bindhost[i], hints) == 0) {
593 				rpcbreg = 1;
594 				rpcbregcnt++;
595 				if ((sock = socket(ai_udp6->ai_family,
596 				    ai_udp6->ai_socktype,
597 				    ai_udp6->ai_protocol)) < 0) {
598 					syslog(LOG_ERR,
599 						"can't create udp6 socket");
600 					nfsd_exit(1);
601 				}
602 				if (setsockopt(sock, IPPROTO_IPV6, IPV6_V6ONLY,
603 				    &on, sizeof on) < 0) {
604 					syslog(LOG_ERR,
605 					    "can't set v6-only binding for "
606 					    "udp6 socket: %m");
607 					nfsd_exit(1);
608 				}
609 				if (bind(sock, ai_udp6->ai_addr,
610 				    ai_udp6->ai_addrlen) < 0) {
611 					syslog(LOG_ERR,
612 					    "can't bind udp6 addr %s: %m",
613 					    bindhost[i]);
614 					nfsd_exit(1);
615 				}
616 				freeaddrinfo(ai_udp6);
617 				addsockargs.sock = sock;
618 				addsockargs.name = NULL;
619 				addsockargs.namelen = 0;
620 				if (nfssvc(nfssvc_addsock, &addsockargs) < 0) {
621 					syslog(LOG_ERR,
622 					    "can't add UDP6 socket");
623 					nfsd_exit(1);
624 				}
625 				(void)close(sock);
626 			}
627 		}
628 		if (rpcbreg == 1) {
629 			memset(&hints, 0, sizeof hints);
630 			hints.ai_flags = AI_PASSIVE;
631 			hints.ai_family = AF_INET6;
632 			hints.ai_socktype = SOCK_DGRAM;
633 			hints.ai_protocol = IPPROTO_UDP;
634 			ecode = getaddrinfo(NULL, "nfs", &hints, &ai_udp6);
635 			if (ecode != 0) {
636 				syslog(LOG_ERR, "getaddrinfo udp6: %s",
637 				   gai_strerror(ecode));
638 				nfsd_exit(1);
639 			}
640 			nconf_udp6 = getnetconfigent("udp6");
641 			if (nconf_udp6 == NULL) {
642 				syslog(LOG_ERR, "getnetconfigent udp6 failed");
643 				nfsd_exit(1);
644 			}
645 			nb_udp6.buf = ai_udp6->ai_addr;
646 			nb_udp6.len = nb_udp6.maxlen = ai_udp6->ai_addrlen;
647 			if (nfs_minvers == NFS_VER2)
648 				if (!rpcb_set(NFS_PROGRAM, 2, nconf_udp6,
649 				    &nb_udp6)) {
650 					syslog(LOG_ERR,
651 					    "rpcb_set udp6 failed");
652 					nfsd_exit(1);
653 				}
654 			if (nfs_minvers <= NFS_VER3)
655 				if (!rpcb_set(NFS_PROGRAM, 3, nconf_udp6,
656 				    &nb_udp6)) {
657 					syslog(LOG_ERR,
658 					    "rpcb_set udp6 failed");
659 					nfsd_exit(1);
660 				}
661 			freeaddrinfo(ai_udp6);
662 		}
663 	}
664 
665 	/* Set up the socket for tcp and rpcb register it. */
666 	if (tcpflag) {
667 		rpcbreg = 0;
668 		for (i = 0; i < bindhostc; i++) {
669 			memset(&hints, 0, sizeof hints);
670 			hints.ai_flags = AI_PASSIVE;
671 			hints.ai_family = AF_INET;
672 			hints.ai_socktype = SOCK_STREAM;
673 			hints.ai_protocol = IPPROTO_TCP;
674 			if (setbindhost(&ai_tcp, bindhost[i], hints) == 0) {
675 				rpcbreg = 1;
676 				rpcbregcnt++;
677 				if ((tcpsock = socket(AF_INET, SOCK_STREAM,
678 				    0)) < 0) {
679 					syslog(LOG_ERR,
680 					    "can't create tcp socket");
681 					nfsd_exit(1);
682 				}
683 				if (setsockopt(tcpsock, SOL_SOCKET,
684 				    SO_REUSEADDR,
685 				    (char *)&on, sizeof(on)) < 0)
686 					syslog(LOG_ERR,
687 					     "setsockopt SO_REUSEADDR: %m");
688 				if (bind(tcpsock, ai_tcp->ai_addr,
689 				    ai_tcp->ai_addrlen) < 0) {
690 					syslog(LOG_ERR,
691 					    "can't bind tcp addr %s: %m",
692 					    bindhost[i]);
693 					nfsd_exit(1);
694 				}
695 				if (listen(tcpsock, -1) < 0) {
696 					syslog(LOG_ERR, "listen failed");
697 					nfsd_exit(1);
698 				}
699 				freeaddrinfo(ai_tcp);
700 				FD_SET(tcpsock, &sockbits);
701 				maxsock = tcpsock;
702 				connect_type_cnt++;
703 			}
704 		}
705 		if (rpcbreg == 1) {
706 			memset(&hints, 0, sizeof hints);
707 			hints.ai_flags = AI_PASSIVE;
708 			hints.ai_family = AF_INET;
709 			hints.ai_socktype = SOCK_STREAM;
710 			hints.ai_protocol = IPPROTO_TCP;
711 			ecode = getaddrinfo(NULL, "nfs", &hints,
712 			     &ai_tcp);
713 			if (ecode != 0) {
714 				syslog(LOG_ERR, "getaddrinfo tcp: %s",
715 				   gai_strerror(ecode));
716 				nfsd_exit(1);
717 			}
718 			nconf_tcp = getnetconfigent("tcp");
719 			if (nconf_tcp == NULL) {
720 				syslog(LOG_ERR, "getnetconfigent tcp failed");
721 				nfsd_exit(1);
722 			}
723 			nb_tcp.buf = ai_tcp->ai_addr;
724 			nb_tcp.len = nb_tcp.maxlen = ai_tcp->ai_addrlen;
725 			if (nfs_minvers == NFS_VER2)
726 				if (!rpcb_set(NFS_PROGRAM, 2, nconf_tcp,
727 				    &nb_tcp)) {
728 					syslog(LOG_ERR, "rpcb_set tcp failed");
729 					nfsd_exit(1);
730 				}
731 			if (nfs_minvers <= NFS_VER3)
732 				if (!rpcb_set(NFS_PROGRAM, 3, nconf_tcp,
733 				    &nb_tcp)) {
734 					syslog(LOG_ERR, "rpcb_set tcp failed");
735 					nfsd_exit(1);
736 				}
737 			freeaddrinfo(ai_tcp);
738 		}
739 	}
740 
741 	/* Set up the socket for tcp6 and rpcb register it. */
742 	if (tcpflag && ip6flag) {
743 		rpcbreg = 0;
744 		for (i = 0; i < bindhostc; i++) {
745 			memset(&hints, 0, sizeof hints);
746 			hints.ai_flags = AI_PASSIVE;
747 			hints.ai_family = AF_INET6;
748 			hints.ai_socktype = SOCK_STREAM;
749 			hints.ai_protocol = IPPROTO_TCP;
750 			if (setbindhost(&ai_tcp6, bindhost[i], hints) == 0) {
751 				rpcbreg = 1;
752 				rpcbregcnt++;
753 				if ((tcp6sock = socket(ai_tcp6->ai_family,
754 				    ai_tcp6->ai_socktype,
755 				    ai_tcp6->ai_protocol)) < 0) {
756 					syslog(LOG_ERR,
757 					    "can't create tcp6 socket");
758 					nfsd_exit(1);
759 				}
760 				if (setsockopt(tcp6sock, SOL_SOCKET,
761 				    SO_REUSEADDR,
762 				    (char *)&on, sizeof(on)) < 0)
763 					syslog(LOG_ERR,
764 					    "setsockopt SO_REUSEADDR: %m");
765 				if (setsockopt(tcp6sock, IPPROTO_IPV6,
766 				    IPV6_V6ONLY, &on, sizeof on) < 0) {
767 					syslog(LOG_ERR,
768 					"can't set v6-only binding for tcp6 "
769 					    "socket: %m");
770 					nfsd_exit(1);
771 				}
772 				if (bind(tcp6sock, ai_tcp6->ai_addr,
773 				    ai_tcp6->ai_addrlen) < 0) {
774 					syslog(LOG_ERR,
775 					    "can't bind tcp6 addr %s: %m",
776 					    bindhost[i]);
777 					nfsd_exit(1);
778 				}
779 				if (listen(tcp6sock, -1) < 0) {
780 					syslog(LOG_ERR, "listen failed");
781 					nfsd_exit(1);
782 				}
783 				freeaddrinfo(ai_tcp6);
784 				FD_SET(tcp6sock, &sockbits);
785 				if (maxsock < tcp6sock)
786 					maxsock = tcp6sock;
787 				connect_type_cnt++;
788 			}
789 		}
790 		if (rpcbreg == 1) {
791 			memset(&hints, 0, sizeof hints);
792 			hints.ai_flags = AI_PASSIVE;
793 			hints.ai_family = AF_INET6;
794 			hints.ai_socktype = SOCK_STREAM;
795 			hints.ai_protocol = IPPROTO_TCP;
796 			ecode = getaddrinfo(NULL, "nfs", &hints, &ai_tcp6);
797 			if (ecode != 0) {
798 				syslog(LOG_ERR, "getaddrinfo tcp6: %s",
799 				   gai_strerror(ecode));
800 				nfsd_exit(1);
801 			}
802 			nconf_tcp6 = getnetconfigent("tcp6");
803 			if (nconf_tcp6 == NULL) {
804 				syslog(LOG_ERR, "getnetconfigent tcp6 failed");
805 				nfsd_exit(1);
806 			}
807 			nb_tcp6.buf = ai_tcp6->ai_addr;
808 			nb_tcp6.len = nb_tcp6.maxlen = ai_tcp6->ai_addrlen;
809 			if (nfs_minvers == NFS_VER2)
810 				if (!rpcb_set(NFS_PROGRAM, 2, nconf_tcp6,
811 				    &nb_tcp6)) {
812 					syslog(LOG_ERR, "rpcb_set tcp6 failed");
813 					nfsd_exit(1);
814 				}
815 			if (nfs_minvers <= NFS_VER3)
816 				if (!rpcb_set(NFS_PROGRAM, 3, nconf_tcp6,
817 				    &nb_tcp6)) {
818 					syslog(LOG_ERR, "rpcb_set tcp6 failed");
819 					nfsd_exit(1);
820 				}
821 			freeaddrinfo(ai_tcp6);
822 		}
823 	}
824 
825 	if (rpcbregcnt == 0) {
826 		syslog(LOG_ERR, "rpcb_set() failed, nothing to do: %m");
827 		nfsd_exit(1);
828 	}
829 
830 	if (tcpflag && connect_type_cnt == 0) {
831 		syslog(LOG_ERR, "tcp connects == 0, nothing to do: %m");
832 		nfsd_exit(1);
833 	}
834 
835 	setproctitle("master");
836 	/*
837 	 * We always want a master to have a clean way to shut nfsd down
838 	 * (with unregistration): if the master is killed, it unregisters and
839 	 * kills all children. If we run for UDP only (and so do not have to
840 	 * loop waiting for accept), we instead make the parent
841 	 * a "server" too. start_server will not return.
842 	 */
843 	if (!tcpflag)
844 		start_server(1, &nfsdargs, vhostname);
845 
846 	/*
847 	 * Loop forever accepting connections and passing the sockets
848 	 * into the kernel for the mounts.
849 	 */
850 	for (;;) {
851 		ready = sockbits;
852 		if (connect_type_cnt > 1) {
853 			if (select(maxsock + 1,
854 			    &ready, NULL, NULL, NULL) < 1) {
855 				error = errno;
856 				if (error == EINTR)
857 					continue;
858 				syslog(LOG_ERR, "select failed: %m");
859 				nfsd_exit(1);
860 			}
861 		}
862 		for (tcpsock = 0; tcpsock <= maxsock; tcpsock++) {
863 			if (FD_ISSET(tcpsock, &ready)) {
864 				len = sizeof(peer);
865 				if ((msgsock = accept(tcpsock,
866 				    (struct sockaddr *)&peer, &len)) < 0) {
867 					error = errno;
868 					syslog(LOG_ERR, "accept failed: %m");
869 					if (error == ECONNABORTED ||
870 					    error == EINTR)
871 						continue;
872 					nfsd_exit(1);
873 				}
874 				if (setsockopt(msgsock, SOL_SOCKET,
875 				    SO_KEEPALIVE, (char *)&on, sizeof(on)) < 0)
876 					syslog(LOG_ERR,
877 					    "setsockopt SO_KEEPALIVE: %m");
878 				addsockargs.sock = msgsock;
879 				addsockargs.name = (caddr_t)&peer;
880 				addsockargs.namelen = len;
881 				nfssvc(nfssvc_addsock, &addsockargs);
882 				(void)close(msgsock);
883 			}
884 		}
885 	}
886 }
887 
888 static int
setbindhost(struct addrinfo ** ai,const char * bindhost,struct addrinfo hints)889 setbindhost(struct addrinfo **ai, const char *bindhost, struct addrinfo hints)
890 {
891 	int ecode;
892 	u_int32_t host_addr[4];  /* IPv4 or IPv6 */
893 	const char *hostptr;
894 
895 	if (bindhost == NULL || strcmp("*", bindhost) == 0)
896 		hostptr = NULL;
897 	else
898 		hostptr = bindhost;
899 
900 	if (hostptr != NULL) {
901 		switch (hints.ai_family) {
902 		case AF_INET:
903 			if (inet_pton(AF_INET, hostptr, host_addr) == 1) {
904 				hints.ai_flags = AI_NUMERICHOST;
905 			} else {
906 				if (inet_pton(AF_INET6, hostptr,
907 				    host_addr) == 1)
908 					return (1);
909 			}
910 			break;
911 		case AF_INET6:
912 			if (inet_pton(AF_INET6, hostptr, host_addr) == 1) {
913 				hints.ai_flags = AI_NUMERICHOST;
914 			} else {
915 				if (inet_pton(AF_INET, hostptr,
916 				    host_addr) == 1)
917 					return (1);
918 			}
919 			break;
920 		default:
921 			break;
922 		}
923 	}
924 
925 	ecode = getaddrinfo(hostptr, "nfs", &hints, ai);
926 	if (ecode != 0) {
927 		syslog(LOG_ERR, "getaddrinfo %s: %s", bindhost,
928 		    gai_strerror(ecode));
929 		return (1);
930 	}
931 	return (0);
932 }
933 
934 static void
set_nfsdcnt(int proposed)935 set_nfsdcnt(int proposed)
936 {
937 
938 	if (proposed < 1) {
939 		warnx("nfsd count too low %d; reset to %d", proposed,
940 		    DEFNFSDCNT);
941 		nfsdcnt = DEFNFSDCNT;
942 	} else if (proposed > MAXNFSDCNT) {
943 		warnx("nfsd count too high %d; truncated to %d", proposed,
944 		    MAXNFSDCNT);
945 		nfsdcnt = MAXNFSDCNT;
946 	} else
947 		nfsdcnt = proposed;
948 	nfsdcnt_set = 1;
949 }
950 
951 static void
usage(void)952 usage(void)
953 {
954 	(void)fprintf(stderr, "%s", getopt_usage);
955 	exit(1);
956 }
957 
958 static void
nonfs(__unused int signo)959 nonfs(__unused int signo)
960 {
961 	syslog(LOG_ERR, "missing system call: NFS not available");
962 }
963 
964 static void
reapchild(__unused int signo)965 reapchild(__unused int signo)
966 {
967 	pid_t pid;
968 	int i;
969 
970 	while ((pid = wait3(NULL, WNOHANG, NULL)) > 0) {
971 		for (i = 0; i < nfsdcnt; i++)
972 			if (pid == children[i])
973 				children[i] = -1;
974 	}
975 }
976 
977 static void
unregistration(void)978 unregistration(void)
979 {
980 	if ((nfs_minvers == NFS_VER2 && !rpcb_unset(NFS_PROGRAM, 2, NULL)) ||
981 	    (nfs_minvers <= NFS_VER3 && !rpcb_unset(NFS_PROGRAM, 3, NULL)))
982 		syslog(LOG_ERR, "rpcb_unset failed");
983 }
984 
985 static void
killchildren(void)986 killchildren(void)
987 {
988 	int i;
989 
990 	for (i = 0; i < nfsdcnt; i++) {
991 		if (children[i] > 0)
992 			kill(children[i], SIGKILL);
993 	}
994 }
995 
996 /*
997  * Cleanup master after SIGUSR1.
998  */
999 static void
cleanup(__unused int signo)1000 cleanup(__unused int signo)
1001 {
1002 	nfsd_exit(0);
1003 }
1004 
1005 /*
1006  * Cleanup child after SIGUSR1.
1007  */
1008 static void
child_cleanup(__unused int signo)1009 child_cleanup(__unused int signo)
1010 {
1011 	exit(0);
1012 }
1013 
1014 static void
nfsd_exit(int status)1015 nfsd_exit(int status)
1016 {
1017 	killchildren();
1018 	unregistration();
1019 	exit(status);
1020 }
1021 
1022 static int
get_tuned_nfsdcount(void)1023 get_tuned_nfsdcount(void)
1024 {
1025 	int ncpu, error, tuned_nfsdcnt;
1026 	size_t ncpu_size;
1027 
1028 	ncpu_size = sizeof(ncpu);
1029 	error = sysctlbyname("hw.ncpu", &ncpu, &ncpu_size, NULL, 0);
1030 	if (error) {
1031 		warnx("sysctlbyname(hw.ncpu) failed defaulting to %d nfs servers",
1032 		    DEFNFSDCNT);
1033 		tuned_nfsdcnt = DEFNFSDCNT;
1034 	} else {
1035 		tuned_nfsdcnt = ncpu * 8;
1036 	}
1037 	return tuned_nfsdcnt;
1038 }
1039 
1040 static void
start_server(int master,struct nfsd_nfsd_args * nfsdargp,const char * vhost)1041 start_server(int master, struct nfsd_nfsd_args *nfsdargp, const char *vhost)
1042 {
1043 	char principal[MAXHOSTNAMELEN + 5];
1044 	int status, error;
1045 	char hostname[MAXHOSTNAMELEN + 1], *cp;
1046 	struct addrinfo *aip, hints;
1047 
1048 	status = 0;
1049 	if (vhost == NULL)
1050 		gethostname(hostname, sizeof (hostname));
1051 	else
1052 		strlcpy(hostname, vhost, sizeof (hostname));
1053 	snprintf(principal, sizeof (principal), "nfs@%s", hostname);
1054 	if ((cp = strchr(hostname, '.')) == NULL ||
1055 	    *(cp + 1) == '\0') {
1056 		/* If not fully qualified, try getaddrinfo() */
1057 		memset((void *)&hints, 0, sizeof (hints));
1058 		hints.ai_flags = AI_CANONNAME;
1059 		error = getaddrinfo(hostname, NULL, &hints, &aip);
1060 		if (error == 0) {
1061 			if (aip->ai_canonname != NULL &&
1062 			    (cp = strchr(aip->ai_canonname, '.')) !=
1063 			    NULL && *(cp + 1) != '\0')
1064 				snprintf(principal, sizeof (principal),
1065 				    "nfs@%s", aip->ai_canonname);
1066 			freeaddrinfo(aip);
1067 		}
1068 	}
1069 	nfsdargp->principal = principal;
1070 
1071 	if (nfsdcnt_set)
1072 		nfsdargp->minthreads = nfsdargp->maxthreads = nfsdcnt;
1073 	else {
1074 		nfsdargp->minthreads = minthreads_set ? minthreads : get_tuned_nfsdcount();
1075 		nfsdargp->maxthreads = maxthreads_set ? maxthreads : nfsdargp->minthreads;
1076 		if (nfsdargp->maxthreads < nfsdargp->minthreads)
1077 			nfsdargp->maxthreads = nfsdargp->minthreads;
1078 	}
1079 	error = nfssvc(nfssvc_nfsd, nfsdargp);
1080 	if (error < 0 && errno == EAUTH) {
1081 		/*
1082 		 * This indicates that it could not register the
1083 		 * rpcsec_gss credentials, usually because the
1084 		 * gssd daemon isn't running.
1085 		 * (only the experimental server with nfsv4)
1086 		 */
1087 		syslog(LOG_ERR, "No gssd, using AUTH_SYS only");
1088 		principal[0] = '\0';
1089 		error = nfssvc(nfssvc_nfsd, nfsdargp);
1090 	}
1091 	if (error < 0) {
1092 		if (errno == ENXIO) {
1093 			syslog(LOG_ERR, "Bad -p option, cannot run");
1094 			if (masterpid != 0 && master == 0)
1095 				kill(masterpid, SIGUSR1);
1096 		} else
1097 			syslog(LOG_ERR, "nfssvc: %m");
1098 		status = 1;
1099 	}
1100 	if (master)
1101 		nfsd_exit(status);
1102 	else
1103 		exit(status);
1104 }
1105 
1106 /*
1107  * Open the stable restart file and return the file descriptor for it.
1108  */
1109 static void
open_stable(int * stable_fdp,int * backup_fdp)1110 open_stable(int *stable_fdp, int *backup_fdp)
1111 {
1112 	int stable_fd, backup_fd = -1, ret;
1113 	struct stat st, backup_st;
1114 
1115 	/* Open and stat the stable restart file. */
1116 	stable_fd = open(NFSD_STABLERESTART, O_RDWR, 0);
1117 	if (stable_fd < 0)
1118 		stable_fd = open(NFSD_STABLERESTART, O_RDWR | O_CREAT, 0600);
1119 	if (stable_fd >= 0) {
1120 		ret = fstat(stable_fd, &st);
1121 		if (ret < 0) {
1122 			close(stable_fd);
1123 			stable_fd = -1;
1124 		}
1125 	}
1126 
1127 	/* Open and stat the backup stable restart file. */
1128 	if (stable_fd >= 0) {
1129 		backup_fd = open(NFSD_STABLEBACKUP, O_RDWR, 0);
1130 		if (backup_fd < 0)
1131 			backup_fd = open(NFSD_STABLEBACKUP, O_RDWR | O_CREAT,
1132 			    0600);
1133 		if (backup_fd >= 0) {
1134 			ret = fstat(backup_fd, &backup_st);
1135 			if (ret < 0) {
1136 				close(backup_fd);
1137 				backup_fd = -1;
1138 			}
1139 		}
1140 		if (backup_fd < 0) {
1141 			close(stable_fd);
1142 			stable_fd = -1;
1143 		}
1144 	}
1145 
1146 	*stable_fdp = stable_fd;
1147 	*backup_fdp = backup_fd;
1148 	if (stable_fd < 0)
1149 		return;
1150 
1151 	/* Sync up the 2 files, as required. */
1152 	if (st.st_size > 0)
1153 		copy_stable(stable_fd, backup_fd);
1154 	else if (backup_st.st_size > 0)
1155 		copy_stable(backup_fd, stable_fd);
1156 }
1157 
1158 /*
1159  * Copy the stable restart file to the backup or vice versa.
1160  */
1161 static void
copy_stable(int from_fd,int to_fd)1162 copy_stable(int from_fd, int to_fd)
1163 {
1164 	int cnt, ret;
1165 	static char buf[1024];
1166 
1167 	ret = lseek(from_fd, (off_t)0, SEEK_SET);
1168 	if (ret >= 0)
1169 		ret = lseek(to_fd, (off_t)0, SEEK_SET);
1170 	if (ret >= 0)
1171 		ret = ftruncate(to_fd, (off_t)0);
1172 	if (ret >= 0)
1173 		do {
1174 			cnt = read(from_fd, buf, 1024);
1175 			if (cnt > 0)
1176 				ret = write(to_fd, buf, cnt);
1177 			else if (cnt < 0)
1178 				ret = cnt;
1179 		} while (cnt > 0 && ret >= 0);
1180 	if (ret >= 0)
1181 		ret = fsync(to_fd);
1182 	if (ret < 0)
1183 		syslog(LOG_ERR, "stable restart copy failure: %m");
1184 }
1185 
1186 /*
1187  * Back up the stable restart file when indicated by the kernel.
1188  */
1189 static void
backup_stable(__unused int signo)1190 backup_stable(__unused int signo)
1191 {
1192 
1193 	if (stablefd >= 0)
1194 		copy_stable(stablefd, backupfd);
1195 }
1196 
1197 /*
1198  * Parse the pNFS string and extract the DS servers and ports numbers.
1199  */
1200 static void
parse_dsserver(const char * optionarg,struct nfsd_nfsd_args * nfsdargp)1201 parse_dsserver(const char *optionarg, struct nfsd_nfsd_args *nfsdargp)
1202 {
1203 	char *cp, *cp2, *dsaddr, *dshost, *dspath, *dsvol, nfsprt[9];
1204 	char *mdspath, *mdsp, ip6[INET6_ADDRSTRLEN];
1205 	const char *ad;
1206 	int ecode;
1207 	u_int adsiz, dsaddrcnt, dshostcnt, dspathcnt, hostsiz, pathsiz;
1208 	u_int mdspathcnt;
1209 	size_t dsaddrsiz, dshostsiz, dspathsiz, nfsprtsiz, mdspathsiz;
1210 	struct addrinfo hints, *ai_tcp, *res;
1211 	struct sockaddr_in sin;
1212 	struct sockaddr_in6 sin6;
1213 
1214 	cp = strdup(optionarg);
1215 	if (cp == NULL)
1216 		errx(1, "Out of memory");
1217 
1218 	/* Now, do the host names. */
1219 	dspathsiz = 1024;
1220 	dspathcnt = 0;
1221 	dspath = malloc(dspathsiz);
1222 	if (dspath == NULL)
1223 		errx(1, "Out of memory");
1224 	dshostsiz = 1024;
1225 	dshostcnt = 0;
1226 	dshost = malloc(dshostsiz);
1227 	if (dshost == NULL)
1228 		errx(1, "Out of memory");
1229 	dsaddrsiz = 1024;
1230 	dsaddrcnt = 0;
1231 	dsaddr = malloc(dsaddrsiz);
1232 	if (dsaddr == NULL)
1233 		errx(1, "Out of memory");
1234 	mdspathsiz = 1024;
1235 	mdspathcnt = 0;
1236 	mdspath = malloc(mdspathsiz);
1237 	if (mdspath == NULL)
1238 		errx(1, "Out of memory");
1239 
1240 	/* Put the NFS port# in "." form. */
1241 	snprintf(nfsprt, 9, ".%d.%d", 2049 >> 8, 2049 & 0xff);
1242 	nfsprtsiz = strlen(nfsprt);
1243 
1244 	ai_tcp = NULL;
1245 	/* Loop around for each DS server name. */
1246 	do {
1247 		cp2 = strchr(cp, ',');
1248 		if (cp2 != NULL) {
1249 			/* Not the last DS in the list. */
1250 			*cp2++ = '\0';
1251 			if (*cp2 == '\0')
1252 				usage();
1253 		}
1254 
1255 		dsvol = strchr(cp, ':');
1256 		if (dsvol == NULL || *(dsvol + 1) == '\0')
1257 			usage();
1258 		*dsvol++ = '\0';
1259 
1260 		/* Optional path for MDS file system to be stored on DS. */
1261 		mdsp = strchr(dsvol, '#');
1262 		if (mdsp != NULL) {
1263 			if (*(mdsp + 1) == '\0' || mdsp <= dsvol)
1264 				usage();
1265 			*mdsp++ = '\0';
1266 		}
1267 
1268 		/* Append this pathname to dspath. */
1269 		pathsiz = strlen(dsvol);
1270 		if (dspathcnt + pathsiz + 1 > dspathsiz) {
1271 			dspathsiz *= 2;
1272 			dspath = realloc(dspath, dspathsiz);
1273 			if (dspath == NULL)
1274 				errx(1, "Out of memory");
1275 		}
1276 		strcpy(&dspath[dspathcnt], dsvol);
1277 		dspathcnt += pathsiz + 1;
1278 
1279 		/* Append this pathname to mdspath. */
1280 		if (mdsp != NULL)
1281 			pathsiz = strlen(mdsp);
1282 		else
1283 			pathsiz = 0;
1284 		if (mdspathcnt + pathsiz + 1 > mdspathsiz) {
1285 			mdspathsiz *= 2;
1286 			mdspath = realloc(mdspath, mdspathsiz);
1287 			if (mdspath == NULL)
1288 				errx(1, "Out of memory");
1289 		}
1290 		if (mdsp != NULL)
1291 			strcpy(&mdspath[mdspathcnt], mdsp);
1292 		else
1293 			mdspath[mdspathcnt] = '\0';
1294 		mdspathcnt += pathsiz + 1;
1295 
1296 		if (ai_tcp != NULL)
1297 			freeaddrinfo(ai_tcp);
1298 
1299 		/* Get the fully qualified domain name and IP address. */
1300 		memset(&hints, 0, sizeof(hints));
1301 		hints.ai_flags = AI_CANONNAME | AI_ADDRCONFIG;
1302 		hints.ai_family = PF_UNSPEC;
1303 		hints.ai_socktype = SOCK_STREAM;
1304 		hints.ai_protocol = IPPROTO_TCP;
1305 		ecode = getaddrinfo(cp, NULL, &hints, &ai_tcp);
1306 		if (ecode != 0)
1307 			err(1, "getaddrinfo pnfs: %s %s", cp,
1308 			    gai_strerror(ecode));
1309 		ad = NULL;
1310 		for (res = ai_tcp; res != NULL; res = res->ai_next) {
1311 			if (res->ai_addr->sa_family == AF_INET) {
1312 				if (res->ai_addrlen < sizeof(sin))
1313 					err(1, "getaddrinfo() returned "
1314 					    "undersized IPv4 address");
1315 				/*
1316 				 * Mips cares about sockaddr_in alignment,
1317 				 * so copy the address.
1318 				 */
1319 				memcpy(&sin, res->ai_addr, sizeof(sin));
1320 				ad = inet_ntoa(sin.sin_addr);
1321 				break;
1322 			} else if (res->ai_family == AF_INET6) {
1323 				if (res->ai_addrlen < sizeof(sin6))
1324 					err(1, "getaddrinfo() returned "
1325 					    "undersized IPv6 address");
1326 				/*
1327 				 * Mips cares about sockaddr_in6 alignment,
1328 				 * so copy the address.
1329 				 */
1330 				memcpy(&sin6, res->ai_addr, sizeof(sin6));
1331 				ad = inet_ntop(AF_INET6, &sin6.sin6_addr, ip6,
1332 				    sizeof(ip6));
1333 
1334 				/*
1335 				 * XXX
1336 				 * Since a link local address will only
1337 				 * work if the client and DS are in the
1338 				 * same scope zone, only use it if it is
1339 				 * the only address.
1340 				 */
1341 				if (ad != NULL &&
1342 				    !IN6_IS_ADDR_LINKLOCAL(&sin6.sin6_addr))
1343 					break;
1344 			}
1345 		}
1346 		if (ad == NULL)
1347 			err(1, "No IP address for %s", cp);
1348 
1349 		/* Append this address to dsaddr. */
1350 		adsiz = strlen(ad);
1351 		if (dsaddrcnt + adsiz + nfsprtsiz + 1 > dsaddrsiz) {
1352 			dsaddrsiz *= 2;
1353 			dsaddr = realloc(dsaddr, dsaddrsiz);
1354 			if (dsaddr == NULL)
1355 				errx(1, "Out of memory");
1356 		}
1357 		strcpy(&dsaddr[dsaddrcnt], ad);
1358 		strcat(&dsaddr[dsaddrcnt], nfsprt);
1359 		dsaddrcnt += adsiz + nfsprtsiz + 1;
1360 
1361 		/* Append this hostname to dshost. */
1362 		hostsiz = strlen(ai_tcp->ai_canonname);
1363 		if (dshostcnt + hostsiz + 1 > dshostsiz) {
1364 			dshostsiz *= 2;
1365 			dshost = realloc(dshost, dshostsiz);
1366 			if (dshost == NULL)
1367 				errx(1, "Out of memory");
1368 		}
1369 		strcpy(&dshost[dshostcnt], ai_tcp->ai_canonname);
1370 		dshostcnt += hostsiz + 1;
1371 
1372 		cp = cp2;
1373 	} while (cp != NULL);
1374 
1375 	nfsdargp->addr = dsaddr;
1376 	nfsdargp->addrlen = dsaddrcnt;
1377 	nfsdargp->dnshost = dshost;
1378 	nfsdargp->dnshostlen = dshostcnt;
1379 	nfsdargp->dspath = dspath;
1380 	nfsdargp->dspathlen = dspathcnt;
1381 	nfsdargp->mdspath = mdspath;
1382 	nfsdargp->mdspathlen = mdspathcnt;
1383 	freeaddrinfo(ai_tcp);
1384 }
1385 
1386