xref: /xnu-8020.121.3/bsd/nfs/nfs_subs.c (revision fdd8201d7b966f0c3ea610489d29bd841d358941)
1 /*
2  * Copyright (c) 2000-2020 Apple Inc. All rights reserved.
3  *
4  * @APPLE_OSREFERENCE_LICENSE_HEADER_START@
5  *
6  * This file contains Original Code and/or Modifications of Original Code
7  * as defined in and that are subject to the Apple Public Source License
8  * Version 2.0 (the 'License'). You may not use this file except in
9  * compliance with the License. The rights granted to you under the License
10  * may not be used to create, or enable the creation or redistribution of,
11  * unlawful or unlicensed copies of an Apple operating system, or to
12  * circumvent, violate, or enable the circumvention or violation of, any
13  * terms of an Apple operating system software license agreement.
14  *
15  * Please obtain a copy of the License at
16  * http://www.opensource.apple.com/apsl/ and read it before using this file.
17  *
18  * The Original Code and all software distributed under the License are
19  * distributed on an 'AS IS' basis, WITHOUT WARRANTY OF ANY KIND, EITHER
20  * EXPRESS OR IMPLIED, AND APPLE HEREBY DISCLAIMS ALL SUCH WARRANTIES,
21  * INCLUDING WITHOUT LIMITATION, ANY WARRANTIES OF MERCHANTABILITY,
22  * FITNESS FOR A PARTICULAR PURPOSE, QUIET ENJOYMENT OR NON-INFRINGEMENT.
23  * Please see the License for the specific language governing rights and
24  * limitations under the License.
25  *
26  * @APPLE_OSREFERENCE_LICENSE_HEADER_END@
27  */
28 /* Copyright (c) 1995 NeXT Computer, Inc. All Rights Reserved */
29 /*
30  * Copyright (c) 1989, 1993
31  *	The Regents of the University of California.  All rights reserved.
32  *
33  * This code is derived from software contributed to Berkeley by
34  * Rick Macklem at The University of Guelph.
35  *
36  * Redistribution and use in source and binary forms, with or without
37  * modification, are permitted provided that the following conditions
38  * are met:
39  * 1. Redistributions of source code must retain the above copyright
40  *    notice, this list of conditions and the following disclaimer.
41  * 2. Redistributions in binary form must reproduce the above copyright
42  *    notice, this list of conditions and the following disclaimer in the
43  *    documentation and/or other materials provided with the distribution.
44  * 3. All advertising materials mentioning features or use of this software
45  *    must display the following acknowledgement:
46  *	This product includes software developed by the University of
47  *	California, Berkeley and its contributors.
48  * 4. Neither the name of the University nor the names of its contributors
49  *    may be used to endorse or promote products derived from this software
50  *    without specific prior written permission.
51  *
52  * THIS SOFTWARE IS PROVIDED BY THE REGENTS AND CONTRIBUTORS ``AS IS'' AND
53  * ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
54  * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE
55  * ARE DISCLAIMED.  IN NO EVENT SHALL THE REGENTS OR CONTRIBUTORS BE LIABLE
56  * FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL
57  * DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS
58  * OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION)
59  * HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT
60  * LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY
61  * OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF
62  * SUCH DAMAGE.
63  *
64  *	@(#)nfs_subs.c	8.8 (Berkeley) 5/22/95
65  * FreeBSD-Id: nfs_subs.c,v 1.47 1997/11/07 08:53:24 phk Exp $
66  */
67 
68 #include <nfs/nfs_conf.h>
69 #if CONFIG_NFS
70 
71 /*
72  * These functions support the macros and help fiddle mbuf chains for
73  * the nfs op functions. They do things like create the rpc header and
74  * copy data between mbuf chains and uio lists.
75  */
76 #include <sys/param.h>
77 #include <sys/proc.h>
78 #include <sys/kauth.h>
79 #include <sys/systm.h>
80 #include <sys/kernel.h>
81 #include <sys/mount_internal.h>
82 #include <sys/vnode_internal.h>
83 #include <sys/kpi_mbuf.h>
84 #include <sys/socket.h>
85 #include <sys/un.h>
86 #include <sys/stat.h>
87 #include <sys/malloc.h>
88 #include <sys/syscall.h>
89 #include <sys/ubc_internal.h>
90 #include <sys/fcntl.h>
91 #include <sys/uio.h>
92 #include <sys/domain.h>
93 #include <libkern/OSAtomic.h>
94 #include <kern/thread_call.h>
95 #include <kern/task.h>
96 
97 #include <sys/vm.h>
98 #include <sys/vmparam.h>
99 
100 #include <sys/time.h>
101 #include <kern/clock.h>
102 
103 #include <nfs/rpcv2.h>
104 #include <nfs/nfsproto.h>
105 #include <nfs/nfs.h>
106 #include <nfs/nfsnode.h>
107 #if CONFIG_NFS_CLIENT
108 #define _NFS_XDR_SUBS_FUNCS_ /* define this to get xdrbuf function definitions */
109 #endif
110 #include <nfs/xdr_subs.h>
111 #include <nfs/nfsm_subs.h>
112 #include <nfs/nfs_gss.h>
113 #include <nfs/nfsmount.h>
114 #include <nfs/nfs_lock.h>
115 
116 #include <miscfs/specfs/specdev.h>
117 
118 #include <netinet/in.h>
119 #include <net/kpi_interface.h>
120 
121 #include <sys/utfconv.h>
122 
123 /*
124  * NFS globals
125  */
126 struct nfsclntstats __attribute__((aligned(8))) nfsclntstats;
127 struct nfsrvstats __attribute__((aligned(8))) nfsrvstats;
128 size_t nfs_mbuf_mhlen = 0, nfs_mbuf_minclsize = 0;
129 
130 /* NFS debugging support */
131 uint32_t nfsclnt_debug_ctl;
132 uint32_t nfsrv_debug_ctl;
133 
134 #include <libkern/libkern.h>
135 #include <stdarg.h>
136 
137 void
nfs_printf(unsigned int debug_control,unsigned int facility,unsigned int level,const char * fmt,...)138 nfs_printf(unsigned int debug_control, unsigned int facility, unsigned int level, const char *fmt, ...)
139 {
140 	va_list ap;
141 
142 	if (__NFS_IS_DBG(debug_control, facility, level)) {
143 		va_start(ap, fmt);
144 		vprintf(fmt, ap);
145 		va_end(ap);
146 	}
147 }
148 
149 
150 #define DISPLAYLEN 16
151 
152 static bool
isprint(int ch)153 isprint(int ch)
154 {
155 	return ch >= 0x20 && ch <= 0x7e;
156 }
157 
158 static void
hexdump(void * data,size_t len)159 hexdump(void *data, size_t len)
160 {
161 	size_t i, j;
162 	unsigned char *d = data;
163 	char *p, disbuf[3 * DISPLAYLEN + 1];
164 
165 	for (i = 0; i < len; i += DISPLAYLEN) {
166 		for (p = disbuf, j = 0; (j + i) < len && j < DISPLAYLEN; j++, p += 3) {
167 			snprintf(p, 4, "%2.2x ", d[i + j]);
168 		}
169 		for (; j < DISPLAYLEN; j++, p += 3) {
170 			snprintf(p, 4, "   ");
171 		}
172 		printf("%s    ", disbuf);
173 		for (p = disbuf, j = 0; (j + i) < len && j < DISPLAYLEN; j++, p++) {
174 			snprintf(p, 2, "%c", isprint(d[i + j]) ? d[i + j] : '.');
175 		}
176 		printf("%s\n", disbuf);
177 	}
178 }
179 
180 void
nfs_dump_mbuf(const char * func,int lineno,const char * msg,mbuf_t mb)181 nfs_dump_mbuf(const char *func, int lineno, const char *msg, mbuf_t mb)
182 {
183 	mbuf_t m;
184 
185 	printf("%s:%d %s\n", func, lineno, msg);
186 	for (m = mb; m; m = mbuf_next(m)) {
187 		hexdump(mbuf_data(m), mbuf_len(m));
188 	}
189 }
190 
191 int
nfs_maperr(const char * func,int error)192 nfs_maperr(const char *func, int error)
193 {
194 	if (error < NFSERR_BADHANDLE || error > NFSERR_DIRBUFDROPPED) {
195 		return error;
196 	}
197 	switch (error) {
198 	case NFSERR_BADOWNER:
199 		printf("%s: No name and/or group mapping err=%d\n", func, error);
200 		return EPERM;
201 	case NFSERR_BADNAME:
202 	case NFSERR_BADCHAR:
203 		printf("%s: nfs char/name not handled by server err=%d\n", func, error);
204 		return ENOENT;
205 	case NFSERR_STALE_CLIENTID:
206 	case NFSERR_STALE_STATEID:
207 	case NFSERR_EXPIRED:
208 	case NFSERR_BAD_STATEID:
209 		printf("%s: nfs recover err returned %d\n", func, error);
210 		return EIO;
211 	case NFSERR_BADHANDLE:
212 	case NFSERR_SERVERFAULT:
213 	case NFSERR_BADTYPE:
214 	case NFSERR_FHEXPIRED:
215 	case NFSERR_RESOURCE:
216 	case NFSERR_MOVED:
217 	case NFSERR_NOFILEHANDLE:
218 	case NFSERR_MINOR_VERS_MISMATCH:
219 	case NFSERR_OLD_STATEID:
220 	case NFSERR_BAD_SEQID:
221 	case NFSERR_LEASE_MOVED:
222 	case NFSERR_RECLAIM_BAD:
223 	case NFSERR_BADXDR:
224 	case NFSERR_OP_ILLEGAL:
225 		printf("%s: nfs client/server protocol prob err=%d\n", func, error);
226 		return EIO;
227 	default:
228 		printf("%s: nfs err=%d\n", func, error);
229 		return EIO;
230 	}
231 }
232 
233 /*
234  * functions to convert between NFS and VFS types
235  */
236 nfstype
vtonfs_type(enum vtype vtype,int nfsvers)237 vtonfs_type(enum vtype vtype, int nfsvers)
238 {
239 	switch (vtype) {
240 	case VNON:
241 		return NFNON;
242 	case VREG:
243 		return NFREG;
244 	case VDIR:
245 		return NFDIR;
246 	case VBLK:
247 		return NFBLK;
248 	case VCHR:
249 		return NFCHR;
250 	case VLNK:
251 		return NFLNK;
252 	case VSOCK:
253 		if (nfsvers > NFS_VER2) {
254 			return NFSOCK;
255 		}
256 		return NFNON;
257 	case VFIFO:
258 		if (nfsvers > NFS_VER2) {
259 			return NFFIFO;
260 		}
261 		return NFNON;
262 	case VBAD:
263 	case VSTR:
264 	case VCPLX:
265 	default:
266 		return NFNON;
267 	}
268 }
269 
270 enum vtype
nfstov_type(nfstype nvtype,int nfsvers)271 nfstov_type(nfstype nvtype, int nfsvers)
272 {
273 	switch (nvtype) {
274 	case NFNON:
275 		return VNON;
276 	case NFREG:
277 		return VREG;
278 	case NFDIR:
279 		return VDIR;
280 	case NFBLK:
281 		return VBLK;
282 	case NFCHR:
283 		return VCHR;
284 	case NFLNK:
285 		return VLNK;
286 	case NFSOCK:
287 		if (nfsvers > NFS_VER2) {
288 			return VSOCK;
289 		}
290 		OS_FALLTHROUGH;
291 	case NFFIFO:
292 		if (nfsvers > NFS_VER2) {
293 			return VFIFO;
294 		}
295 		OS_FALLTHROUGH;
296 	case NFATTRDIR:
297 		if (nfsvers > NFS_VER3) {
298 			return VDIR;
299 		}
300 		OS_FALLTHROUGH;
301 	case NFNAMEDATTR:
302 		if (nfsvers > NFS_VER3) {
303 			return VREG;
304 		}
305 		OS_FALLTHROUGH;
306 	default:
307 		return VNON;
308 	}
309 }
310 
311 int
vtonfsv2_mode(enum vtype vtype,mode_t m)312 vtonfsv2_mode(enum vtype vtype, mode_t m)
313 {
314 	switch (vtype) {
315 	case VNON:
316 	case VREG:
317 	case VDIR:
318 	case VBLK:
319 	case VCHR:
320 	case VLNK:
321 	case VSOCK:
322 		return MAKEIMODE(vtype, m);
323 	case VFIFO:
324 		return MAKEIMODE(VCHR, m);
325 	case VBAD:
326 	case VSTR:
327 	case VCPLX:
328 	default:
329 		return MAKEIMODE(VNON, m);
330 	}
331 }
332 
333 #if CONFIG_NFS_SERVER
334 
335 /*
336  * Mapping of old NFS Version 2 RPC numbers to generic numbers.
337  */
338 int nfsv3_procid[NFS_NPROCS] = {
339 	NFSPROC_NULL,
340 	NFSPROC_GETATTR,
341 	NFSPROC_SETATTR,
342 	NFSPROC_NOOP,
343 	NFSPROC_LOOKUP,
344 	NFSPROC_READLINK,
345 	NFSPROC_READ,
346 	NFSPROC_NOOP,
347 	NFSPROC_WRITE,
348 	NFSPROC_CREATE,
349 	NFSPROC_REMOVE,
350 	NFSPROC_RENAME,
351 	NFSPROC_LINK,
352 	NFSPROC_SYMLINK,
353 	NFSPROC_MKDIR,
354 	NFSPROC_RMDIR,
355 	NFSPROC_READDIR,
356 	NFSPROC_FSSTAT,
357 	NFSPROC_NOOP,
358 	NFSPROC_NOOP,
359 	NFSPROC_NOOP,
360 	NFSPROC_NOOP,
361 	NFSPROC_NOOP
362 };
363 
364 #endif /* CONFIG_NFS_SERVER */
365 
366 /*
367  * and the reverse mapping from generic to Version 2 procedure numbers
368  */
369 int nfsv2_procid[NFS_NPROCS] = {
370 	NFSV2PROC_NULL,
371 	NFSV2PROC_GETATTR,
372 	NFSV2PROC_SETATTR,
373 	NFSV2PROC_LOOKUP,
374 	NFSV2PROC_NOOP,
375 	NFSV2PROC_READLINK,
376 	NFSV2PROC_READ,
377 	NFSV2PROC_WRITE,
378 	NFSV2PROC_CREATE,
379 	NFSV2PROC_MKDIR,
380 	NFSV2PROC_SYMLINK,
381 	NFSV2PROC_CREATE,
382 	NFSV2PROC_REMOVE,
383 	NFSV2PROC_RMDIR,
384 	NFSV2PROC_RENAME,
385 	NFSV2PROC_LINK,
386 	NFSV2PROC_READDIR,
387 	NFSV2PROC_NOOP,
388 	NFSV2PROC_STATFS,
389 	NFSV2PROC_NOOP,
390 	NFSV2PROC_NOOP,
391 	NFSV2PROC_NOOP,
392 	NFSV2PROC_NOOP
393 };
394 
395 
396 /*
397  * initialize NFS's cache of mbuf constants
398  */
399 void
nfs_mbuf_init(void)400 nfs_mbuf_init(void)
401 {
402 	struct mbuf_stat ms;
403 
404 	mbuf_stats(&ms);
405 	nfs_mbuf_mhlen = ms.mhlen;
406 	nfs_mbuf_minclsize = ms.minclsize;
407 }
408 
409 #if CONFIG_NFS_SERVER
410 
411 static void
nfs_netopt_free(struct nfs_netopt * no)412 nfs_netopt_free(struct nfs_netopt *no)
413 {
414 	if (no->no_addr) {
415 		kfree_data(no->no_addr, no->no_addr->sa_len);
416 	}
417 	if (no->no_mask) {
418 		kfree_data(no->no_mask, no->no_mask->sa_len);
419 	}
420 
421 	kfree_type(struct nfs_netopt, no);
422 }
423 
424 /*
425  * allocate a list of mbufs to hold the given amount of data
426  */
427 int
nfsm_mbuf_get_list(size_t size,mbuf_t * mp,int * mbcnt)428 nfsm_mbuf_get_list(size_t size, mbuf_t *mp, int *mbcnt)
429 {
430 	int error, cnt;
431 	mbuf_t mhead, mlast, m;
432 	size_t len, mlen;
433 
434 	error = cnt = 0;
435 	mhead = mlast = NULL;
436 	len = 0;
437 
438 	while (len < size) {
439 		nfsm_mbuf_getcluster(error, &m, (size - len));
440 		if (error) {
441 			break;
442 		}
443 		if (!mhead) {
444 			mhead = m;
445 		}
446 		if (mlast && ((error = mbuf_setnext(mlast, m)))) {
447 			mbuf_free(m);
448 			break;
449 		}
450 		mlen = mbuf_maxlen(m);
451 		if ((len + mlen) > size) {
452 			mlen = size - len;
453 		}
454 		mbuf_setlen(m, mlen);
455 		len += mlen;
456 		cnt++;
457 		mlast = m;
458 	}
459 
460 	if (!error) {
461 		*mp = mhead;
462 		*mbcnt = cnt;
463 	}
464 	return error;
465 }
466 
467 #endif /* CONFIG_NFS_SERVER */
468 
469 /*
470  * nfsm_chain_new_mbuf()
471  *
472  * Add a new mbuf to the given chain.
473  */
474 int
nfsm_chain_new_mbuf(struct nfsm_chain * nmc,size_t sizehint)475 nfsm_chain_new_mbuf(struct nfsm_chain *nmc, size_t sizehint)
476 {
477 	mbuf_t mb;
478 	int error = 0;
479 
480 	if (nmc->nmc_flags & NFSM_CHAIN_FLAG_ADD_CLUSTERS) {
481 		sizehint = nfs_mbuf_minclsize;
482 	}
483 
484 	/* allocate a new mbuf */
485 	nfsm_mbuf_getcluster(error, &mb, sizehint);
486 	if (error) {
487 		return error;
488 	}
489 	if (mb == NULL) {
490 		panic("got NULL mbuf?");
491 	}
492 
493 	/* do we have a current mbuf? */
494 	if (nmc->nmc_mcur) {
495 		/* first cap off current mbuf */
496 		mbuf_setlen(nmc->nmc_mcur, nmc->nmc_ptr - (caddr_t)mbuf_data(nmc->nmc_mcur));
497 		/* then append the new mbuf */
498 		error = mbuf_setnext(nmc->nmc_mcur, mb);
499 		if (error) {
500 			mbuf_free(mb);
501 			return error;
502 		}
503 	}
504 
505 	/* set up for using the new mbuf */
506 	nmc->nmc_mcur = mb;
507 	nmc->nmc_ptr = mbuf_data(mb);
508 	nmc->nmc_left = mbuf_trailingspace(mb);
509 
510 	return 0;
511 }
512 
513 /*
514  * nfsm_chain_add_opaque_f()
515  *
516  * Add "len" bytes of opaque data pointed to by "buf" to the given chain.
517  */
518 int
nfsm_chain_add_opaque_f(struct nfsm_chain * nmc,const u_char * buf,size_t len)519 nfsm_chain_add_opaque_f(struct nfsm_chain *nmc, const u_char *buf, size_t len)
520 {
521 	size_t paddedlen, tlen;
522 	int error;
523 
524 	paddedlen = nfsm_rndup(len);
525 
526 	while (paddedlen) {
527 		if (!nmc->nmc_left) {
528 			error = nfsm_chain_new_mbuf(nmc, paddedlen);
529 			if (error) {
530 				return error;
531 			}
532 		}
533 		tlen = MIN(nmc->nmc_left, paddedlen);
534 		if (tlen) {
535 			if (len) {
536 				if (tlen > len) {
537 					tlen = len;
538 				}
539 				bcopy(buf, nmc->nmc_ptr, tlen);
540 			} else {
541 				bzero(nmc->nmc_ptr, tlen);
542 			}
543 			nmc->nmc_ptr += tlen;
544 			nmc->nmc_left -= tlen;
545 			paddedlen -= tlen;
546 			if (len) {
547 				buf += tlen;
548 				len -= tlen;
549 			}
550 		}
551 	}
552 	return 0;
553 }
554 
555 /*
556  * nfsm_chain_add_opaque_nopad_f()
557  *
558  * Add "len" bytes of opaque data pointed to by "buf" to the given chain.
559  * Do not XDR pad.
560  */
561 int
nfsm_chain_add_opaque_nopad_f(struct nfsm_chain * nmc,const u_char * buf,size_t len)562 nfsm_chain_add_opaque_nopad_f(struct nfsm_chain *nmc, const u_char *buf, size_t len)
563 {
564 	size_t tlen;
565 	int error;
566 
567 	while (len > 0) {
568 		if (nmc->nmc_left <= 0) {
569 			error = nfsm_chain_new_mbuf(nmc, len);
570 			if (error) {
571 				return error;
572 			}
573 		}
574 		tlen = MIN(nmc->nmc_left, len);
575 		bcopy(buf, nmc->nmc_ptr, tlen);
576 		nmc->nmc_ptr += tlen;
577 		nmc->nmc_left -= tlen;
578 		len -= tlen;
579 		buf += tlen;
580 	}
581 	return 0;
582 }
583 
584 /*
585  * nfsm_chain_add_uio()
586  *
587  * Add "len" bytes of data from "uio" to the given chain.
588  */
589 int
nfsm_chain_add_uio(struct nfsm_chain * nmc,uio_t uio,size_t len)590 nfsm_chain_add_uio(struct nfsm_chain *nmc, uio_t uio, size_t len)
591 {
592 	size_t paddedlen, tlen;
593 	int error;
594 
595 	paddedlen = nfsm_rndup(len);
596 
597 	while (paddedlen) {
598 		if (!nmc->nmc_left) {
599 			error = nfsm_chain_new_mbuf(nmc, paddedlen);
600 			if (error) {
601 				return error;
602 			}
603 		}
604 		tlen = MIN(nmc->nmc_left, paddedlen);
605 		if (tlen) {
606 			if (len) {
607 				tlen = MIN(INT32_MAX, MIN(tlen, len));
608 				uiomove(nmc->nmc_ptr, (int)tlen, uio);
609 			} else {
610 				bzero(nmc->nmc_ptr, tlen);
611 			}
612 			nmc->nmc_ptr += tlen;
613 			nmc->nmc_left -= tlen;
614 			paddedlen -= tlen;
615 			if (len) {
616 				len -= tlen;
617 			}
618 		}
619 	}
620 	return 0;
621 }
622 
623 /*
624  * Find the length of the NFS mbuf chain
625  * up to the current encoding/decoding offset.
626  */
627 size_t
nfsm_chain_offset(struct nfsm_chain * nmc)628 nfsm_chain_offset(struct nfsm_chain *nmc)
629 {
630 	mbuf_t mb;
631 	size_t len = 0;
632 
633 	for (mb = nmc->nmc_mhead; mb; mb = mbuf_next(mb)) {
634 		if (mb == nmc->nmc_mcur) {
635 			return len + (nmc->nmc_ptr - (caddr_t) mbuf_data(mb));
636 		}
637 		len += mbuf_len(mb);
638 	}
639 
640 	return len;
641 }
642 
643 /*
644  * nfsm_chain_advance()
645  *
646  * Advance an nfsm_chain by "len" bytes.
647  */
648 int
nfsm_chain_advance(struct nfsm_chain * nmc,size_t len)649 nfsm_chain_advance(struct nfsm_chain *nmc, size_t len)
650 {
651 	mbuf_t mb;
652 
653 	while (len) {
654 		if (nmc->nmc_left >= len) {
655 			nmc->nmc_left -= len;
656 			nmc->nmc_ptr += len;
657 			return 0;
658 		}
659 		len -= nmc->nmc_left;
660 		nmc->nmc_mcur = mb = mbuf_next(nmc->nmc_mcur);
661 		if (!mb) {
662 			return EBADRPC;
663 		}
664 		nmc->nmc_ptr = mbuf_data(mb);
665 		nmc->nmc_left = mbuf_len(mb);
666 	}
667 
668 	return 0;
669 }
670 
671 /*
672  * nfsm_chain_reverse()
673  *
674  * Reverse decode offset in an nfsm_chain by "len" bytes.
675  */
676 int
nfsm_chain_reverse(struct nfsm_chain * nmc,size_t len)677 nfsm_chain_reverse(struct nfsm_chain *nmc, size_t len)
678 {
679 	size_t mlen, new_offset;
680 	int error = 0;
681 
682 	mlen = nmc->nmc_ptr - (caddr_t) mbuf_data(nmc->nmc_mcur);
683 	if (len <= mlen) {
684 		nmc->nmc_ptr -= len;
685 		nmc->nmc_left += len;
686 		return 0;
687 	}
688 
689 	new_offset = nfsm_chain_offset(nmc) - len;
690 	nfsm_chain_dissect_init(error, nmc, nmc->nmc_mhead);
691 	if (error) {
692 		return error;
693 	}
694 
695 	return nfsm_chain_advance(nmc, new_offset);
696 }
697 
698 /*
699  * nfsm_chain_get_opaque_pointer_f()
700  *
701  * Return a pointer to the next "len" bytes of contiguous data in
702  * the mbuf chain.  If the next "len" bytes are not contiguous, we
703  * try to manipulate the mbuf chain so that it is.
704  *
705  * The nfsm_chain is advanced by nfsm_rndup("len") bytes.
706  */
707 int
nfsm_chain_get_opaque_pointer_f(struct nfsm_chain * nmc,uint32_t len,u_char ** pptr)708 nfsm_chain_get_opaque_pointer_f(struct nfsm_chain *nmc, uint32_t len, u_char **pptr)
709 {
710 	mbuf_t mbcur, mb;
711 	uint32_t padlen;
712 	size_t mblen, cplen, need, left;
713 	u_char *ptr;
714 	int error = 0;
715 
716 	/* move to next mbuf with data */
717 	while (nmc->nmc_mcur && (nmc->nmc_left == 0)) {
718 		mb = mbuf_next(nmc->nmc_mcur);
719 		nmc->nmc_mcur = mb;
720 		if (!mb) {
721 			break;
722 		}
723 		nmc->nmc_ptr = mbuf_data(mb);
724 		nmc->nmc_left = mbuf_len(mb);
725 	}
726 	/* check if we've run out of data */
727 	if (!nmc->nmc_mcur) {
728 		return EBADRPC;
729 	}
730 
731 	/* do we already have a contiguous buffer? */
732 	if (nmc->nmc_left >= len) {
733 		/* the returned pointer will be the current pointer */
734 		*pptr = (u_char*)nmc->nmc_ptr;
735 		error = nfsm_chain_advance(nmc, nfsm_rndup(len));
736 		return error;
737 	}
738 
739 	padlen = nfsm_rndup(len) - len;
740 
741 	/* we need (len - left) more bytes */
742 	mbcur = nmc->nmc_mcur;
743 	left = nmc->nmc_left;
744 	need = len - left;
745 
746 	if (need > mbuf_trailingspace(mbcur)) {
747 		/*
748 		 * The needed bytes won't fit in the current mbuf so we'll
749 		 * allocate a new mbuf to hold the contiguous range of data.
750 		 */
751 		nfsm_mbuf_getcluster(error, &mb, len);
752 		if (error) {
753 			return error;
754 		}
755 		/* double check that this mbuf can hold all the data */
756 		if (mbuf_maxlen(mb) < len) {
757 			mbuf_free(mb);
758 			return EOVERFLOW;
759 		}
760 
761 		/* the returned pointer will be the new mbuf's data pointer */
762 		*pptr = ptr = mbuf_data(mb);
763 
764 		/* copy "left" bytes to the new mbuf */
765 		bcopy(nmc->nmc_ptr, ptr, left);
766 		ptr += left;
767 		mbuf_setlen(mb, left);
768 
769 		/* insert the new mbuf between the current and next mbufs */
770 		error = mbuf_setnext(mb, mbuf_next(mbcur));
771 		if (!error) {
772 			error = mbuf_setnext(mbcur, mb);
773 		}
774 		if (error) {
775 			mbuf_free(mb);
776 			return error;
777 		}
778 
779 		/* reduce current mbuf's length by "left" */
780 		mbuf_setlen(mbcur, mbuf_len(mbcur) - left);
781 
782 		/*
783 		 * update nmc's state to point at the end of the mbuf
784 		 * where the needed data will be copied to.
785 		 */
786 		nmc->nmc_mcur = mbcur = mb;
787 		nmc->nmc_left = 0;
788 		nmc->nmc_ptr = (caddr_t)ptr;
789 	} else {
790 		/* The rest of the data will fit in this mbuf. */
791 
792 		/* the returned pointer will be the current pointer */
793 		*pptr = (u_char*)nmc->nmc_ptr;
794 
795 		/*
796 		 * update nmc's state to point at the end of the mbuf
797 		 * where the needed data will be copied to.
798 		 */
799 		nmc->nmc_ptr += left;
800 		nmc->nmc_left = 0;
801 	}
802 
803 	/*
804 	 * move the next "need" bytes into the current
805 	 * mbuf from the mbufs that follow
806 	 */
807 
808 	/* extend current mbuf length */
809 	mbuf_setlen(mbcur, mbuf_len(mbcur) + need);
810 
811 	/* mb follows mbufs we're copying/compacting data from */
812 	mb = mbuf_next(mbcur);
813 
814 	while (need && mb) {
815 		/* copy as much as we need/can */
816 		ptr = mbuf_data(mb);
817 		mblen = mbuf_len(mb);
818 		cplen = MIN(mblen, need);
819 		if (cplen) {
820 			bcopy(ptr, nmc->nmc_ptr, cplen);
821 			/*
822 			 * update the mbuf's pointer and length to reflect that
823 			 * the data was shifted to an earlier mbuf in the chain
824 			 */
825 			error = mbuf_setdata(mb, ptr + cplen, mblen - cplen);
826 			if (error) {
827 				mbuf_setlen(mbcur, mbuf_len(mbcur) - need);
828 				return error;
829 			}
830 			/* update pointer/need */
831 			nmc->nmc_ptr += cplen;
832 			need -= cplen;
833 		}
834 		/* if more needed, go to next mbuf */
835 		if (need) {
836 			mb = mbuf_next(mb);
837 		}
838 	}
839 
840 	/* did we run out of data in the mbuf chain? */
841 	if (need) {
842 		mbuf_setlen(mbcur, mbuf_len(mbcur) - need);
843 		return EBADRPC;
844 	}
845 
846 	/*
847 	 * update nmc's state to point after this contiguous data
848 	 *
849 	 * "mb" points to the last mbuf we copied data from so we
850 	 * just set nmc to point at whatever remains in that mbuf.
851 	 */
852 	nmc->nmc_mcur = mb;
853 	nmc->nmc_ptr = mbuf_data(mb);
854 	nmc->nmc_left = mbuf_len(mb);
855 
856 	/* move past any padding */
857 	if (padlen) {
858 		error = nfsm_chain_advance(nmc, padlen);
859 	}
860 
861 	return error;
862 }
863 
864 /*
865  * nfsm_chain_get_opaque_f()
866  *
867  * Read the next "len" bytes in the chain into "buf".
868  * The nfsm_chain is advanced by nfsm_rndup("len") bytes.
869  */
870 int
nfsm_chain_get_opaque_f(struct nfsm_chain * nmc,size_t len,u_char * buf)871 nfsm_chain_get_opaque_f(struct nfsm_chain *nmc, size_t len, u_char *buf)
872 {
873 	size_t cplen, padlen;
874 	int error = 0;
875 
876 	padlen = nfsm_rndup(len) - len;
877 
878 	/* loop through mbufs copying all the data we need */
879 	while (len && nmc->nmc_mcur) {
880 		/* copy as much as we need/can */
881 		cplen = MIN(nmc->nmc_left, len);
882 		if (cplen) {
883 			bcopy(nmc->nmc_ptr, buf, cplen);
884 			nmc->nmc_ptr += cplen;
885 			nmc->nmc_left -= cplen;
886 			buf += cplen;
887 			len -= cplen;
888 		}
889 		/* if more needed, go to next mbuf */
890 		if (len) {
891 			mbuf_t mb = mbuf_next(nmc->nmc_mcur);
892 			nmc->nmc_mcur = mb;
893 			nmc->nmc_ptr = mb ? mbuf_data(mb) : NULL;
894 			nmc->nmc_left = mb ? mbuf_len(mb) : 0;
895 		}
896 	}
897 
898 	/* did we run out of data in the mbuf chain? */
899 	if (len) {
900 		return EBADRPC;
901 	}
902 
903 	if (padlen) {
904 		nfsm_chain_adv(error, nmc, padlen);
905 	}
906 
907 	return error;
908 }
909 
910 /*
911  * nfsm_chain_get_uio()
912  *
913  * Read the next "len" bytes in the chain into the given uio.
914  * The nfsm_chain is advanced by nfsm_rndup("len") bytes.
915  */
916 int
nfsm_chain_get_uio(struct nfsm_chain * nmc,size_t len,uio_t uio)917 nfsm_chain_get_uio(struct nfsm_chain *nmc, size_t len, uio_t uio)
918 {
919 	size_t cplen, padlen;
920 	int error = 0;
921 
922 	padlen = nfsm_rndup(len) - len;
923 
924 	/* loop through mbufs copying all the data we need */
925 	while (len && nmc->nmc_mcur) {
926 		/* copy as much as we need/can */
927 		cplen = MIN(nmc->nmc_left, len);
928 		if (cplen) {
929 			cplen = MIN(cplen, INT32_MAX);
930 			error = uiomove(nmc->nmc_ptr, (int)cplen, uio);
931 			if (error) {
932 				return error;
933 			}
934 			nmc->nmc_ptr += cplen;
935 			nmc->nmc_left -= cplen;
936 			len -= cplen;
937 		}
938 		/* if more needed, go to next mbuf */
939 		if (len) {
940 			mbuf_t mb = mbuf_next(nmc->nmc_mcur);
941 			nmc->nmc_mcur = mb;
942 			nmc->nmc_ptr = mb ? mbuf_data(mb) : NULL;
943 			nmc->nmc_left = mb ? mbuf_len(mb) : 0;
944 		}
945 	}
946 
947 	/* did we run out of data in the mbuf chain? */
948 	if (len) {
949 		return EBADRPC;
950 	}
951 
952 	if (padlen) {
953 		nfsm_chain_adv(error, nmc, padlen);
954 	}
955 
956 	return error;
957 }
958 
959 #if CONFIG_NFS_CLIENT
960 
961 int
nfsm_chain_add_string_nfc(struct nfsm_chain * nmc,const uint8_t * s,size_t slen)962 nfsm_chain_add_string_nfc(struct nfsm_chain *nmc, const uint8_t *s, size_t slen)
963 {
964 	uint8_t smallbuf[64];
965 	uint8_t *nfcname = smallbuf;
966 	size_t buflen = sizeof(smallbuf), nfclen;
967 	int error;
968 
969 	error = utf8_normalizestr(s, slen, nfcname, &nfclen, buflen, UTF_PRECOMPOSED | UTF_NO_NULL_TERM);
970 	if (error == ENAMETOOLONG) {
971 		buflen = MAXPATHLEN;
972 		nfcname = zalloc(ZV_NAMEI);
973 		error = utf8_normalizestr(s, slen, nfcname, &nfclen, buflen, UTF_PRECOMPOSED | UTF_NO_NULL_TERM);
974 	}
975 
976 	/* if we got an error, just use the original string */
977 	if (error) {
978 		nfsm_chain_add_string(error, nmc, s, slen);
979 	} else {
980 		nfsm_chain_add_string(error, nmc, nfcname, nfclen);
981 	}
982 
983 	if (nfcname && (nfcname != smallbuf)) {
984 		NFS_ZFREE(ZV_NAMEI, nfcname);
985 	}
986 	return error;
987 }
988 
989 /*
990  * Add a verifier that can reasonably be expected to be unique.
991  */
992 int
nfsm_chaim_add_exclusive_create_verifier(int error,struct nfsm_chain * nmreq,struct nfsmount * nmp)993 nfsm_chaim_add_exclusive_create_verifier(int error, struct nfsm_chain *nmreq, struct nfsmount *nmp)
994 {
995 	uint32_t val;
996 	uint64_t xid;
997 	struct sockaddr ss;
998 
999 	nfs_get_xid(&xid);
1000 	val = (uint32_t)(xid >> 32);
1001 
1002 	if (nmp->nm_nso && !sock_getsockname(nmp->nm_nso->nso_so, (struct sockaddr*)&ss, sizeof(ss))) {
1003 		if (nmp->nm_saddr->sa_family == AF_INET) {
1004 			val = ((struct sockaddr_in*)&ss)->sin_addr.s_addr;
1005 		} else if (nmp->nm_saddr->sa_family == AF_INET6) {
1006 			val = ((struct sockaddr_in6*)&ss)->sin6_addr.__u6_addr.__u6_addr32[3];
1007 		}
1008 	}
1009 
1010 	nfsm_chain_add_32(error, nmreq, val);
1011 	nfsm_chain_add_32(error, nmreq, (uint32_t)xid);
1012 
1013 	return error;
1014 }
1015 
1016 /*
1017  * Add an NFSv2 "sattr" structure to an mbuf chain
1018  */
1019 int
nfsm_chain_add_v2sattr_f(struct nfsm_chain * nmc,struct vnode_attr * vap,uint32_t szrdev)1020 nfsm_chain_add_v2sattr_f(struct nfsm_chain *nmc, struct vnode_attr *vap, uint32_t szrdev)
1021 {
1022 	int error = 0;
1023 
1024 	nfsm_chain_add_32(error, nmc, vtonfsv2_mode(vap->va_type,
1025 	    (VATTR_IS_ACTIVE(vap, va_mode) ? vap->va_mode : 0600)));
1026 	nfsm_chain_add_32(error, nmc,
1027 	    VATTR_IS_ACTIVE(vap, va_uid) ? vap->va_uid : (uint32_t)-1);
1028 	nfsm_chain_add_32(error, nmc,
1029 	    VATTR_IS_ACTIVE(vap, va_gid) ? vap->va_gid : (uint32_t)-1);
1030 	nfsm_chain_add_32(error, nmc, szrdev);
1031 	nfsm_chain_add_v2time(error, nmc,
1032 	    VATTR_IS_ACTIVE(vap, va_access_time) ?
1033 	    &vap->va_access_time : NULL);
1034 	nfsm_chain_add_v2time(error, nmc,
1035 	    VATTR_IS_ACTIVE(vap, va_modify_time) ?
1036 	    &vap->va_modify_time : NULL);
1037 
1038 	return error;
1039 }
1040 
1041 /*
1042  * Add an NFSv3 "sattr" structure to an mbuf chain
1043  */
1044 int
nfsm_chain_add_v3sattr_f(__unused struct nfsmount * nmp,struct nfsm_chain * nmc,struct vnode_attr * vap)1045 nfsm_chain_add_v3sattr_f(
1046 	__unused struct nfsmount *nmp,
1047 	struct nfsm_chain *nmc,
1048 	struct vnode_attr *vap)
1049 {
1050 	int error = 0;
1051 
1052 	if (VATTR_IS_ACTIVE(vap, va_mode)) {
1053 		nfsm_chain_add_32(error, nmc, TRUE);
1054 		nfsm_chain_add_32(error, nmc, vap->va_mode);
1055 	} else {
1056 		nfsm_chain_add_32(error, nmc, FALSE);
1057 	}
1058 	if (VATTR_IS_ACTIVE(vap, va_uid)) {
1059 		nfsm_chain_add_32(error, nmc, TRUE);
1060 		nfsm_chain_add_32(error, nmc, vap->va_uid);
1061 	} else {
1062 		nfsm_chain_add_32(error, nmc, FALSE);
1063 	}
1064 	if (VATTR_IS_ACTIVE(vap, va_gid)) {
1065 		nfsm_chain_add_32(error, nmc, TRUE);
1066 		nfsm_chain_add_32(error, nmc, vap->va_gid);
1067 	} else {
1068 		nfsm_chain_add_32(error, nmc, FALSE);
1069 	}
1070 	if (VATTR_IS_ACTIVE(vap, va_data_size)) {
1071 		nfsm_chain_add_32(error, nmc, TRUE);
1072 		nfsm_chain_add_64(error, nmc, vap->va_data_size);
1073 	} else {
1074 		nfsm_chain_add_32(error, nmc, FALSE);
1075 	}
1076 	if (vap->va_vaflags & VA_UTIMES_NULL) {
1077 		nfsm_chain_add_32(error, nmc, NFS_TIME_SET_TO_SERVER);
1078 		nfsm_chain_add_32(error, nmc, NFS_TIME_SET_TO_SERVER);
1079 	} else {
1080 		if (VATTR_IS_ACTIVE(vap, va_access_time)) {
1081 			nfsm_chain_add_32(error, nmc, NFS_TIME_SET_TO_CLIENT);
1082 			nfsm_chain_add_32(error, nmc, vap->va_access_time.tv_sec);
1083 			nfsm_chain_add_32(error, nmc, vap->va_access_time.tv_nsec);
1084 		} else {
1085 			nfsm_chain_add_32(error, nmc, NFS_TIME_DONT_CHANGE);
1086 		}
1087 		if (VATTR_IS_ACTIVE(vap, va_modify_time)) {
1088 			nfsm_chain_add_32(error, nmc, NFS_TIME_SET_TO_CLIENT);
1089 			nfsm_chain_add_32(error, nmc, vap->va_modify_time.tv_sec);
1090 			nfsm_chain_add_32(error, nmc, vap->va_modify_time.tv_nsec);
1091 		} else {
1092 			nfsm_chain_add_32(error, nmc, NFS_TIME_DONT_CHANGE);
1093 		}
1094 	}
1095 
1096 	return error;
1097 }
1098 
1099 
1100 /*
1101  * nfsm_chain_get_fh_attr()
1102  *
1103  * Get the file handle and attributes from an mbuf chain. (NFSv2/v3)
1104  */
1105 int
nfsm_chain_get_fh_attr(struct nfsmount * nmp,struct nfsm_chain * nmc,nfsnode_t dnp,vfs_context_t ctx,int nfsvers,uint64_t * xidp,fhandle_t * fhp,struct nfs_vattr * nvap)1106 nfsm_chain_get_fh_attr(
1107 	struct nfsmount *nmp,
1108 	struct nfsm_chain *nmc,
1109 	nfsnode_t dnp,
1110 	vfs_context_t ctx,
1111 	int nfsvers,
1112 	uint64_t *xidp,
1113 	fhandle_t *fhp,
1114 	struct nfs_vattr *nvap)
1115 {
1116 	int error = 0, gotfh, gotattr;
1117 
1118 	gotfh = gotattr = 1;
1119 
1120 	if (nfsvers == NFS_VER3) { /* check for file handle */
1121 		nfsm_chain_get_32(error, nmc, gotfh);
1122 	}
1123 	if (!error && gotfh) { /* get file handle */
1124 		nfsm_chain_get_fh(error, nmc, nfsvers, fhp);
1125 	} else {
1126 		fhp->fh_len = 0;
1127 	}
1128 	if (nfsvers == NFS_VER3) { /* check for file attributes */
1129 		nfsm_chain_get_32(error, nmc, gotattr);
1130 	}
1131 	nfsmout_if(error);
1132 	if (gotattr) {
1133 		if (!gotfh) { /* skip attributes */
1134 			nfsm_chain_adv(error, nmc, NFSX_V3FATTR);
1135 		} else { /* get attributes */
1136 			error = nfs_parsefattr(nmp, nmc, nfsvers, nvap);
1137 		}
1138 	} else if (gotfh) {
1139 		/* we need valid attributes in order to call nfs_nget() */
1140 		if (nfs3_getattr_rpc(NULL, NFSTOMP(dnp), fhp->fh_data, fhp->fh_len, 0, ctx, nvap, xidp)) {
1141 			gotattr = 0;
1142 			fhp->fh_len = 0;
1143 		}
1144 	}
1145 nfsmout:
1146 	return error;
1147 }
1148 
1149 /*
1150  * Get and process NFSv3 WCC data from an mbuf chain
1151  */
1152 int
nfsm_chain_get_wcc_data_f(struct nfsm_chain * nmc,nfsnode_t np,struct timespec * premtime,int * newpostattr,u_int64_t * xidp)1153 nfsm_chain_get_wcc_data_f(
1154 	struct nfsm_chain *nmc,
1155 	nfsnode_t np,
1156 	struct timespec *premtime,
1157 	int *newpostattr,
1158 	u_int64_t *xidp)
1159 {
1160 	int error = 0;
1161 	uint32_t flag = 0;
1162 
1163 	nfsm_chain_get_32(error, nmc, flag);
1164 	if (!error && flag) {
1165 		nfsm_chain_adv(error, nmc, 2 * NFSX_UNSIGNED);
1166 		nfsm_chain_get_32(error, nmc, premtime->tv_sec);
1167 		nfsm_chain_get_32(error, nmc, premtime->tv_nsec);
1168 		nfsm_chain_adv(error, nmc, 2 * NFSX_UNSIGNED);
1169 	} else {
1170 		premtime->tv_sec = 0;
1171 		premtime->tv_nsec = 0;
1172 	}
1173 	nfsm_chain_postop_attr_update_flag(error, nmc, np, *newpostattr, xidp);
1174 
1175 	return error;
1176 }
1177 
1178 /*
1179  * Get the next RPC transaction ID (XID)
1180  */
1181 void
nfs_get_xid(uint64_t * xidp)1182 nfs_get_xid(uint64_t *xidp)
1183 {
1184 	struct timeval tv;
1185 
1186 	lck_mtx_lock(&nfs_request_mutex);
1187 	if (!nfs_xid) {
1188 		/*
1189 		 * Derive initial xid from system time.
1190 		 *
1191 		 * Note: it's OK if this code inits nfs_xid to 0 (for example,
1192 		 * due to a broken clock) because we immediately increment it
1193 		 * and we guarantee to never use xid 0.  So, nfs_xid should only
1194 		 * ever be 0 the first time this function is called.
1195 		 */
1196 		microtime(&tv);
1197 		nfs_xid = tv.tv_sec << 12;
1198 	}
1199 	if (++nfs_xid == 0) {
1200 		/* Skip zero xid if it should ever happen. */
1201 		nfs_xidwrap++;
1202 		nfs_xid++;
1203 	}
1204 	*xidp = nfs_xid + (nfs_xidwrap << 32);
1205 	lck_mtx_unlock(&nfs_request_mutex);
1206 }
1207 
1208 /*
1209  * Build the RPC header and fill in the authorization info.
1210  * Returns the head of the mbuf list and the xid.
1211  */
1212 
1213 int
nfsm_rpchead(struct nfsreq * req,mbuf_t mrest,u_int64_t * xidp,mbuf_t * mreqp)1214 nfsm_rpchead(
1215 	struct nfsreq *req,
1216 	mbuf_t mrest,
1217 	u_int64_t *xidp,
1218 	mbuf_t *mreqp)
1219 {
1220 	struct nfsmount *nmp = req->r_nmp;
1221 	int nfsvers = nmp->nm_vers;
1222 	int proc = ((nfsvers == NFS_VER2) ? nfsv2_procid[req->r_procnum] : (int)req->r_procnum);
1223 
1224 	return nfsm_rpchead2(nmp, nmp->nm_sotype, NFS_PROG, nfsvers, proc,
1225 	           req->r_auth, req->r_cred, req, mrest, xidp, mreqp);
1226 }
1227 
1228 /*
1229  * get_auiliary_groups:	Gets the supplementary groups from a credential.
1230  *
1231  * IN:		cred:	credential to get the associated groups from.
1232  * OUT:		groups:	An array of gids of NGROUPS size.
1233  * IN:		count:	The number of groups to get; i.e.; the number of groups the server supports
1234  *
1235  * returns:	The number of groups found.
1236  *
1237  * Just a wrapper around kauth_cred_getgroups to handle the case of a server supporting less
1238  * than NGROUPS.
1239  */
1240 static size_t
get_auxiliary_groups(kauth_cred_t cred,gid_t groups[NGROUPS],size_t count)1241 get_auxiliary_groups(kauth_cred_t cred, gid_t groups[NGROUPS], size_t count)
1242 {
1243 	gid_t pgid;
1244 	size_t maxcount = count < NGROUPS ? count + 1 : NGROUPS;
1245 	size_t i;
1246 
1247 	for (i = 0; i < NGROUPS; i++) {
1248 		groups[i] = -2; /* Initialize to the nobody group */
1249 	}
1250 	(void)kauth_cred_getgroups(cred, groups, &maxcount);
1251 	if (maxcount < 1) {
1252 		return maxcount;
1253 	}
1254 
1255 	/*
1256 	 * kauth_get_groups returns the primary group followed by the
1257 	 * users auxiliary groups. If the number of groups the server supports
1258 	 * is less than NGROUPS, then we will drop the first group so that
1259 	 * we can send one more group over the wire.
1260 	 */
1261 
1262 
1263 	if (count < NGROUPS) {
1264 		pgid = kauth_cred_getgid(cred);
1265 		if (pgid == groups[0]) {
1266 			maxcount -= 1;
1267 			for (i = 0; i < maxcount; i++) {
1268 				groups[i] = groups[i + 1];
1269 			}
1270 		}
1271 	}
1272 
1273 	return maxcount;
1274 }
1275 
1276 int
nfsm_rpchead2(__unused struct nfsmount * nmp,int sotype,int prog,int vers,int proc,int auth_type,kauth_cred_t cred,__unused struct nfsreq * req,mbuf_t mrest,u_int64_t * xidp,mbuf_t * mreqp)1277 nfsm_rpchead2(__unused struct nfsmount *nmp, int sotype, int prog, int vers, int proc, int auth_type,
1278     kauth_cred_t cred, __unused struct nfsreq *req, mbuf_t mrest, u_int64_t *xidp, mbuf_t *mreqp)
1279 {
1280 	mbuf_t mreq, mb;
1281 	size_t i;
1282 	int error, auth_len = 0, authsiz, reqlen;
1283 	size_t headlen;
1284 	struct nfsm_chain nmreq;
1285 	gid_t grouplist[NGROUPS];
1286 	size_t groupcount = 0;
1287 
1288 	/* calculate expected auth length */
1289 	switch (auth_type) {
1290 	case RPCAUTH_NONE:
1291 		auth_len = 0;
1292 		break;
1293 	case RPCAUTH_SYS:
1294 	{
1295 		size_t count = nmp->nm_numgrps < NGROUPS ? nmp->nm_numgrps : NGROUPS;
1296 
1297 		if (!cred) {
1298 			return EINVAL;
1299 		}
1300 		groupcount = get_auxiliary_groups(cred, grouplist, count);
1301 		auth_len = ((uint32_t)groupcount + 5) * NFSX_UNSIGNED;
1302 		break;
1303 	}
1304 #if CONFIG_NFS_GSS
1305 	case RPCAUTH_KRB5:
1306 	case RPCAUTH_KRB5I:
1307 	case RPCAUTH_KRB5P:
1308 		if (!req || !cred) {
1309 			return EINVAL;
1310 		}
1311 		auth_len = 5 * NFSX_UNSIGNED + 0;         // zero context handle for now
1312 		break;
1313 #endif /* CONFIG_NFS_GSS */
1314 	default:
1315 		return EINVAL;
1316 	}
1317 	authsiz = nfsm_rndup(auth_len);
1318 
1319 	/* allocate the packet */
1320 	headlen = authsiz + 10 * NFSX_UNSIGNED;
1321 	if (sotype == SOCK_STREAM) { /* also include room for any RPC Record Mark */
1322 		headlen += NFSX_UNSIGNED;
1323 	}
1324 	if (headlen >= nfs_mbuf_minclsize) {
1325 		error = mbuf_getpacket(MBUF_WAITOK, &mreq);
1326 	} else {
1327 		error = mbuf_gethdr(MBUF_WAITOK, MBUF_TYPE_DATA, &mreq);
1328 		if (!error) {
1329 			if (headlen < nfs_mbuf_mhlen) {
1330 				mbuf_align_32(mreq, headlen);
1331 			} else {
1332 				mbuf_align_32(mreq, 8 * NFSX_UNSIGNED);
1333 			}
1334 		}
1335 	}
1336 	if (error) {
1337 		/* unable to allocate packet */
1338 		/* XXX should we keep statistics for these errors? */
1339 		return error;
1340 	}
1341 
1342 	/*
1343 	 * If the caller gave us a non-zero XID then use it because
1344 	 * it may be a higher-level resend with a GSSAPI credential.
1345 	 * Otherwise, allocate a new one.
1346 	 */
1347 	if (*xidp == 0) {
1348 		nfs_get_xid(xidp);
1349 	}
1350 
1351 	/* build the header(s) */
1352 	nfsm_chain_init(&nmreq, mreq);
1353 
1354 	/* First, if it's a TCP stream insert space for an RPC record mark */
1355 	if (sotype == SOCK_STREAM) {
1356 		nfsm_chain_add_32(error, &nmreq, 0);
1357 	}
1358 
1359 	/* Then the RPC header. */
1360 	nfsm_chain_add_32(error, &nmreq, (*xidp & 0xffffffff));
1361 	nfsm_chain_add_32(error, &nmreq, RPC_CALL);
1362 	nfsm_chain_add_32(error, &nmreq, RPC_VER2);
1363 	nfsm_chain_add_32(error, &nmreq, prog);
1364 	nfsm_chain_add_32(error, &nmreq, vers);
1365 	nfsm_chain_add_32(error, &nmreq, proc);
1366 
1367 #if CONFIG_NFS_GSS
1368 add_cred:
1369 #endif
1370 	switch (auth_type) {
1371 	case RPCAUTH_NONE:
1372 		nfsm_chain_add_32(error, &nmreq, RPCAUTH_NONE); /* auth */
1373 		nfsm_chain_add_32(error, &nmreq, 0);            /* length */
1374 		nfsm_chain_add_32(error, &nmreq, RPCAUTH_NONE); /* verf */
1375 		nfsm_chain_add_32(error, &nmreq, 0);            /* length */
1376 		nfsm_chain_build_done(error, &nmreq);
1377 		/* Append the args mbufs */
1378 		if (!error) {
1379 			error = mbuf_setnext(nmreq.nmc_mcur, mrest);
1380 		}
1381 		break;
1382 	case RPCAUTH_SYS: {
1383 		nfsm_chain_add_32(error, &nmreq, RPCAUTH_SYS);
1384 		nfsm_chain_add_32(error, &nmreq, authsiz);
1385 		{
1386 			nfsm_chain_add_32(error, &nmreq, 0);    /* stamp */
1387 		}
1388 		nfsm_chain_add_32(error, &nmreq, 0);    /* zero-length hostname */
1389 		nfsm_chain_add_32(error, &nmreq, kauth_cred_getuid(cred));      /* UID */
1390 		nfsm_chain_add_32(error, &nmreq, kauth_cred_getgid(cred));      /* GID */
1391 		nfsm_chain_add_32(error, &nmreq, groupcount);/* additional GIDs */
1392 		for (i = 0; i < groupcount; i++) {
1393 			nfsm_chain_add_32(error, &nmreq, grouplist[i]);
1394 		}
1395 
1396 		/* And the verifier... */
1397 		nfsm_chain_add_32(error, &nmreq, RPCAUTH_NONE); /* flavor */
1398 		nfsm_chain_add_32(error, &nmreq, 0);            /* length */
1399 		nfsm_chain_build_done(error, &nmreq);
1400 
1401 		/* Append the args mbufs */
1402 		if (!error) {
1403 			error = mbuf_setnext(nmreq.nmc_mcur, mrest);
1404 		}
1405 		break;
1406 	}
1407 #if CONFIG_NFS_GSS
1408 	case RPCAUTH_KRB5:
1409 	case RPCAUTH_KRB5I:
1410 	case RPCAUTH_KRB5P:
1411 		error = nfs_gss_clnt_cred_put(req, &nmreq, mrest);
1412 		if (error == ENEEDAUTH) {
1413 			size_t count = nmp->nm_numgrps < NGROUPS ? nmp->nm_numgrps : NGROUPS;
1414 
1415 			/*
1416 			 * Use sec=sys for this user
1417 			 */
1418 			error = 0;
1419 			req->r_auth = auth_type = RPCAUTH_SYS;
1420 			groupcount = get_auxiliary_groups(cred, grouplist, count);
1421 			auth_len = ((uint32_t)groupcount + 5) * NFSX_UNSIGNED;
1422 			authsiz = nfsm_rndup(auth_len);
1423 			goto add_cred;
1424 		}
1425 		break;
1426 #endif /* CONFIG_NFS_GSS */
1427 	}
1428 	;
1429 
1430 	/* finish setting up the packet */
1431 	if (!error) {
1432 		error = mbuf_pkthdr_setrcvif(mreq, 0);
1433 	}
1434 
1435 	if (error) {
1436 		mbuf_freem(mreq);
1437 		return error;
1438 	}
1439 
1440 	/* Calculate the size of the request */
1441 	reqlen = 0;
1442 	for (mb = nmreq.nmc_mhead; mb; mb = mbuf_next(mb)) {
1443 		reqlen += mbuf_len(mb);
1444 	}
1445 
1446 	mbuf_pkthdr_setlen(mreq, reqlen);
1447 
1448 	/*
1449 	 * If the request goes on a TCP stream,
1450 	 * set its size in the RPC record mark.
1451 	 * The record mark count doesn't include itself
1452 	 * and the last fragment bit is set.
1453 	 */
1454 	if (sotype == SOCK_STREAM) {
1455 		nfsm_chain_set_recmark(error, &nmreq,
1456 		    (reqlen - NFSX_UNSIGNED) | 0x80000000);
1457 	}
1458 
1459 	*mreqp = mreq;
1460 	return 0;
1461 }
1462 
1463 /*
1464  * Parse an NFS file attribute structure out of an mbuf chain.
1465  */
1466 int
nfs_parsefattr(__unused struct nfsmount * nmp,struct nfsm_chain * nmc,int nfsvers,struct nfs_vattr * nvap)1467 nfs_parsefattr(
1468 	__unused struct nfsmount *nmp,
1469 	struct nfsm_chain *nmc,
1470 	int nfsvers,
1471 	struct nfs_vattr *nvap)
1472 {
1473 	int error = 0;
1474 	enum vtype vtype;
1475 	nfstype nvtype;
1476 	uint32_t vmode, val, val2;
1477 	dev_t rdev;
1478 
1479 	val = val2 = 0;
1480 	NVATTR_INIT(nvap);
1481 
1482 	NFS_BITMAP_SET(nvap->nva_bitmap, NFS_FATTR_TYPE);
1483 	NFS_BITMAP_SET(nvap->nva_bitmap, NFS_FATTR_MODE);
1484 	NFS_BITMAP_SET(nvap->nva_bitmap, NFS_FATTR_NUMLINKS);
1485 	NFS_BITMAP_SET(nvap->nva_bitmap, NFS_FATTR_OWNER);
1486 	NFS_BITMAP_SET(nvap->nva_bitmap, NFS_FATTR_OWNER_GROUP);
1487 	NFS_BITMAP_SET(nvap->nva_bitmap, NFS_FATTR_SIZE);
1488 	NFS_BITMAP_SET(nvap->nva_bitmap, NFS_FATTR_SPACE_USED);
1489 	NFS_BITMAP_SET(nvap->nva_bitmap, NFS_FATTR_RAWDEV);
1490 	NFS_BITMAP_SET(nvap->nva_bitmap, NFS_FATTR_FSID);
1491 	NFS_BITMAP_SET(nvap->nva_bitmap, NFS_FATTR_FILEID);
1492 	NFS_BITMAP_SET(nvap->nva_bitmap, NFS_FATTR_TIME_ACCESS);
1493 	NFS_BITMAP_SET(nvap->nva_bitmap, NFS_FATTR_TIME_MODIFY);
1494 	NFS_BITMAP_SET(nvap->nva_bitmap, NFS_FATTR_TIME_METADATA);
1495 
1496 	nfsm_chain_get_32(error, nmc, nvtype);
1497 	nfsm_chain_get_32(error, nmc, vmode);
1498 	nfsmout_if(error);
1499 
1500 	if (nfsvers == NFS_VER3) {
1501 		nvap->nva_type = vtype = nfstov_type(nvtype, nfsvers);
1502 	} else {
1503 		/*
1504 		 * The duplicate information returned in fa_type and fa_mode
1505 		 * is an ambiguity in the NFS version 2 protocol.
1506 		 *
1507 		 * VREG should be taken literally as a regular file.  If a
1508 		 * server intends to return some type information differently
1509 		 * in the upper bits of the mode field (e.g. for sockets, or
1510 		 * FIFOs), NFSv2 mandates fa_type to be VNON.  Anyway, we
1511 		 * leave the examination of the mode bits even in the VREG
1512 		 * case to avoid breakage for bogus servers, but we make sure
1513 		 * that there are actually type bits set in the upper part of
1514 		 * fa_mode (and failing that, trust the va_type field).
1515 		 *
1516 		 * NFSv3 cleared the issue, and requires fa_mode to not
1517 		 * contain any type information (while also introducing
1518 		 * sockets and FIFOs for fa_type).
1519 		 */
1520 		vtype = nfstov_type(nvtype, nfsvers);
1521 		if ((vtype == VNON) || ((vtype == VREG) && ((vmode & S_IFMT) != 0))) {
1522 			vtype = IFTOVT(vmode);
1523 		}
1524 		nvap->nva_type = vtype;
1525 	}
1526 
1527 	nvap->nva_mode = (vmode & 07777);
1528 
1529 	nfsm_chain_get_32(error, nmc, nvap->nva_nlink);
1530 	nfsm_chain_get_32(error, nmc, nvap->nva_uid);
1531 	nfsm_chain_get_32(error, nmc, nvap->nva_gid);
1532 
1533 	if (nfsvers == NFS_VER3) {
1534 		nfsm_chain_get_64(error, nmc, nvap->nva_size);
1535 		nfsm_chain_get_64(error, nmc, nvap->nva_bytes);
1536 		nfsm_chain_get_32(error, nmc, nvap->nva_rawdev.specdata1);
1537 		nfsm_chain_get_32(error, nmc, nvap->nva_rawdev.specdata2);
1538 		nfsmout_if(error);
1539 		nfsm_chain_get_64(error, nmc, nvap->nva_fsid.major);
1540 		nvap->nva_fsid.minor = 0;
1541 		nfsm_chain_get_64(error, nmc, nvap->nva_fileid);
1542 	} else {
1543 		nfsm_chain_get_32(error, nmc, nvap->nva_size);
1544 		nfsm_chain_adv(error, nmc, NFSX_UNSIGNED);
1545 		nfsm_chain_get_32(error, nmc, rdev);
1546 		nfsmout_if(error);
1547 		nvap->nva_rawdev.specdata1 = major(rdev);
1548 		nvap->nva_rawdev.specdata2 = minor(rdev);
1549 		nfsm_chain_get_32(error, nmc, val); /* blocks */
1550 		nfsmout_if(error);
1551 		nvap->nva_bytes = val * NFS_FABLKSIZE;
1552 		nfsm_chain_get_32(error, nmc, val);
1553 		nfsmout_if(error);
1554 		nvap->nva_fsid.major = (uint64_t)val;
1555 		nvap->nva_fsid.minor = 0;
1556 		nfsm_chain_get_32(error, nmc, val);
1557 		nfsmout_if(error);
1558 		nvap->nva_fileid = (uint64_t)val;
1559 		/* Really ugly NFSv2 kludge. */
1560 		if ((vtype == VCHR) && (rdev == (dev_t)0xffffffff)) {
1561 			nvap->nva_type = VFIFO;
1562 		}
1563 	}
1564 	nfsm_chain_get_time(error, nmc, nfsvers,
1565 	    nvap->nva_timesec[NFSTIME_ACCESS],
1566 	    nvap->nva_timensec[NFSTIME_ACCESS]);
1567 	nfsm_chain_get_time(error, nmc, nfsvers,
1568 	    nvap->nva_timesec[NFSTIME_MODIFY],
1569 	    nvap->nva_timensec[NFSTIME_MODIFY]);
1570 	nfsm_chain_get_time(error, nmc, nfsvers,
1571 	    nvap->nva_timesec[NFSTIME_CHANGE],
1572 	    nvap->nva_timensec[NFSTIME_CHANGE]);
1573 
1574 nfsmout:
1575 	return error;
1576 }
1577 
1578 /*
1579  * Load the attribute cache (that lives in the nfsnode entry) with
1580  * the value pointed to by nvap, unless the file type in the attribute
1581  * cache doesn't match the file type in the nvap, in which case log a
1582  * warning and return ESTALE.
1583  *
1584  * If the dontshrink flag is set, then it's not safe to call ubc_setsize()
1585  * to shrink the size of the file.
1586  */
1587 int
nfs_loadattrcache(nfsnode_t np,struct nfs_vattr * nvap,u_int64_t * xidp,int dontshrink)1588 nfs_loadattrcache(
1589 	nfsnode_t np,
1590 	struct nfs_vattr *nvap,
1591 	u_int64_t *xidp,
1592 	int dontshrink)
1593 {
1594 	mount_t mp;
1595 	vnode_t vp;
1596 	struct timeval now;
1597 	struct nfs_vattr *npnvap;
1598 	int xattr = np->n_vattr.nva_flags & NFS_FFLAG_IS_ATTR;
1599 	int referral = np->n_vattr.nva_flags & NFS_FFLAG_TRIGGER_REFERRAL;
1600 	int aclbit, monitored, error = 0;
1601 	kauth_acl_t acl;
1602 	struct nfsmount *nmp;
1603 	uint32_t events = np->n_events;
1604 
1605 	if (np->n_hflag & NHINIT) {
1606 		vp = NULL;
1607 		mp = np->n_mount;
1608 	} else {
1609 		vp = NFSTOV(np);
1610 		mp = vnode_mount(vp);
1611 	}
1612 	monitored = vp ? vnode_ismonitored(vp) : 0;
1613 
1614 	FSDBG_TOP(527, np, vp, *xidp >> 32, *xidp);
1615 
1616 	if (!((nmp = VFSTONFS(mp)))) {
1617 		FSDBG_BOT(527, ENXIO, 1, 0, *xidp);
1618 		return ENXIO;
1619 	}
1620 
1621 	if (*xidp < np->n_xid) {
1622 		/*
1623 		 * We have already updated attributes with a response from
1624 		 * a later request.  The attributes we have here are probably
1625 		 * stale so we drop them (just return).  However, our
1626 		 * out-of-order receipt could be correct - if the requests were
1627 		 * processed out of order at the server.  Given the uncertainty
1628 		 * we invalidate our cached attributes.  *xidp is zeroed here
1629 		 * to indicate the attributes were dropped - only getattr
1630 		 * cares - it needs to retry the rpc.
1631 		 */
1632 		NATTRINVALIDATE(np);
1633 		FSDBG_BOT(527, 0, np, np->n_xid, *xidp);
1634 		*xidp = 0;
1635 		return 0;
1636 	}
1637 
1638 	if (vp && (nvap->nva_type != vnode_vtype(vp))) {
1639 		/*
1640 		 * The filehandle has changed type on us.  This can be
1641 		 * caused by either the server not having unique filehandles
1642 		 * or because another client has removed the previous
1643 		 * filehandle and a new object (of a different type)
1644 		 * has been created with the same filehandle.
1645 		 *
1646 		 * We can't simply switch the type on the vnode because
1647 		 * there may be type-specific fields that need to be
1648 		 * cleaned up or set up.
1649 		 *
1650 		 * So, what should we do with this vnode?
1651 		 *
1652 		 * About the best we can do is log a warning and return
1653 		 * an error.  ESTALE is about the closest error, but it
1654 		 * is a little strange that we come up with this error
1655 		 * internally instead of simply passing it through from
1656 		 * the server.  Hopefully, the vnode will be reclaimed
1657 		 * soon so the filehandle can be reincarnated as the new
1658 		 * object type.
1659 		 */
1660 		printf("nfs loadattrcache vnode changed type, was %d now %d\n",
1661 		    vnode_vtype(vp), nvap->nva_type);
1662 		error = ESTALE;
1663 		if (monitored) {
1664 			events |= VNODE_EVENT_DELETE;
1665 		}
1666 		goto out;
1667 	}
1668 
1669 	npnvap = &np->n_vattr;
1670 
1671 	/*
1672 	 * The ACL cache needs special handling because it is not
1673 	 * always updated.  Save current ACL cache state so it can
1674 	 * be restored after copying the new attributes into place.
1675 	 */
1676 	aclbit = NFS_BITMAP_ISSET(npnvap->nva_bitmap, NFS_FATTR_ACL);
1677 	acl = npnvap->nva_acl;
1678 
1679 	if (monitored) {
1680 		/*
1681 		 * For monitored nodes, check for attribute changes that should generate events.
1682 		 */
1683 		if (NFS_BITMAP_ISSET(nvap->nva_bitmap, NFS_FATTR_NUMLINKS) &&
1684 		    (nvap->nva_nlink != npnvap->nva_nlink)) {
1685 			events |= VNODE_EVENT_ATTRIB | VNODE_EVENT_LINK;
1686 		}
1687 		if (events & VNODE_EVENT_PERMS) {
1688 			/* no need to do all the checking if it's already set */;
1689 		} else if (NFS_BITMAP_ISSET(nvap->nva_bitmap, NFS_FATTR_MODE) &&
1690 		    (nvap->nva_mode != npnvap->nva_mode)) {
1691 			events |= VNODE_EVENT_ATTRIB | VNODE_EVENT_PERMS;
1692 		} else if (NFS_BITMAP_ISSET(nvap->nva_bitmap, NFS_FATTR_OWNER) &&
1693 		    (nvap->nva_uid != npnvap->nva_uid)) {
1694 			events |= VNODE_EVENT_ATTRIB | VNODE_EVENT_PERMS;
1695 		} else if (NFS_BITMAP_ISSET(nvap->nva_bitmap, NFS_FATTR_OWNER_GROUP) &&
1696 		    (nvap->nva_gid != npnvap->nva_gid)) {
1697 			events |= VNODE_EVENT_ATTRIB | VNODE_EVENT_PERMS;
1698 #if CONFIG_NFS4
1699 		} else if (nmp->nm_vers >= NFS_VER4) {
1700 			if (NFS_BITMAP_ISSET(nvap->nva_bitmap, NFS_FATTR_OWNER) &&
1701 			    !kauth_guid_equal(&nvap->nva_uuuid, &npnvap->nva_uuuid)) {
1702 				events |= VNODE_EVENT_ATTRIB | VNODE_EVENT_PERMS;
1703 			} else if (NFS_BITMAP_ISSET(nvap->nva_bitmap, NFS_FATTR_OWNER_GROUP) &&
1704 			    !kauth_guid_equal(&nvap->nva_guuid, &npnvap->nva_guuid)) {
1705 				events |= VNODE_EVENT_ATTRIB | VNODE_EVENT_PERMS;
1706 			} else if ((NFS_BITMAP_ISSET(nvap->nva_bitmap, NFS_FATTR_ACL) &&
1707 			    nvap->nva_acl && npnvap->nva_acl &&
1708 			    ((nvap->nva_acl->acl_entrycount != npnvap->nva_acl->acl_entrycount) ||
1709 			    bcmp(nvap->nva_acl, npnvap->nva_acl, KAUTH_ACL_COPYSIZE(nvap->nva_acl))))) {
1710 				events |= VNODE_EVENT_ATTRIB | VNODE_EVENT_PERMS;
1711 			}
1712 #endif
1713 		}
1714 		if (/* Oh, C... */
1715 #if CONFIG_NFS4
1716 			((nmp->nm_vers >= NFS_VER4) && NFS_BITMAP_ISSET(nvap->nva_bitmap, NFS_FATTR_CHANGE) && (nvap->nva_change != npnvap->nva_change)) ||
1717 #endif
1718 			(NFS_BITMAP_ISSET(nvap->nva_bitmap, NFS_FATTR_TIME_MODIFY) &&
1719 			((nvap->nva_timesec[NFSTIME_MODIFY] != npnvap->nva_timesec[NFSTIME_MODIFY]) ||
1720 			(nvap->nva_timensec[NFSTIME_MODIFY] != npnvap->nva_timensec[NFSTIME_MODIFY])))) {
1721 			events |= VNODE_EVENT_ATTRIB | VNODE_EVENT_WRITE;
1722 		}
1723 		if (!events && NFS_BITMAP_ISSET(nvap->nva_bitmap, NFS_FATTR_RAWDEV) &&
1724 		    ((nvap->nva_rawdev.specdata1 != npnvap->nva_rawdev.specdata1) ||
1725 		    (nvap->nva_rawdev.specdata2 != npnvap->nva_rawdev.specdata2))) {
1726 			events |= VNODE_EVENT_ATTRIB;
1727 		}
1728 		if (!events && NFS_BITMAP_ISSET(nvap->nva_bitmap, NFS_FATTR_FILEID) &&
1729 		    (nvap->nva_fileid != npnvap->nva_fileid)) {
1730 			events |= VNODE_EVENT_ATTRIB;
1731 		}
1732 		if (!events && NFS_BITMAP_ISSET(nvap->nva_bitmap, NFS_FATTR_ARCHIVE) &&
1733 		    ((nvap->nva_flags & NFS_FFLAG_ARCHIVED) != (npnvap->nva_flags & NFS_FFLAG_ARCHIVED))) {
1734 			events |= VNODE_EVENT_ATTRIB;
1735 		}
1736 		if (!events && NFS_BITMAP_ISSET(nvap->nva_bitmap, NFS_FATTR_HIDDEN) &&
1737 		    ((nvap->nva_flags & NFS_FFLAG_HIDDEN) != (npnvap->nva_flags & NFS_FFLAG_HIDDEN))) {
1738 			events |= VNODE_EVENT_ATTRIB;
1739 		}
1740 		if (!events && NFS_BITMAP_ISSET(nvap->nva_bitmap, NFS_FATTR_TIME_CREATE) &&
1741 		    ((nvap->nva_timesec[NFSTIME_CREATE] != npnvap->nva_timesec[NFSTIME_CREATE]) ||
1742 		    (nvap->nva_timensec[NFSTIME_CREATE] != npnvap->nva_timensec[NFSTIME_CREATE]))) {
1743 			events |= VNODE_EVENT_ATTRIB;
1744 		}
1745 		if (!events && NFS_BITMAP_ISSET(nvap->nva_bitmap, NFS_FATTR_TIME_BACKUP) &&
1746 		    ((nvap->nva_timesec[NFSTIME_BACKUP] != npnvap->nva_timesec[NFSTIME_BACKUP]) ||
1747 		    (nvap->nva_timensec[NFSTIME_BACKUP] != npnvap->nva_timensec[NFSTIME_BACKUP]))) {
1748 			events |= VNODE_EVENT_ATTRIB;
1749 		}
1750 	}
1751 
1752 #if CONFIG_NFS4
1753 	/* Copy the attributes to the attribute cache */
1754 	if (nmp->nm_vers >= NFS_VER4 && npnvap->nva_flags & NFS_FFLAG_PARTIAL_WRITE) {
1755 		/*
1756 		 * NFSv4 WRITE RPCs contain partial GETATTR requests - only type, change, size, metadatatime and modifytime are requested.
1757 		 * In such cases,  we do not update the time stamp - but the requested attributes.
1758 		 */
1759 		NFS_BITMAP_COPY_ATTR(nvap, npnvap, TYPE, type);
1760 		NFS_BITMAP_COPY_ATTR(nvap, npnvap, CHANGE, change);
1761 		NFS_BITMAP_COPY_ATTR(nvap, npnvap, SIZE, size);
1762 		NFS_BITMAP_COPY_TIME(nvap, npnvap, METADATA, CHANGE);
1763 		NFS_BITMAP_COPY_TIME(nvap, npnvap, MODIFY, MODIFY);
1764 	} else
1765 #endif /* CONFIG_NFS4 */
1766 	{
1767 		bcopy((caddr_t)nvap, (caddr_t)npnvap, sizeof(*nvap));
1768 		microuptime(&now);
1769 		np->n_attrstamp = now.tv_sec;
1770 	}
1771 
1772 	np->n_xid = *xidp;
1773 	/* NFS_FFLAG_IS_ATTR and NFS_FFLAG_TRIGGER_REFERRAL need to be sticky... */
1774 	if (vp && xattr) {
1775 		nvap->nva_flags |= xattr;
1776 	}
1777 	if (vp && referral) {
1778 		nvap->nva_flags |= referral;
1779 	}
1780 
1781 	if (NFS_BITMAP_ISSET(nvap->nva_bitmap, NFS_FATTR_ACL)) {
1782 		/* we're updating the ACL */
1783 		if (nvap->nva_acl) {
1784 			/* make a copy of the acl for the cache */
1785 			npnvap->nva_acl = kauth_acl_alloc(nvap->nva_acl->acl_entrycount);
1786 			if (npnvap->nva_acl) {
1787 				bcopy(nvap->nva_acl, npnvap->nva_acl, KAUTH_ACL_COPYSIZE(nvap->nva_acl));
1788 			} else {
1789 				/* can't make a copy to cache, invalidate ACL cache */
1790 				NFS_BITMAP_CLR(npnvap->nva_bitmap, NFS_FATTR_ACL);
1791 				NACLINVALIDATE(np);
1792 				aclbit = 0;
1793 			}
1794 		}
1795 		if (acl) {
1796 			kauth_acl_free(acl);
1797 			acl = NULL;
1798 		}
1799 	}
1800 	if (NFS_BITMAP_ISSET(nvap->nva_bitmap, NFS_FATTR_ACL)) {
1801 		/* update the ACL timestamp */
1802 		microuptime(&now);
1803 		np->n_aclstamp = now.tv_sec;
1804 	} else {
1805 		/* we aren't updating the ACL, so restore original values */
1806 		if (aclbit) {
1807 			NFS_BITMAP_SET(npnvap->nva_bitmap, NFS_FATTR_ACL);
1808 		}
1809 		npnvap->nva_acl = acl;
1810 	}
1811 
1812 #if CONFIG_TRIGGERS
1813 #if CONFIG_NFS4
1814 	/*
1815 	 * For NFSv4, if the fsid doesn't match the fsid for the mount, then
1816 	 * this node is for a different file system on the server.  So we mark
1817 	 * this node as a trigger node that will trigger the mirror mount.
1818 	 */
1819 	if ((nmp->nm_vers >= NFS_VER4) && (nvap->nva_type == VDIR) &&
1820 	    ((np->n_vattr.nva_fsid.major != nmp->nm_fsid.major) ||
1821 	    (np->n_vattr.nva_fsid.minor != nmp->nm_fsid.minor))) {
1822 		np->n_vattr.nva_flags |= NFS_FFLAG_TRIGGER;
1823 	}
1824 #endif /* CONFIG_NFS4 */
1825 #endif /* CONFIG_TRIGGERS */
1826 
1827 	if (!vp || (nvap->nva_type != VREG)) {
1828 		np->n_size = nvap->nva_size;
1829 	} else if (nvap->nva_size != np->n_size) {
1830 		FSDBG(527, np, nvap->nva_size, np->n_size, (nvap->nva_type == VREG) | (np->n_flag & NMODIFIED ? 6 : 4));
1831 		if (!UBCINFOEXISTS(vp) || (dontshrink && (nvap->nva_size < np->n_size))) {
1832 			/* asked not to shrink, so stick with current size */
1833 			FSDBG(527, np, np->n_size, np->n_vattr.nva_size, 0xf00d0001);
1834 			nvap->nva_size = np->n_size;
1835 			NATTRINVALIDATE(np);
1836 		} else if ((np->n_flag & NMODIFIED) && (nvap->nva_size < np->n_size)) {
1837 			/* if we've modified, stick with larger size */
1838 			FSDBG(527, np, np->n_size, np->n_vattr.nva_size, 0xf00d0002);
1839 			nvap->nva_size = np->n_size;
1840 			npnvap->nva_size = np->n_size;
1841 		} else {
1842 			/*
1843 			 * n_size is protected by the data lock, so we need to
1844 			 * defer updating it until it's safe.  We save the new size
1845 			 * and set a flag and it'll get updated the next time we get/drop
1846 			 * the data lock or the next time we do a getattr.
1847 			 */
1848 			np->n_newsize = nvap->nva_size;
1849 			SET(np->n_flag, NUPDATESIZE);
1850 			if (monitored) {
1851 				events |= VNODE_EVENT_ATTRIB | VNODE_EVENT_EXTEND;
1852 			}
1853 		}
1854 	}
1855 
1856 	if (np->n_flag & NCHG) {
1857 		if (np->n_flag & NACC) {
1858 			nvap->nva_timesec[NFSTIME_ACCESS] = np->n_atim.tv_sec;
1859 			nvap->nva_timensec[NFSTIME_ACCESS] = np->n_atim.tv_nsec;
1860 		}
1861 		if (np->n_flag & NUPD) {
1862 			nvap->nva_timesec[NFSTIME_MODIFY] = np->n_mtim.tv_sec;
1863 			nvap->nva_timensec[NFSTIME_MODIFY] = np->n_mtim.tv_nsec;
1864 		}
1865 	}
1866 
1867 out:
1868 	if (monitored && events) {
1869 		nfs_vnode_notify(np, events);
1870 	}
1871 	FSDBG_BOT(527, error, np, np->n_size, *xidp);
1872 	return error;
1873 }
1874 
1875 /*
1876  * Calculate the attribute timeout based on
1877  * how recently the file has been modified.
1878  */
1879 long
nfs_attrcachetimeout(nfsnode_t np)1880 nfs_attrcachetimeout(nfsnode_t np)
1881 {
1882 	struct nfsmount *nmp;
1883 	struct timeval now;
1884 	int isdir;
1885 	long timeo;
1886 
1887 	nmp = NFSTONMP(np);
1888 	if (nfs_mount_gone(nmp)) {
1889 		return 0;
1890 	}
1891 
1892 	isdir = vnode_isdir(NFSTOV(np));
1893 #if CONFIG_NFS4
1894 	if ((nmp->nm_vers >= NFS_VER4) && (np->n_openflags & N_DELEG_MASK)) {
1895 		/* If we have a delegation, we always use the max timeout. */
1896 		timeo = isdir ? nmp->nm_acdirmax : nmp->nm_acregmax;
1897 	} else
1898 #endif
1899 	if ((np)->n_flag & NMODIFIED) {
1900 		/* If we have modifications, we always use the min timeout. */
1901 		timeo = isdir ? nmp->nm_acdirmin : nmp->nm_acregmin;
1902 	} else {
1903 		/* Otherwise, we base the timeout on how old the file seems. */
1904 		/* Note that if the client and server clocks are way out of sync, */
1905 		/* timeout will probably get clamped to a min or max value */
1906 		microtime(&now);
1907 		timeo = (now.tv_sec - (np)->n_vattr.nva_timesec[NFSTIME_MODIFY]) / 10;
1908 		if (isdir) {
1909 			if (timeo < nmp->nm_acdirmin) {
1910 				timeo = nmp->nm_acdirmin;
1911 			} else if (timeo > nmp->nm_acdirmax) {
1912 				timeo = nmp->nm_acdirmax;
1913 			}
1914 		} else {
1915 			if (timeo < nmp->nm_acregmin) {
1916 				timeo = nmp->nm_acregmin;
1917 			} else if (timeo > nmp->nm_acregmax) {
1918 				timeo = nmp->nm_acregmax;
1919 			}
1920 		}
1921 	}
1922 
1923 	return timeo;
1924 }
1925 
1926 /*
1927  * Check the attribute cache time stamp.
1928  * If the cache is valid, copy contents to *nvaper and return 0
1929  * otherwise return an error.
1930  * Must be called with the node locked.
1931  */
1932 int
nfs_getattrcache(nfsnode_t np,struct nfs_vattr * nvaper,int flags)1933 nfs_getattrcache(nfsnode_t np, struct nfs_vattr *nvaper, int flags)
1934 {
1935 	struct nfs_vattr *nvap;
1936 	struct timeval nowup;
1937 	long timeo;
1938 	struct nfsmount *nmp;
1939 
1940 	/* Check if the attributes are valid. */
1941 	if (!NATTRVALID(np) || ((flags & NGA_ACL) && !NACLVALID(np))) {
1942 		FSDBG(528, np, 0, 0xffffff01, ENOENT);
1943 		OSAddAtomic64(1, &nfsclntstats.attrcache_misses);
1944 		return ENOENT;
1945 	}
1946 
1947 	nmp = NFSTONMP(np);
1948 	if (nfs_mount_gone(nmp)) {
1949 		return ENXIO;
1950 	}
1951 	/*
1952 	 * Verify the cached attributes haven't timed out.
1953 	 * If the server isn't responding, skip the check
1954 	 * and return cached attributes.
1955 	 */
1956 	if (!nfs_use_cache(nmp)) {
1957 		microuptime(&nowup);
1958 		if (np->n_attrstamp > nowup.tv_sec) {
1959 			printf("NFS: Attribute time stamp is in the future by %ld seconds. Invalidating cache\n",
1960 			    np->n_attrstamp - nowup.tv_sec);
1961 			NATTRINVALIDATE(np);
1962 			NACCESSINVALIDATE(np);
1963 			return ENOENT;
1964 		}
1965 		timeo = nfs_attrcachetimeout(np);
1966 		if ((nowup.tv_sec - np->n_attrstamp) >= timeo) {
1967 			FSDBG(528, np, 0, 0xffffff02, ENOENT);
1968 			OSAddAtomic64(1, &nfsclntstats.attrcache_misses);
1969 			return ENOENT;
1970 		}
1971 		if ((flags & NGA_ACL) && ((nowup.tv_sec - np->n_aclstamp) >= timeo)) {
1972 			FSDBG(528, np, 0, 0xffffff02, ENOENT);
1973 			OSAddAtomic64(1, &nfsclntstats.attrcache_misses);
1974 			return ENOENT;
1975 		}
1976 	}
1977 
1978 	nvap = &np->n_vattr;
1979 	FSDBG(528, np, nvap->nva_size, np->n_size, 0xcace);
1980 	OSAddAtomic64(1, &nfsclntstats.attrcache_hits);
1981 
1982 	if (nvap->nva_type != VREG) {
1983 		np->n_size = nvap->nva_size;
1984 	} else if (nvap->nva_size != np->n_size) {
1985 		FSDBG(528, np, nvap->nva_size, np->n_size, (nvap->nva_type == VREG) | (np->n_flag & NMODIFIED ? 6 : 4));
1986 		if ((np->n_flag & NMODIFIED) && (nvap->nva_size < np->n_size)) {
1987 			/* if we've modified, stick with larger size */
1988 			nvap->nva_size = np->n_size;
1989 		} else {
1990 			/*
1991 			 * n_size is protected by the data lock, so we need to
1992 			 * defer updating it until it's safe.  We save the new size
1993 			 * and set a flag and it'll get updated the next time we get/drop
1994 			 * the data lock or the next time we do a getattr.
1995 			 */
1996 			np->n_newsize = nvap->nva_size;
1997 			SET(np->n_flag, NUPDATESIZE);
1998 		}
1999 	}
2000 
2001 	bcopy((caddr_t)nvap, (caddr_t)nvaper, sizeof(struct nfs_vattr));
2002 	if (np->n_flag & NCHG) {
2003 		if (np->n_flag & NACC) {
2004 			nvaper->nva_timesec[NFSTIME_ACCESS] = np->n_atim.tv_sec;
2005 			nvaper->nva_timensec[NFSTIME_ACCESS] = np->n_atim.tv_nsec;
2006 		}
2007 		if (np->n_flag & NUPD) {
2008 			nvaper->nva_timesec[NFSTIME_MODIFY] = np->n_mtim.tv_sec;
2009 			nvaper->nva_timensec[NFSTIME_MODIFY] = np->n_mtim.tv_nsec;
2010 		}
2011 	}
2012 	if (nvap->nva_acl) {
2013 		if (flags & NGA_ACL) {
2014 			nvaper->nva_acl = kauth_acl_alloc(nvap->nva_acl->acl_entrycount);
2015 			if (!nvaper->nva_acl) {
2016 				return ENOMEM;
2017 			}
2018 			bcopy(nvap->nva_acl, nvaper->nva_acl, KAUTH_ACL_COPYSIZE(nvap->nva_acl));
2019 		} else {
2020 			nvaper->nva_acl = NULL;
2021 		}
2022 	}
2023 	return 0;
2024 }
2025 
2026 /*
2027  * When creating file system objects:
2028  * Don't bother setting UID if it's the same as the credential performing the create.
2029  * Don't bother setting GID if it's the same as the directory or credential.
2030  */
2031 void
nfs_avoid_needless_id_setting_on_create(nfsnode_t dnp,struct vnode_attr * vap,vfs_context_t ctx)2032 nfs_avoid_needless_id_setting_on_create(nfsnode_t dnp, struct vnode_attr *vap, vfs_context_t ctx)
2033 {
2034 	if (VATTR_IS_ACTIVE(vap, va_uid)) {
2035 		if (kauth_cred_getuid(vfs_context_ucred(ctx)) == vap->va_uid) {
2036 			VATTR_CLEAR_ACTIVE(vap, va_uid);
2037 			VATTR_CLEAR_ACTIVE(vap, va_uuuid);
2038 		}
2039 	}
2040 	if (VATTR_IS_ACTIVE(vap, va_gid)) {
2041 		if ((vap->va_gid == dnp->n_vattr.nva_gid) ||
2042 		    (kauth_cred_getgid(vfs_context_ucred(ctx)) == vap->va_gid)) {
2043 			VATTR_CLEAR_ACTIVE(vap, va_gid);
2044 			VATTR_CLEAR_ACTIVE(vap, va_guuid);
2045 		}
2046 	}
2047 }
2048 
2049 /*
2050  * Convert a universal address string to a sockaddr structure.
2051  *
2052  * Universal addresses can be in the following formats:
2053  *
2054  * d = decimal (IPv4)
2055  * x = hexadecimal (IPv6)
2056  * p = port (decimal)
2057  *
2058  * d.d.d.d
2059  * d.d.d.d.p.p
2060  * x:x:x:x:x:x:x:x
2061  * x:x:x:x:x:x:x:x.p.p
2062  * x:x:x:x:x:x:d.d.d.d
2063  * x:x:x:x:x:x:d.d.d.d.p.p
2064  *
2065  * IPv6 strings can also have a series of zeroes elided
2066  * IPv6 strings can also have a %scope suffix at the end (after any port)
2067  *
2068  * rules & exceptions:
2069  * - value before : is hex
2070  * - value before . is dec
2071  * - once . hit, all values are dec
2072  * - hex+port case means value before first dot is actually hex
2073  * - . is always preceded by digits except if last hex was double-colon
2074  *
2075  * scan, converting #s to bytes
2076  * first time a . is encountered, scan the rest to count them.
2077  * 2 dots = just port
2078  * 3 dots = just IPv4 no port
2079  * 5 dots = IPv4 and port
2080  */
2081 
2082 #define IS_DIGIT(C) \
2083 	(((C) >= '0') && ((C) <= '9'))
2084 
2085 #define IS_XDIGIT(C) \
2086 	(IS_DIGIT(C) || \
2087 	 (((C) >= 'A') && ((C) <= 'F')) || \
2088 	 (((C) >= 'a') && ((C) <= 'f')))
2089 
2090 int
nfs_uaddr2sockaddr(const char * uaddr,struct sockaddr * addr)2091 nfs_uaddr2sockaddr(const char *uaddr, struct sockaddr *addr)
2092 {
2093 	const char *p, *pd;     /* pointers to current character in scan */
2094 	const char *pnum;       /* pointer to current number to decode */
2095 	const char *pscope;     /* pointer to IPv6 scope ID */
2096 	uint8_t a[18];          /* octet array to store address bytes */
2097 	int i;                  /* index of next octet to decode */
2098 	int dci;                /* index of octet to insert double-colon zeroes */
2099 	int dcount, xdcount;    /* count of digits in current number */
2100 	int needmore;           /* set when we know we need more input (e.g. after colon, period) */
2101 	int dots;               /* # of dots */
2102 	int hex;                /* contains hex values */
2103 	unsigned long val;      /* decoded value */
2104 	int s;                  /* index used for sliding array to insert elided zeroes */
2105 
2106 	/* AF_LOCAL address are paths that start with '/' or are empty */
2107 	if (*uaddr == '/' || *uaddr == '\0') { /* AF_LOCAL address */
2108 		struct sockaddr_un *sun = (struct sockaddr_un *)addr;
2109 		sun->sun_family = AF_LOCAL;
2110 		sun->sun_len = sizeof(struct sockaddr_un);
2111 		strlcpy(sun->sun_path, uaddr, sizeof(sun->sun_path));
2112 
2113 		return 1;
2114 	}
2115 
2116 #define HEXVALUE        0
2117 #define DECIMALVALUE    1
2118 
2119 #define GET(TYPE) \
2120 	do { \
2121 	        if ((dcount <= 0) || (dcount > (((TYPE) == DECIMALVALUE) ? 3 : 4))) \
2122 	                return (0); \
2123 	        if (((TYPE) == DECIMALVALUE) && xdcount) \
2124 	                return (0); \
2125 	        val = strtoul(pnum, NULL, ((TYPE) == DECIMALVALUE) ? 10 : 16); \
2126 	        if (((TYPE) == DECIMALVALUE) && (val >= 256)) \
2127 	                return (0); \
2128 	/* check if there is room left in the array */ \
2129 	        if (i > (int)(sizeof(a) - (((TYPE) == HEXVALUE) ? 2 : 1) - ((dci != -1) ? 2 : 0))) \
2130 	                return (0); \
2131 	        if ((TYPE) == HEXVALUE) \
2132 	                a[i++] = ((val >> 8) & 0xff); \
2133 	        a[i++] = (val & 0xff); \
2134 	} while (0)
2135 
2136 	hex = 0;
2137 	dots = 0;
2138 	dci = -1;
2139 	i = dcount = xdcount = 0;
2140 	pnum = p = uaddr;
2141 	pscope = NULL;
2142 	needmore = 1;
2143 	if ((*p == ':') && (*++p != ':')) { /* if it starts with colon, gotta be a double */
2144 		return 0;
2145 	}
2146 
2147 	while (*p) {
2148 		if (IS_XDIGIT(*p)) {
2149 			dcount++;
2150 			if (!IS_DIGIT(*p)) {
2151 				xdcount++;
2152 			}
2153 			needmore = 0;
2154 			p++;
2155 		} else if (*p == '.') {
2156 			/* rest is decimal IPv4 dotted quad and/or port */
2157 			if (!dots) {
2158 				/* this is the first, so count them */
2159 				for (pd = p; *pd; pd++) {
2160 					if (*pd == '.') {
2161 						if (++dots > 5) {
2162 							return 0;
2163 						}
2164 					} else if (hex && (*pd == '%')) {
2165 						break;
2166 					} else if ((*pd < '0') || (*pd > '9')) {
2167 						return 0;
2168 					}
2169 				}
2170 				if ((dots != 2) && (dots != 3) && (dots != 5)) {
2171 					return 0;
2172 				}
2173 				if (hex && (dots == 2)) { /* hex+port */
2174 					if (!dcount && needmore) {
2175 						return 0;
2176 					}
2177 					if (dcount) { /* last hex may be elided zero */
2178 						GET(HEXVALUE);
2179 					}
2180 				} else {
2181 					GET(DECIMALVALUE);
2182 				}
2183 			} else {
2184 				GET(DECIMALVALUE);
2185 			}
2186 			dcount = xdcount = 0;
2187 			needmore = 1;
2188 			pnum = ++p;
2189 		} else if (*p == ':') {
2190 			hex = 1;
2191 			if (dots) {
2192 				return 0;
2193 			}
2194 			if (!dcount) { /* missing number, probably double colon */
2195 				if (dci >= 0) { /* can only have one double colon */
2196 					return 0;
2197 				}
2198 				dci = i;
2199 				needmore = 0;
2200 			} else {
2201 				GET(HEXVALUE);
2202 				dcount = xdcount = 0;
2203 				needmore = 1;
2204 			}
2205 			pnum = ++p;
2206 		} else if (*p == '%') { /* scope ID delimiter */
2207 			if (!hex) {
2208 				return 0;
2209 			}
2210 			p++;
2211 			pscope = p;
2212 			break;
2213 		} else { /* unexpected character */
2214 			return 0;
2215 		}
2216 	}
2217 	if (needmore && !dcount) {
2218 		return 0;
2219 	}
2220 	if (dcount) { /* decode trailing number */
2221 		GET(dots ? DECIMALVALUE : HEXVALUE);
2222 	}
2223 	if (dci >= 0) {  /* got a double-colon at i, need to insert a range of zeroes */
2224 		/* if we got a port, slide to end of array */
2225 		/* otherwise, slide to end of address (non-port) values */
2226 		int end = ((dots == 2) || (dots == 5)) ? sizeof(a) : (sizeof(a) - 2);
2227 		if (i % 2) { /* length of zero range must be multiple of 2 */
2228 			return 0;
2229 		}
2230 		if (i >= end) { /* no room? */
2231 			return 0;
2232 		}
2233 		/* slide (i-dci) numbers up from index dci */
2234 		for (s = 0; s < (i - dci); s++) {
2235 			a[end - 1 - s] = a[i - 1 - s];
2236 		}
2237 		/* zero (end-i) numbers at index dci */
2238 		for (s = 0; s < (end - i); s++) {
2239 			a[dci + s] = 0;
2240 		}
2241 		i = end;
2242 	}
2243 
2244 	/* copy out resulting socket address */
2245 	if (hex) {
2246 		struct sockaddr_in6 *sin6 = (struct sockaddr_in6*)addr;
2247 		if ((((dots == 0) || (dots == 3)) && (i != (sizeof(a) - 2)))) {
2248 			return 0;
2249 		}
2250 		if ((((dots == 2) || (dots == 5)) && (i != sizeof(a)))) {
2251 			return 0;
2252 		}
2253 		bzero(sin6, sizeof(struct sockaddr_in6));
2254 		sin6->sin6_len = sizeof(struct sockaddr_in6);
2255 		sin6->sin6_family = AF_INET6;
2256 		bcopy(a, &sin6->sin6_addr.s6_addr, sizeof(struct in6_addr));
2257 		if ((dots == 5) || (dots == 2)) {
2258 			sin6->sin6_port = htons((in_port_t)((a[16] << 8) | a[17]));
2259 		}
2260 		if (pscope) {
2261 			for (p = pscope; IS_DIGIT(*p); p++) {
2262 				;
2263 			}
2264 			if (*p && !IS_DIGIT(*p)) { /* name */
2265 				ifnet_t interface = NULL;
2266 				if (ifnet_find_by_name(pscope, &interface) == 0) {
2267 					sin6->sin6_scope_id = ifnet_index(interface);
2268 				}
2269 				if (interface) {
2270 					ifnet_release(interface);
2271 				}
2272 			} else { /* decimal number */
2273 				sin6->sin6_scope_id = (uint32_t)strtoul(pscope, NULL, 10);
2274 			}
2275 			/* XXX should we also embed scope id for linklocal? */
2276 		}
2277 	} else {
2278 		struct sockaddr_in *sin = (struct sockaddr_in*)addr;
2279 		if ((dots != 3) && (dots != 5)) {
2280 			return 0;
2281 		}
2282 		if ((dots == 3) && (i != 4)) {
2283 			return 0;
2284 		}
2285 		if ((dots == 5) && (i != 6)) {
2286 			return 0;
2287 		}
2288 		bzero(sin, sizeof(struct sockaddr_in));
2289 		sin->sin_len = sizeof(struct sockaddr_in);
2290 		sin->sin_family = AF_INET;
2291 		bcopy(a, &sin->sin_addr.s_addr, sizeof(struct in_addr));
2292 		if (dots == 5) {
2293 			sin->sin_port = htons((in_port_t)((a[4] << 8) | a[5]));
2294 		}
2295 	}
2296 	return 1;
2297 }
2298 
2299 /* Is a mount gone away? */
2300 int
nfs_mount_gone(struct nfsmount * nmp)2301 nfs_mount_gone(struct nfsmount *nmp)
2302 {
2303 	return !nmp || vfs_isforce(nmp->nm_mountp) || (nmp->nm_state & (NFSSTA_FORCE | NFSSTA_DEAD));
2304 }
2305 
2306 /*
2307  * Return some of the more significant mount options
2308  * as a string, e.g. "'ro,hard,intr,tcp,vers=3,sec=krb5,deadtimeout=0'
2309  */
2310 int
nfs_mountopts(struct nfsmount * nmp,char * buf,int buflen)2311 nfs_mountopts(struct nfsmount *nmp, char *buf, int buflen)
2312 {
2313 	int c;
2314 
2315 	c = snprintf(buf, buflen, "%s,%s,%s,%s,vers=%d,sec=%s,%sdeadtimeout=%d",
2316 	    (vfs_flags(nmp->nm_mountp) & MNT_RDONLY) ? "ro" : "rw",
2317 	    NMFLAG(nmp, SOFT) ? "soft" : "hard",
2318 	    NMFLAG(nmp, INTR) ? "intr" : "nointr",
2319 	    nmp->nm_sotype == SOCK_STREAM ? "tcp" : "udp",
2320 	    nmp->nm_vers,
2321 	    nmp->nm_auth == RPCAUTH_KRB5  ? "krb5" :
2322 	    nmp->nm_auth == RPCAUTH_KRB5I ? "krb5i" :
2323 	    nmp->nm_auth == RPCAUTH_KRB5P ? "krb5p" :
2324 	    nmp->nm_auth == RPCAUTH_SYS   ? "sys" : "none",
2325 	    nmp->nm_lockmode == NFS_LOCK_MODE_ENABLED ?  "locks," :
2326 	    nmp->nm_lockmode == NFS_LOCK_MODE_DISABLED ? "nolocks," :
2327 	    nmp->nm_lockmode == NFS_LOCK_MODE_LOCAL ? "locallocks," : "",
2328 	    nmp->nm_deadtimeout);
2329 
2330 	return c > buflen ? ENOMEM : 0;
2331 }
2332 
2333 #endif /* CONFIG_NFS_CLIENT */
2334 
2335 /*
2336  * Schedule a callout thread to run an NFS timer function
2337  * interval milliseconds in the future.
2338  */
2339 void
nfs_interval_timer_start(thread_call_t call,time_t interval)2340 nfs_interval_timer_start(thread_call_t call, time_t interval)
2341 {
2342 	uint64_t deadline;
2343 
2344 	clock_interval_to_deadline((int)interval, 1000 * 1000, &deadline);
2345 	thread_call_enter_delayed(call, deadline);
2346 }
2347 
2348 
2349 #if CONFIG_NFS_SERVER
2350 
2351 int nfsrv_cmp_secflavs(struct nfs_sec *, struct nfs_sec *);
2352 int nfsrv_hang_addrlist(struct nfs_export *, struct user_nfs_export_args *);
2353 int nfsrv_free_netopt(struct radix_node *, void *);
2354 int nfsrv_free_addrlist(struct nfs_export *, struct user_nfs_export_args *);
2355 struct nfs_export_options *nfsrv_export_lookup(struct nfs_export *, mbuf_t);
2356 struct nfs_export *nfsrv_fhtoexport(struct nfs_filehandle *);
2357 struct nfs_user_stat_node *nfsrv_get_user_stat_node(struct nfs_active_user_list *, struct sockaddr *, uid_t);
2358 void nfsrv_init_user_list(struct nfs_active_user_list *);
2359 void nfsrv_free_user_list(struct nfs_active_user_list *);
2360 
2361 /*
2362  * add NFSv3 WCC data to an mbuf chain
2363  */
2364 int
nfsm_chain_add_wcc_data_f(struct nfsrv_descript * nd,struct nfsm_chain * nmc,int preattrerr,struct vnode_attr * prevap,int postattrerr,struct vnode_attr * postvap)2365 nfsm_chain_add_wcc_data_f(
2366 	struct nfsrv_descript *nd,
2367 	struct nfsm_chain *nmc,
2368 	int preattrerr,
2369 	struct vnode_attr *prevap,
2370 	int postattrerr,
2371 	struct vnode_attr *postvap)
2372 {
2373 	int error = 0;
2374 
2375 	if (preattrerr) {
2376 		nfsm_chain_add_32(error, nmc, FALSE);
2377 	} else {
2378 		nfsm_chain_add_32(error, nmc, TRUE);
2379 		nfsm_chain_add_64(error, nmc, prevap->va_data_size);
2380 		nfsm_chain_add_time(error, nmc, NFS_VER3, &prevap->va_modify_time);
2381 		nfsm_chain_add_time(error, nmc, NFS_VER3, &prevap->va_change_time);
2382 	}
2383 	nfsm_chain_add_postop_attr(error, nd, nmc, postattrerr, postvap);
2384 
2385 	return error;
2386 }
2387 
2388 /*
2389  * Extract a lookup path from the given mbufs and store it in
2390  * a newly allocated buffer saved in the given nameidata structure.
2391  */
2392 int
nfsm_chain_get_path_namei(struct nfsm_chain * nmc,uint32_t len,struct nameidata * nip)2393 nfsm_chain_get_path_namei(
2394 	struct nfsm_chain *nmc,
2395 	uint32_t len,
2396 	struct nameidata *nip)
2397 {
2398 	struct componentname *cnp = &nip->ni_cnd;
2399 	int error = 0;
2400 	char *cp;
2401 
2402 	if (len > (MAXPATHLEN - 1)) {
2403 		return ENAMETOOLONG;
2404 	}
2405 
2406 	/*
2407 	 * Get a buffer for the name to be translated, and copy the
2408 	 * name into the buffer.
2409 	 */
2410 	cnp->cn_pnbuf = zalloc(ZV_NAMEI);
2411 	cnp->cn_pnlen = MAXPATHLEN;
2412 	cnp->cn_flags |= HASBUF;
2413 
2414 	/* Copy the name from the mbuf list to the string */
2415 	cp = cnp->cn_pnbuf;
2416 	nfsm_chain_get_opaque(error, nmc, len, cp);
2417 	if (error) {
2418 		goto out;
2419 	}
2420 	cnp->cn_pnbuf[len] = '\0';
2421 
2422 	/* sanity check the string */
2423 	if ((strlen(cp) != len) || strchr(cp, '/')) {
2424 		error = EACCES;
2425 	}
2426 out:
2427 	if (error) {
2428 		if (cnp->cn_pnbuf) {
2429 			NFS_ZFREE(ZV_NAMEI, cnp->cn_pnbuf);
2430 		}
2431 		cnp->cn_flags &= ~HASBUF;
2432 	} else {
2433 		nip->ni_pathlen = len;
2434 	}
2435 	return error;
2436 }
2437 
2438 /*
2439  * Set up nameidata for a lookup() call and do it.
2440  */
2441 int
nfsrv_namei(struct nfsrv_descript * nd,vfs_context_t ctx,struct nameidata * nip,struct nfs_filehandle * nfhp,vnode_t * retdirp,struct nfs_export ** nxp,struct nfs_export_options ** nxop)2442 nfsrv_namei(
2443 	struct nfsrv_descript *nd,
2444 	vfs_context_t ctx,
2445 	struct nameidata *nip,
2446 	struct nfs_filehandle *nfhp,
2447 	vnode_t *retdirp,
2448 	struct nfs_export **nxp,
2449 	struct nfs_export_options **nxop)
2450 {
2451 	vnode_t dp;
2452 	int error;
2453 	struct componentname *cnp = &nip->ni_cnd;
2454 	uint32_t cnflags;
2455 	char *tmppn;
2456 
2457 	*retdirp = NULL;
2458 
2459 	/*
2460 	 * Extract and set starting directory.
2461 	 */
2462 	error = nfsrv_fhtovp(nfhp, nd, &dp, nxp, nxop);
2463 	if (error) {
2464 		goto out;
2465 	}
2466 	error = nfsrv_credcheck(nd, ctx, *nxp, *nxop);
2467 	if (error || (vnode_vtype(dp) != VDIR)) {
2468 		vnode_put(dp);
2469 		error = ENOTDIR;
2470 		goto out;
2471 	}
2472 	*retdirp = dp;
2473 
2474 	nip->ni_cnd.cn_context = ctx;
2475 
2476 	if (*nxop && ((*nxop)->nxo_flags & NX_READONLY)) {
2477 		cnp->cn_flags |= RDONLY;
2478 	}
2479 
2480 	cnp->cn_flags |= NOCROSSMOUNT;
2481 	cnp->cn_nameptr = cnp->cn_pnbuf;
2482 	nip->ni_usedvp = nip->ni_startdir = dp;
2483 	nip->ni_rootdir = rootvnode;
2484 
2485 	/*
2486 	 * And call lookup() to do the real work
2487 	 */
2488 	cnflags = nip->ni_cnd.cn_flags; /* store in case we have to restore */
2489 	while ((error = lookup(nip)) == ERECYCLE) {
2490 		nip->ni_cnd.cn_flags = cnflags;
2491 		cnp->cn_nameptr = cnp->cn_pnbuf;
2492 		nip->ni_usedvp = nip->ni_dvp = nip->ni_startdir = dp;
2493 	}
2494 	if (error) {
2495 		goto out;
2496 	}
2497 
2498 	/* Check for encountering a symbolic link */
2499 	if (cnp->cn_flags & ISSYMLINK) {
2500 		if (cnp->cn_flags & (LOCKPARENT | WANTPARENT)) {
2501 			vnode_put(nip->ni_dvp);
2502 		}
2503 		if (nip->ni_vp) {
2504 			vnode_put(nip->ni_vp);
2505 			nip->ni_vp = NULL;
2506 		}
2507 		error = EINVAL;
2508 	}
2509 out:
2510 	if (error) {
2511 		tmppn = cnp->cn_pnbuf;
2512 		cnp->cn_pnbuf = NULL;
2513 		cnp->cn_flags &= ~HASBUF;
2514 		NFS_ZFREE(ZV_NAMEI, tmppn);
2515 	}
2516 	return error;
2517 }
2518 
2519 /*
2520  * A fiddled version of m_adj() that ensures null fill to a 4-byte
2521  * boundary and only trims off the back end
2522  */
2523 void
nfsm_adj(mbuf_t mp,int len,int nul)2524 nfsm_adj(mbuf_t mp, int len, int nul)
2525 {
2526 	mbuf_t m, mnext;
2527 	int count, i;
2528 	long mlen;
2529 	char *cp;
2530 
2531 	/*
2532 	 * Trim from tail.  Scan the mbuf chain,
2533 	 * calculating its length and finding the last mbuf.
2534 	 * If the adjustment only affects this mbuf, then just
2535 	 * adjust and return.  Otherwise, rescan and truncate
2536 	 * after the remaining size.
2537 	 */
2538 	count = 0;
2539 	m = mp;
2540 	for (;;) {
2541 		mlen = mbuf_len(m);
2542 		count += mlen;
2543 		mnext = mbuf_next(m);
2544 		if (mnext == NULL) {
2545 			break;
2546 		}
2547 		m = mnext;
2548 	}
2549 	if (mlen > len) {
2550 		mlen -= len;
2551 		mbuf_setlen(m, mlen);
2552 		if (nul > 0) {
2553 			cp = (caddr_t)mbuf_data(m) + mlen - nul;
2554 			for (i = 0; i < nul; i++) {
2555 				*cp++ = '\0';
2556 			}
2557 		}
2558 		return;
2559 	}
2560 	count -= len;
2561 	if (count < 0) {
2562 		count = 0;
2563 	}
2564 	/*
2565 	 * Correct length for chain is "count".
2566 	 * Find the mbuf with last data, adjust its length,
2567 	 * and toss data from remaining mbufs on chain.
2568 	 */
2569 	for (m = mp; m; m = mbuf_next(m)) {
2570 		mlen = mbuf_len(m);
2571 		if (mlen >= count) {
2572 			mlen = count;
2573 			mbuf_setlen(m, count);
2574 			if (nul > 0) {
2575 				cp = (caddr_t)mbuf_data(m) + mlen - nul;
2576 				for (i = 0; i < nul; i++) {
2577 					*cp++ = '\0';
2578 				}
2579 			}
2580 			break;
2581 		}
2582 		count -= mlen;
2583 	}
2584 	for (m = mbuf_next(m); m; m = mbuf_next(m)) {
2585 		mbuf_setlen(m, 0);
2586 	}
2587 }
2588 
2589 /*
2590  * Trim the header out of the mbuf list and trim off any trailing
2591  * junk so that the mbuf list has only the write data.
2592  */
2593 int
nfsm_chain_trim_data(struct nfsm_chain * nmc,int len,int * mlen)2594 nfsm_chain_trim_data(struct nfsm_chain *nmc, int len, int *mlen)
2595 {
2596 	int cnt = 0;
2597 	long dlen, adjust;
2598 	caddr_t data;
2599 	mbuf_t m;
2600 
2601 	if (mlen) {
2602 		*mlen = 0;
2603 	}
2604 
2605 	/* trim header */
2606 	for (m = nmc->nmc_mhead; m && (m != nmc->nmc_mcur); m = mbuf_next(m)) {
2607 		mbuf_setlen(m, 0);
2608 	}
2609 	if (!m) {
2610 		return EIO;
2611 	}
2612 
2613 	/* trim current mbuf */
2614 	data = mbuf_data(m);
2615 	dlen = mbuf_len(m);
2616 	adjust = nmc->nmc_ptr - data;
2617 	dlen -= adjust;
2618 	if ((dlen > 0) && (adjust > 0)) {
2619 		if (mbuf_setdata(m, nmc->nmc_ptr, dlen)) {
2620 			return EIO;
2621 		}
2622 	} else {
2623 		mbuf_setlen(m, dlen);
2624 	}
2625 
2626 	/* skip next len bytes  */
2627 	for (; m && (cnt < len); m = mbuf_next(m)) {
2628 		dlen = mbuf_len(m);
2629 		cnt += dlen;
2630 		if (cnt > len) {
2631 			/* truncate to end of data */
2632 			mbuf_setlen(m, dlen - (cnt - len));
2633 			if (m == nmc->nmc_mcur) {
2634 				nmc->nmc_left -= (cnt - len);
2635 			}
2636 			cnt = len;
2637 		}
2638 	}
2639 	if (mlen) {
2640 		*mlen = cnt;
2641 	}
2642 
2643 	/* trim any trailing data */
2644 	if (m == nmc->nmc_mcur) {
2645 		nmc->nmc_left = 0;
2646 	}
2647 	for (; m; m = mbuf_next(m)) {
2648 		mbuf_setlen(m, 0);
2649 	}
2650 
2651 	return 0;
2652 }
2653 
2654 int
nfsm_chain_add_fattr(struct nfsrv_descript * nd,struct nfsm_chain * nmc,struct vnode_attr * vap)2655 nfsm_chain_add_fattr(
2656 	struct nfsrv_descript *nd,
2657 	struct nfsm_chain *nmc,
2658 	struct vnode_attr *vap)
2659 {
2660 	int error = 0;
2661 
2662 	// XXX Should we assert here that all fields are supported?
2663 
2664 	nfsm_chain_add_32(error, nmc, vtonfs_type(vap->va_type, nd->nd_vers));
2665 	if (nd->nd_vers == NFS_VER3) {
2666 		nfsm_chain_add_32(error, nmc, vap->va_mode & 07777);
2667 	} else {
2668 		nfsm_chain_add_32(error, nmc, vtonfsv2_mode(vap->va_type, vap->va_mode));
2669 	}
2670 	nfsm_chain_add_32(error, nmc, vap->va_nlink);
2671 	nfsm_chain_add_32(error, nmc, vap->va_uid);
2672 	nfsm_chain_add_32(error, nmc, vap->va_gid);
2673 	if (nd->nd_vers == NFS_VER3) {
2674 		nfsm_chain_add_64(error, nmc, vap->va_data_size);
2675 		nfsm_chain_add_64(error, nmc, vap->va_data_alloc);
2676 		nfsm_chain_add_32(error, nmc, major(vap->va_rdev));
2677 		nfsm_chain_add_32(error, nmc, minor(vap->va_rdev));
2678 		nfsm_chain_add_64(error, nmc, vap->va_fsid);
2679 		nfsm_chain_add_64(error, nmc, vap->va_fileid);
2680 	} else {
2681 		nfsm_chain_add_32(error, nmc, vap->va_data_size);
2682 		nfsm_chain_add_32(error, nmc, NFS_FABLKSIZE);
2683 		if (vap->va_type == VFIFO) {
2684 			nfsm_chain_add_32(error, nmc, 0xffffffff);
2685 		} else {
2686 			nfsm_chain_add_32(error, nmc, vap->va_rdev);
2687 		}
2688 		nfsm_chain_add_32(error, nmc, vap->va_data_alloc / NFS_FABLKSIZE);
2689 		nfsm_chain_add_32(error, nmc, vap->va_fsid);
2690 		nfsm_chain_add_32(error, nmc, vap->va_fileid);
2691 	}
2692 	nfsm_chain_add_time(error, nmc, nd->nd_vers, &vap->va_access_time);
2693 	nfsm_chain_add_time(error, nmc, nd->nd_vers, &vap->va_modify_time);
2694 	nfsm_chain_add_time(error, nmc, nd->nd_vers, &vap->va_change_time);
2695 
2696 	return error;
2697 }
2698 
2699 int
nfsm_chain_get_sattr(struct nfsrv_descript * nd,struct nfsm_chain * nmc,struct vnode_attr * vap)2700 nfsm_chain_get_sattr(
2701 	struct nfsrv_descript *nd,
2702 	struct nfsm_chain *nmc,
2703 	struct vnode_attr *vap)
2704 {
2705 	int error = 0;
2706 	uint32_t val = 0;
2707 	uint64_t val64 = 0;
2708 	struct timespec now;
2709 
2710 	if (nd->nd_vers == NFS_VER2) {
2711 		/*
2712 		 * There is/was a bug in the Sun client that puts 0xffff in the mode
2713 		 * field of sattr when it should put in 0xffffffff.  The u_short
2714 		 * doesn't sign extend.  So check the low order 2 bytes for 0xffff.
2715 		 */
2716 		nfsm_chain_get_32(error, nmc, val);
2717 		if ((val & 0xffff) != 0xffff) {
2718 			VATTR_SET(vap, va_mode, val & 07777);
2719 			/* save the "type" bits for NFSv2 create */
2720 			VATTR_SET(vap, va_type, IFTOVT(val));
2721 			VATTR_CLEAR_ACTIVE(vap, va_type);
2722 		}
2723 		nfsm_chain_get_32(error, nmc, val);
2724 		if (val != (uint32_t)-1) {
2725 			VATTR_SET(vap, va_uid, val);
2726 		}
2727 		nfsm_chain_get_32(error, nmc, val);
2728 		if (val != (uint32_t)-1) {
2729 			VATTR_SET(vap, va_gid, val);
2730 		}
2731 		/* save the "size" bits for NFSv2 create (even if they appear unset) */
2732 		nfsm_chain_get_32(error, nmc, val);
2733 		VATTR_SET(vap, va_data_size, val);
2734 		if (val == (uint32_t)-1) {
2735 			VATTR_CLEAR_ACTIVE(vap, va_data_size);
2736 		}
2737 		nfsm_chain_get_time(error, nmc, NFS_VER2,
2738 		    vap->va_access_time.tv_sec,
2739 		    vap->va_access_time.tv_nsec);
2740 		if (vap->va_access_time.tv_sec != -1) {
2741 			VATTR_SET_ACTIVE(vap, va_access_time);
2742 		}
2743 		nfsm_chain_get_time(error, nmc, NFS_VER2,
2744 		    vap->va_modify_time.tv_sec,
2745 		    vap->va_modify_time.tv_nsec);
2746 		if (vap->va_modify_time.tv_sec != -1) {
2747 			VATTR_SET_ACTIVE(vap, va_modify_time);
2748 		}
2749 		return error;
2750 	}
2751 
2752 	/* NFSv3 */
2753 	nfsm_chain_get_32(error, nmc, val);
2754 	if (val) {
2755 		nfsm_chain_get_32(error, nmc, val);
2756 		VATTR_SET(vap, va_mode, val & 07777);
2757 	}
2758 	nfsm_chain_get_32(error, nmc, val);
2759 	if (val) {
2760 		nfsm_chain_get_32(error, nmc, val);
2761 		VATTR_SET(vap, va_uid, val);
2762 	}
2763 	nfsm_chain_get_32(error, nmc, val);
2764 	if (val) {
2765 		nfsm_chain_get_32(error, nmc, val);
2766 		VATTR_SET(vap, va_gid, val);
2767 	}
2768 	nfsm_chain_get_32(error, nmc, val);
2769 	if (val) {
2770 		nfsm_chain_get_64(error, nmc, val64);
2771 		VATTR_SET(vap, va_data_size, val64);
2772 	}
2773 	nanotime(&now);
2774 	nfsm_chain_get_32(error, nmc, val);
2775 	switch (val) {
2776 	case NFS_TIME_SET_TO_CLIENT:
2777 		nfsm_chain_get_time(error, nmc, nd->nd_vers,
2778 		    vap->va_access_time.tv_sec,
2779 		    vap->va_access_time.tv_nsec);
2780 		VATTR_SET_ACTIVE(vap, va_access_time);
2781 		vap->va_vaflags &= ~VA_UTIMES_NULL;
2782 		break;
2783 	case NFS_TIME_SET_TO_SERVER:
2784 		VATTR_SET(vap, va_access_time, now);
2785 		vap->va_vaflags |= VA_UTIMES_NULL;
2786 		break;
2787 	}
2788 	nfsm_chain_get_32(error, nmc, val);
2789 	switch (val) {
2790 	case NFS_TIME_SET_TO_CLIENT:
2791 		nfsm_chain_get_time(error, nmc, nd->nd_vers,
2792 		    vap->va_modify_time.tv_sec,
2793 		    vap->va_modify_time.tv_nsec);
2794 		VATTR_SET_ACTIVE(vap, va_modify_time);
2795 		vap->va_vaflags &= ~VA_UTIMES_NULL;
2796 		break;
2797 	case NFS_TIME_SET_TO_SERVER:
2798 		VATTR_SET(vap, va_modify_time, now);
2799 		if (!VATTR_IS_ACTIVE(vap, va_access_time)) {
2800 			vap->va_vaflags |= VA_UTIMES_NULL;
2801 		}
2802 		break;
2803 	}
2804 
2805 	return error;
2806 }
2807 
2808 /*
2809  * Compare two security flavor structs
2810  */
2811 int
nfsrv_cmp_secflavs(struct nfs_sec * sf1,struct nfs_sec * sf2)2812 nfsrv_cmp_secflavs(struct nfs_sec *sf1, struct nfs_sec *sf2)
2813 {
2814 	int i;
2815 
2816 	if (sf1->count != sf2->count) {
2817 		return 1;
2818 	}
2819 	for (i = 0; i < sf1->count; i++) {
2820 		if (sf1->flavors[i] != sf2->flavors[i]) {
2821 			return 1;
2822 		}
2823 	}
2824 	return 0;
2825 }
2826 
2827 /*
2828  * Build hash lists of net addresses and hang them off the NFS export.
2829  * Called by nfsrv_export() to set up the lists of export addresses.
2830  */
2831 int
nfsrv_hang_addrlist(struct nfs_export * nx,struct user_nfs_export_args * unxa)2832 nfsrv_hang_addrlist(struct nfs_export *nx, struct user_nfs_export_args *unxa)
2833 {
2834 	struct nfs_export_net_args nxna;
2835 	struct nfs_netopt *no, *rn_no;
2836 	struct radix_node_head *rnh;
2837 	struct radix_node *rn;
2838 	struct sockaddr *saddr, *smask;
2839 	struct domain *dom;
2840 	size_t i, ss_minsize;
2841 	int error;
2842 	unsigned int net;
2843 	user_addr_t uaddr;
2844 	kauth_cred_t cred;
2845 
2846 	uaddr = unxa->nxa_nets;
2847 	ss_minsize = sizeof(((struct sockaddr_storage *)0)->ss_len) + sizeof(((struct sockaddr_storage *)0)->ss_family);
2848 	for (net = 0; net < unxa->nxa_netcount; net++, uaddr += sizeof(nxna)) {
2849 		error = copyin(uaddr, &nxna, sizeof(nxna));
2850 		if (error) {
2851 			return error;
2852 		}
2853 
2854 		if (nxna.nxna_addr.ss_len > sizeof(struct sockaddr_storage) ||
2855 		    (nxna.nxna_addr.ss_len != 0 && nxna.nxna_addr.ss_len < ss_minsize) ||
2856 		    nxna.nxna_mask.ss_len > sizeof(struct sockaddr_storage) ||
2857 		    (nxna.nxna_mask.ss_len != 0 && nxna.nxna_mask.ss_len < ss_minsize) ||
2858 		    nxna.nxna_addr.ss_family > AF_MAX ||
2859 		    nxna.nxna_mask.ss_family > AF_MAX) {
2860 			return EINVAL;
2861 		}
2862 
2863 		if (nxna.nxna_flags & (NX_MAPROOT | NX_MAPALL)) {
2864 			struct posix_cred temp_pcred;
2865 			bzero(&temp_pcred, sizeof(temp_pcred));
2866 			temp_pcred.cr_uid = nxna.nxna_cred.cr_uid;
2867 			temp_pcred.cr_ngroups = nxna.nxna_cred.cr_ngroups;
2868 			for (i = 0; i < (size_t)nxna.nxna_cred.cr_ngroups && i < NGROUPS; i++) {
2869 				temp_pcred.cr_groups[i] = nxna.nxna_cred.cr_groups[i];
2870 			}
2871 			cred = posix_cred_create(&temp_pcred);
2872 			if (!IS_VALID_CRED(cred)) {
2873 				return ENOMEM;
2874 			}
2875 		} else {
2876 			cred = NOCRED;
2877 		}
2878 
2879 		if (nxna.nxna_addr.ss_len == 0) {
2880 			/* No address means this is a default/world export */
2881 			if (nx->nx_flags & NX_DEFAULTEXPORT) {
2882 				if (IS_VALID_CRED(cred)) {
2883 					kauth_cred_unref(&cred);
2884 				}
2885 				return EEXIST;
2886 			}
2887 			nx->nx_flags |= NX_DEFAULTEXPORT;
2888 			nx->nx_defopt.nxo_flags = nxna.nxna_flags;
2889 			nx->nx_defopt.nxo_cred = cred;
2890 			bcopy(&nxna.nxna_sec, &nx->nx_defopt.nxo_sec, sizeof(struct nfs_sec));
2891 			nx->nx_expcnt++;
2892 			continue;
2893 		}
2894 
2895 		no = kalloc_type(struct nfs_netopt, Z_WAITOK | Z_ZERO | Z_NOFAIL);
2896 		no->no_opt.nxo_flags = nxna.nxna_flags;
2897 		no->no_opt.nxo_cred = cred;
2898 		bcopy(&nxna.nxna_sec, &no->no_opt.nxo_sec, sizeof(struct nfs_sec));
2899 
2900 		if (nxna.nxna_addr.ss_len) {
2901 			no->no_addr = kalloc_data(nxna.nxna_addr.ss_len, M_WAITOK);
2902 			bcopy(&nxna.nxna_addr, no->no_addr, nxna.nxna_addr.ss_len);
2903 		}
2904 		saddr = no->no_addr;
2905 
2906 		if (nxna.nxna_mask.ss_len) {
2907 			no->no_mask = kalloc_data(nxna.nxna_mask.ss_len, M_WAITOK);
2908 			bcopy(&nxna.nxna_mask, no->no_mask, nxna.nxna_mask.ss_len);
2909 		}
2910 		smask = no->no_mask;
2911 
2912 		sa_family_t family = saddr->sa_family;
2913 		if ((rnh = nx->nx_rtable[family]) == 0) {
2914 			/*
2915 			 * Seems silly to initialize every AF when most are not
2916 			 * used, do so on demand here
2917 			 */
2918 			TAILQ_FOREACH(dom, &domains, dom_entry) {
2919 				if (dom->dom_family == family && dom->dom_rtattach) {
2920 					dom->dom_rtattach((void **)&nx->nx_rtable[family],
2921 					    dom->dom_rtoffset);
2922 					break;
2923 				}
2924 			}
2925 			if ((rnh = nx->nx_rtable[family]) == 0) {
2926 				if (IS_VALID_CRED(cred)) {
2927 					kauth_cred_unref(&cred);
2928 				}
2929 				nfs_netopt_free(no);
2930 				return ENOBUFS;
2931 			}
2932 		}
2933 		rn = (*rnh->rnh_addaddr)((caddr_t)saddr, (caddr_t)smask, rnh, no->no_rnodes);
2934 		if (rn == 0) {
2935 			/*
2936 			 * One of the reasons that rnh_addaddr may fail is that
2937 			 * the entry already exists. To check for this case, we
2938 			 * look up the entry to see if it is there. If so, we
2939 			 * do not need to make a new entry but do continue.
2940 			 *
2941 			 * XXX should this be rnh_lookup() instead?
2942 			 */
2943 			int matched = 0;
2944 			rn = (*rnh->rnh_matchaddr)((caddr_t)saddr, rnh);
2945 			rn_no = (struct nfs_netopt *)rn;
2946 			if (rn != 0 && (rn->rn_flags & RNF_ROOT) == 0 &&
2947 			    (rn_no->no_opt.nxo_flags == nxna.nxna_flags) &&
2948 			    (!nfsrv_cmp_secflavs(&rn_no->no_opt.nxo_sec, &nxna.nxna_sec))) {
2949 				kauth_cred_t cred2 = rn_no->no_opt.nxo_cred;
2950 				if (cred == cred2) {
2951 					/* creds are same (or both NULL) */
2952 					matched = 1;
2953 				} else if (cred && cred2 && (kauth_cred_getuid(cred) == kauth_cred_getuid(cred2))) {
2954 					/*
2955 					 * Now compare the effective and
2956 					 * supplementary groups...
2957 					 *
2958 					 * Note: This comparison, as written,
2959 					 * does not correctly indicate that
2960 					 * the groups are equivalent, since
2961 					 * other than the first supplementary
2962 					 * group, which is also the effective
2963 					 * group, order on the remaining groups
2964 					 * doesn't matter, and this is an
2965 					 * ordered compare.
2966 					 */
2967 					gid_t groups[NGROUPS];
2968 					gid_t groups2[NGROUPS];
2969 					size_t groupcount = NGROUPS;
2970 					size_t group2count = NGROUPS;
2971 
2972 					if (!kauth_cred_getgroups(cred, groups, &groupcount) &&
2973 					    !kauth_cred_getgroups(cred2, groups2, &group2count) &&
2974 					    groupcount == group2count) {
2975 						for (i = 0; i < group2count; i++) {
2976 							if (groups[i] != groups2[i]) {
2977 								break;
2978 							}
2979 						}
2980 						if (i >= group2count || i >= NGROUPS) {
2981 							matched = 1;
2982 						}
2983 					}
2984 				}
2985 			}
2986 			if (IS_VALID_CRED(cred)) {
2987 				kauth_cred_unref(&cred);
2988 			}
2989 			nfs_netopt_free(no);
2990 			if (matched) {
2991 				continue;
2992 			}
2993 			return EPERM;
2994 		}
2995 		nx->nx_expcnt++;
2996 	}
2997 
2998 	return 0;
2999 }
3000 
3001 /*
3002  * In order to properly track an export's netopt count, we need to pass
3003  * an additional argument to nfsrv_free_netopt() so that it can decrement
3004  * the export's netopt count.
3005  */
3006 struct nfsrv_free_netopt_arg {
3007 	uint32_t *cnt;
3008 	struct radix_node_head *rnh;
3009 };
3010 
3011 int
nfsrv_free_netopt(struct radix_node * rn,void * w)3012 nfsrv_free_netopt(struct radix_node *rn, void *w)
3013 {
3014 	struct nfsrv_free_netopt_arg *fna = (struct nfsrv_free_netopt_arg *)w;
3015 	struct radix_node_head *rnh = fna->rnh;
3016 	uint32_t *cnt = fna->cnt;
3017 	struct nfs_netopt *nno = (struct nfs_netopt *)rn;
3018 
3019 	(*rnh->rnh_deladdr)(rn->rn_key, rn->rn_mask, rnh);
3020 	if (IS_VALID_CRED(nno->no_opt.nxo_cred)) {
3021 		kauth_cred_unref(&nno->no_opt.nxo_cred);
3022 	}
3023 	nfs_netopt_free(nno);
3024 	*cnt -= 1;
3025 	return 0;
3026 }
3027 
3028 /*
3029  * Free the net address hash lists that are hanging off the mount points.
3030  */
3031 int
nfsrv_free_addrlist(struct nfs_export * nx,struct user_nfs_export_args * unxa)3032 nfsrv_free_addrlist(struct nfs_export *nx, struct user_nfs_export_args *unxa)
3033 {
3034 	struct nfs_export_net_args nxna;
3035 	struct radix_node_head *rnh;
3036 	struct radix_node *rn;
3037 	struct nfsrv_free_netopt_arg fna;
3038 	struct nfs_netopt *nno;
3039 	size_t ss_minsize;
3040 	user_addr_t uaddr;
3041 	unsigned int net;
3042 	int i, error;
3043 
3044 	if (!unxa || !unxa->nxa_netcount) {
3045 		/* delete everything */
3046 		for (i = 0; i <= AF_MAX; i++) {
3047 			if ((rnh = nx->nx_rtable[i])) {
3048 				fna.rnh = rnh;
3049 				fna.cnt = &nx->nx_expcnt;
3050 				(*rnh->rnh_walktree)(rnh, nfsrv_free_netopt, (caddr_t)&fna);
3051 				zfree(radix_node_head_zone, rnh);
3052 				nx->nx_rtable[i] = 0;
3053 			}
3054 		}
3055 		return 0;
3056 	}
3057 
3058 	/* delete only the exports specified */
3059 	uaddr = unxa->nxa_nets;
3060 	ss_minsize = sizeof(((struct sockaddr_storage *)0)->ss_len) + sizeof(((struct sockaddr_storage *)0)->ss_family);
3061 	for (net = 0; net < unxa->nxa_netcount; net++, uaddr += sizeof(nxna)) {
3062 		error = copyin(uaddr, &nxna, sizeof(nxna));
3063 		if (error) {
3064 			return error;
3065 		}
3066 
3067 		if (nxna.nxna_addr.ss_len == 0) {
3068 			/* No address means this is a default/world export */
3069 			if (nx->nx_flags & NX_DEFAULTEXPORT) {
3070 				nx->nx_flags &= ~NX_DEFAULTEXPORT;
3071 				if (IS_VALID_CRED(nx->nx_defopt.nxo_cred)) {
3072 					kauth_cred_unref(&nx->nx_defopt.nxo_cred);
3073 				}
3074 				nx->nx_expcnt--;
3075 			}
3076 			continue;
3077 		}
3078 
3079 		if (nxna.nxna_addr.ss_len > sizeof(struct sockaddr_storage) ||
3080 		    (nxna.nxna_addr.ss_len != 0 && nxna.nxna_addr.ss_len < ss_minsize) ||
3081 		    nxna.nxna_addr.ss_family > AF_MAX) {
3082 			printf("nfsrv_free_addrlist: invalid socket address (%u)\n", net);
3083 			continue;
3084 		}
3085 
3086 		if (nxna.nxna_mask.ss_len > sizeof(struct sockaddr_storage) ||
3087 		    (nxna.nxna_mask.ss_len != 0 && nxna.nxna_mask.ss_len < ss_minsize) ||
3088 		    nxna.nxna_mask.ss_family > AF_MAX) {
3089 			printf("nfsrv_free_addrlist: invalid socket mask (%u)\n", net);
3090 			continue;
3091 		}
3092 
3093 		if ((rnh = nx->nx_rtable[nxna.nxna_addr.ss_family]) == 0) {
3094 			/* AF not initialized? */
3095 			if (!(unxa->nxa_flags & NXA_ADD)) {
3096 				printf("nfsrv_free_addrlist: address not found (0)\n");
3097 			}
3098 			continue;
3099 		}
3100 
3101 		rn = (*rnh->rnh_lookup)(&nxna.nxna_addr,
3102 		    nxna.nxna_mask.ss_len ? &nxna.nxna_mask : NULL, rnh);
3103 		if (!rn || (rn->rn_flags & RNF_ROOT)) {
3104 			if (!(unxa->nxa_flags & NXA_ADD)) {
3105 				printf("nfsrv_free_addrlist: address not found (1)\n");
3106 			}
3107 			continue;
3108 		}
3109 
3110 		(*rnh->rnh_deladdr)(rn->rn_key, rn->rn_mask, rnh);
3111 		nno = (struct nfs_netopt *)rn;
3112 		if (IS_VALID_CRED(nno->no_opt.nxo_cred)) {
3113 			kauth_cred_unref(&nno->no_opt.nxo_cred);
3114 		}
3115 		nfs_netopt_free(nno);
3116 
3117 		nx->nx_expcnt--;
3118 		if (nx->nx_expcnt == ((nx->nx_flags & NX_DEFAULTEXPORT) ? 1 : 0)) {
3119 			/* no more entries in rnh, so free it up */
3120 			zfree(radix_node_head_zone, rnh);
3121 			nx->nx_rtable[nxna.nxna_addr.ss_family] = 0;
3122 		}
3123 	}
3124 
3125 	return 0;
3126 }
3127 
3128 void enablequotas(struct mount *mp, vfs_context_t ctx); // XXX
3129 
3130 #define DATA_VOLUME_MP "/System/Volumes/Data" // PLATFORM_DATA_VOLUME_MOUNT_POINT
3131 
3132 int
nfsrv_export(struct user_nfs_export_args * unxa,vfs_context_t ctx)3133 nfsrv_export(struct user_nfs_export_args *unxa, vfs_context_t ctx)
3134 {
3135 	int error = 0;
3136 	size_t pathlen, nxfs_pathlen;
3137 	struct nfs_exportfs *nxfs, *nxfs2, *nxfs3;
3138 	struct nfs_export *nx, *nx2, *nx3;
3139 	struct nfs_filehandle nfh;
3140 	struct nameidata mnd, xnd;
3141 	vnode_t mvp = NULL, xvp = NULL;
3142 	mount_t mp = NULL;
3143 	char path[MAXPATHLEN], *nxfs_path;
3144 	char fl_pathbuff[MAXPATHLEN];
3145 	int fl_pathbuff_len = MAXPATHLEN;
3146 	int expisroot;
3147 	size_t datavol_len = strlen(DATA_VOLUME_MP);
3148 
3149 	if (unxa->nxa_flags == NXA_CHECK) {
3150 		/* just check if the path is an NFS-exportable file system */
3151 		error = copyinstr(unxa->nxa_fspath, path, MAXPATHLEN, &pathlen);
3152 		if (error) {
3153 			return error;
3154 		}
3155 		NDINIT(&mnd, LOOKUP, OP_LOOKUP, FOLLOW | LOCKLEAF | AUDITVNPATH1,
3156 		    UIO_SYSSPACE, CAST_USER_ADDR_T(path), ctx);
3157 		error = namei(&mnd);
3158 		if (error) {
3159 			return error;
3160 		}
3161 		mvp = mnd.ni_vp;
3162 		mp = vnode_mount(mvp);
3163 		/* make sure it's the root of a file system */
3164 		if (!vnode_isvroot(mvp)) {
3165 			error = EINVAL;
3166 		}
3167 		/* make sure the file system is NFS-exportable */
3168 		if (!error) {
3169 			nfh.nfh_len = NFSV3_MAX_FID_SIZE;
3170 			error = VFS_VPTOFH(mvp, (int*)&nfh.nfh_len, &nfh.nfh_fid[0], NULL);
3171 		}
3172 		if (!error && (nfh.nfh_len > (int)NFSV3_MAX_FID_SIZE)) {
3173 			error = EIO;
3174 		}
3175 		if (!error && !(mp->mnt_vtable->vfc_vfsflags & VFC_VFSREADDIR_EXTENDED)) {
3176 			error = EISDIR;
3177 		}
3178 		vnode_put(mvp);
3179 		nameidone(&mnd);
3180 		return error;
3181 	}
3182 
3183 	/* all other operations: must be super user */
3184 	if ((error = vfs_context_suser(ctx))) {
3185 		return error;
3186 	}
3187 
3188 	if (unxa->nxa_flags & NXA_DELETE_ALL) {
3189 		/* delete all exports on all file systems */
3190 		lck_rw_lock_exclusive(&nfsrv_export_rwlock);
3191 		while ((nxfs = LIST_FIRST(&nfsrv_exports))) {
3192 			mp = vfs_getvfs_by_mntonname(nxfs->nxfs_path);
3193 			if (mp) {
3194 				vfs_clearflags(mp, MNT_EXPORTED);
3195 				mount_iterdrop(mp);
3196 				mp = NULL;
3197 			}
3198 			/* delete all exports on this file system */
3199 			while ((nx = LIST_FIRST(&nxfs->nxfs_exports))) {
3200 				LIST_REMOVE(nx, nx_next);
3201 				LIST_REMOVE(nx, nx_hash);
3202 				/* delete all netopts for this export */
3203 				nfsrv_free_addrlist(nx, NULL);
3204 				nx->nx_flags &= ~NX_DEFAULTEXPORT;
3205 				if (IS_VALID_CRED(nx->nx_defopt.nxo_cred)) {
3206 					kauth_cred_unref(&nx->nx_defopt.nxo_cred);
3207 				}
3208 				/* free active user list for this export */
3209 				nfsrv_free_user_list(&nx->nx_user_list);
3210 				kfree_data_addr(nx->nx_path);
3211 				kfree_type(struct nfs_export, nx);
3212 			}
3213 			LIST_REMOVE(nxfs, nxfs_next);
3214 			kfree_data_addr(nxfs->nxfs_path);
3215 			kfree_type(struct nfs_exportfs, nxfs);
3216 		}
3217 		if (nfsrv_export_hashtbl) {
3218 			/* all exports deleted, clean up export hash table */
3219 			hashdestroy(nfsrv_export_hashtbl, M_TEMP, nfsrv_export_hash);
3220 			nfsrv_export_hash = 0;
3221 			nfsrv_export_hashtbl = NULL;
3222 		}
3223 		lck_rw_done(&nfsrv_export_rwlock);
3224 		return 0;
3225 	}
3226 
3227 	error = copyinstr(unxa->nxa_fspath, path, MAXPATHLEN, &pathlen);
3228 	if (error) {
3229 		return error;
3230 	}
3231 
3232 	lck_rw_lock_exclusive(&nfsrv_export_rwlock);
3233 
3234 	/* init export hash table if not already */
3235 	if (!nfsrv_export_hashtbl) {
3236 		if (nfsrv_export_hash_size <= 0) {
3237 			nfsrv_export_hash_size = NFSRVEXPHASHSZ;
3238 		}
3239 		nfsrv_export_hashtbl = hashinit(nfsrv_export_hash_size, M_TEMP, &nfsrv_export_hash);
3240 	}
3241 
3242 	// first check if we've already got an exportfs with the given ID
3243 	LIST_FOREACH(nxfs, &nfsrv_exports, nxfs_next) {
3244 		if (nxfs->nxfs_id == unxa->nxa_fsid) {
3245 			break;
3246 		}
3247 	}
3248 	if (nxfs) {
3249 		/* verify exported FS path matches given path */
3250 		if (strncmp(path, nxfs->nxfs_path, MAXPATHLEN) &&
3251 		    (strncmp(path, DATA_VOLUME_MP, datavol_len) || strncmp(path + datavol_len, nxfs->nxfs_path, MAXPATHLEN - datavol_len))) {
3252 			error = EEXIST;
3253 			goto unlock_out;
3254 		}
3255 		if ((unxa->nxa_flags & (NXA_ADD | NXA_OFFLINE)) == NXA_ADD) {
3256 			/* find exported FS root vnode */
3257 			NDINIT(&mnd, LOOKUP, OP_LOOKUP, FOLLOW | LOCKLEAF | AUDITVNPATH1,
3258 			    UIO_SYSSPACE, CAST_USER_ADDR_T(nxfs->nxfs_path), ctx);
3259 			error = namei(&mnd);
3260 			if (error) {
3261 				goto unlock_out;
3262 			}
3263 			mvp = mnd.ni_vp;
3264 			/* make sure it's (still) the root of a file system */
3265 			if (!vnode_isvroot(mvp)) {
3266 				error = EINVAL;
3267 				goto out;
3268 			}
3269 			/* if adding, verify that the mount is still what we expect */
3270 			mp = vfs_getvfs_by_mntonname(nxfs->nxfs_path);
3271 			if (!mp) {
3272 				/* check for firmlink-free path */
3273 				if (vn_getpath_ext(mvp, NULLVP, fl_pathbuff, &fl_pathbuff_len, VN_GETPATH_NO_FIRMLINK) == 0 &&
3274 				    fl_pathbuff_len > 0 &&
3275 				    !strncmp(nxfs->nxfs_path, fl_pathbuff, MAXPATHLEN)) {
3276 					mp = vfs_getvfs_by_mntonname(vfs_statfs(vnode_mount(mvp))->f_mntonname);
3277 				}
3278 			}
3279 			if (mp) {
3280 				mount_ref(mp, 0);
3281 				mount_iterdrop(mp);
3282 			}
3283 			/* sanity check: this should be same mount */
3284 			if (mp != vnode_mount(mvp)) {
3285 				error = EINVAL;
3286 				goto out;
3287 			}
3288 		}
3289 	} else {
3290 		/* no current exported file system with that ID */
3291 		if (!(unxa->nxa_flags & NXA_ADD)) {
3292 			error = ENOENT;
3293 			goto unlock_out;
3294 		}
3295 
3296 		/* find exported FS root vnode */
3297 		NDINIT(&mnd, LOOKUP, OP_LOOKUP, FOLLOW | LOCKLEAF | AUDITVNPATH1,
3298 		    UIO_SYSSPACE, CAST_USER_ADDR_T(path), ctx);
3299 		error = namei(&mnd);
3300 		if (error) {
3301 			if (!(unxa->nxa_flags & NXA_OFFLINE)) {
3302 				goto unlock_out;
3303 			}
3304 		} else {
3305 			mvp = mnd.ni_vp;
3306 			/* make sure it's the root of a file system */
3307 			if (!vnode_isvroot(mvp)) {
3308 				/* bail if not marked offline */
3309 				if (!(unxa->nxa_flags & NXA_OFFLINE)) {
3310 					error = EINVAL;
3311 					goto out;
3312 				}
3313 				vnode_put(mvp);
3314 				nameidone(&mnd);
3315 				mvp = NULL;
3316 			} else {
3317 				mp = vnode_mount(mvp);
3318 				mount_ref(mp, 0);
3319 
3320 				/* make sure the file system is NFS-exportable */
3321 				nfh.nfh_len = NFSV3_MAX_FID_SIZE;
3322 				error = VFS_VPTOFH(mvp, (int*)&nfh.nfh_len, &nfh.nfh_fid[0], NULL);
3323 				if (!error && (nfh.nfh_len > (int)NFSV3_MAX_FID_SIZE)) {
3324 					error = EIO;
3325 				}
3326 				if (!error && !(mp->mnt_vtable->vfc_vfsflags & VFC_VFSREADDIR_EXTENDED)) {
3327 					error = EISDIR;
3328 				}
3329 				if (error) {
3330 					goto out;
3331 				}
3332 			}
3333 		}
3334 
3335 		/* add an exportfs for it */
3336 		nxfs = kalloc_type(struct nfs_exportfs, Z_WAITOK | Z_ZERO | Z_NOFAIL);
3337 		nxfs->nxfs_id = unxa->nxa_fsid;
3338 		if (mp) {
3339 			nxfs_path = mp->mnt_vfsstat.f_mntonname;
3340 			nxfs_pathlen = sizeof(mp->mnt_vfsstat.f_mntonname);
3341 		} else {
3342 			nxfs_path = path;
3343 			nxfs_pathlen = pathlen;
3344 		}
3345 		nxfs->nxfs_path = kalloc_data(nxfs_pathlen, Z_WAITOK);
3346 		if (!nxfs->nxfs_path) {
3347 			kfree_type(struct nfs_exportfs, nxfs);
3348 			error = ENOMEM;
3349 			goto out;
3350 		}
3351 		bcopy(nxfs_path, nxfs->nxfs_path, nxfs_pathlen);
3352 		/* insert into list in reverse-sorted order */
3353 		nxfs3 = NULL;
3354 		LIST_FOREACH(nxfs2, &nfsrv_exports, nxfs_next) {
3355 			if (strncmp(nxfs->nxfs_path, nxfs2->nxfs_path, MAXPATHLEN) > 0) {
3356 				break;
3357 			}
3358 			nxfs3 = nxfs2;
3359 		}
3360 		if (nxfs2) {
3361 			LIST_INSERT_BEFORE(nxfs2, nxfs, nxfs_next);
3362 		} else if (nxfs3) {
3363 			LIST_INSERT_AFTER(nxfs3, nxfs, nxfs_next);
3364 		} else {
3365 			LIST_INSERT_HEAD(&nfsrv_exports, nxfs, nxfs_next);
3366 		}
3367 
3368 		/* make sure any quotas are enabled before we export the file system */
3369 		if (mp) {
3370 			enablequotas(mp, ctx);
3371 		}
3372 	}
3373 
3374 	if (unxa->nxa_exppath) {
3375 		error = copyinstr(unxa->nxa_exppath, path, MAXPATHLEN, &pathlen);
3376 		if (error) {
3377 			goto out;
3378 		}
3379 		LIST_FOREACH(nx, &nxfs->nxfs_exports, nx_next) {
3380 			if (nx->nx_id == unxa->nxa_expid) {
3381 				break;
3382 			}
3383 		}
3384 		if (nx) {
3385 			/* verify exported FS path matches given path */
3386 			if (strncmp(path, nx->nx_path, MAXPATHLEN)) {
3387 				error = EEXIST;
3388 				goto out;
3389 			}
3390 		} else {
3391 			/* no current export with that ID */
3392 			if (!(unxa->nxa_flags & NXA_ADD)) {
3393 				error = ENOENT;
3394 				goto out;
3395 			}
3396 			/* add an export for it */
3397 			nx = kalloc_type(struct nfs_export, Z_WAITOK | Z_ZERO | Z_NOFAIL);
3398 			nx->nx_id = unxa->nxa_expid;
3399 			nx->nx_fs = nxfs;
3400 			microtime(&nx->nx_exptime);
3401 			nx->nx_path = kalloc_data(pathlen, Z_WAITOK);
3402 			if (!nx->nx_path) {
3403 				error = ENOMEM;
3404 				kfree_type(struct nfs_export, nx);
3405 				nx = NULL;
3406 				goto out1;
3407 			}
3408 			bcopy(path, nx->nx_path, pathlen);
3409 			/* initialize the active user list */
3410 			nfsrv_init_user_list(&nx->nx_user_list);
3411 			/* insert into list in reverse-sorted order */
3412 			nx3 = NULL;
3413 			LIST_FOREACH(nx2, &nxfs->nxfs_exports, nx_next) {
3414 				if (strncmp(nx->nx_path, nx2->nx_path, MAXPATHLEN) > 0) {
3415 					break;
3416 				}
3417 				nx3 = nx2;
3418 			}
3419 			if (nx2) {
3420 				LIST_INSERT_BEFORE(nx2, nx, nx_next);
3421 			} else if (nx3) {
3422 				LIST_INSERT_AFTER(nx3, nx, nx_next);
3423 			} else {
3424 				LIST_INSERT_HEAD(&nxfs->nxfs_exports, nx, nx_next);
3425 			}
3426 			/* insert into hash */
3427 			LIST_INSERT_HEAD(NFSRVEXPHASH(nxfs->nxfs_id, nx->nx_id), nx, nx_hash);
3428 
3429 			/*
3430 			 * We don't allow/support nested exports.  Check if the new entry
3431 			 * nests with the entries before and after or if there's an
3432 			 * entry for the file system root and subdirs.
3433 			 */
3434 			error = 0;
3435 			if ((nx3 && !strncmp(nx3->nx_path, nx->nx_path, pathlen - 1) &&
3436 			    (nx3->nx_path[pathlen - 1] == '/')) ||
3437 			    (nx2 && !strncmp(nx2->nx_path, nx->nx_path, strlen(nx2->nx_path)) &&
3438 			    (nx->nx_path[strlen(nx2->nx_path)] == '/'))) {
3439 				error = EINVAL;
3440 			}
3441 			if (!error) {
3442 				/* check export conflict with fs root export and vice versa */
3443 				expisroot = !nx->nx_path[0] ||
3444 				    ((nx->nx_path[0] == '.') && !nx->nx_path[1]);
3445 				LIST_FOREACH(nx2, &nxfs->nxfs_exports, nx_next) {
3446 					if (expisroot) {
3447 						if (nx2 != nx) {
3448 							break;
3449 						}
3450 					} else if (!nx2->nx_path[0]) {
3451 						break;
3452 					} else if ((nx2->nx_path[0] == '.') && !nx2->nx_path[1]) {
3453 						break;
3454 					}
3455 				}
3456 				if (nx2) {
3457 					error = EINVAL;
3458 				}
3459 			}
3460 			if (error) {
3461 				/*
3462 				 * Don't actually return an error because mountd is
3463 				 * probably about to delete the conflicting export.
3464 				 * This can happen when a new export momentarily conflicts
3465 				 * with an old export while the transition is being made.
3466 				 * Theoretically, mountd could be written to avoid this
3467 				 * transient situation - but it would greatly increase the
3468 				 * complexity of mountd for very little overall benefit.
3469 				 */
3470 				printf("nfsrv_export: warning: nested exports: %s/%s\n",
3471 				    nxfs->nxfs_path, nx->nx_path);
3472 				error = 0;
3473 			}
3474 			nx->nx_fh.nfh_xh.nxh_flags = NXHF_INVALIDFH;
3475 		}
3476 		/* make sure file handle is set up */
3477 		if ((nx->nx_fh.nfh_xh.nxh_version != htonl(NFS_FH_VERSION)) ||
3478 		    (nx->nx_fh.nfh_xh.nxh_flags & NXHF_INVALIDFH)) {
3479 			/* try to set up export root file handle */
3480 			nx->nx_fh.nfh_xh.nxh_version = htonl(NFS_FH_VERSION);
3481 			nx->nx_fh.nfh_xh.nxh_fsid = htonl(nx->nx_fs->nxfs_id);
3482 			nx->nx_fh.nfh_xh.nxh_expid = htonl(nx->nx_id);
3483 			nx->nx_fh.nfh_xh.nxh_flags = 0;
3484 			nx->nx_fh.nfh_xh.nxh_reserved = 0;
3485 			nx->nx_fh.nfh_fhp = (u_char*)&nx->nx_fh.nfh_xh;
3486 			bzero(&nx->nx_fh.nfh_fid[0], NFSV2_MAX_FID_SIZE);
3487 			if (mvp) {
3488 				/* find export root vnode */
3489 				if (!nx->nx_path[0] || ((nx->nx_path[0] == '.') && !nx->nx_path[1])) {
3490 					/* exporting file system's root directory */
3491 					xvp = mvp;
3492 					vnode_get(xvp);
3493 				} else {
3494 					NDINIT(&xnd, LOOKUP, OP_LOOKUP, LOCKLEAF, UIO_SYSSPACE, CAST_USER_ADDR_T(path), ctx);
3495 					xnd.ni_pathlen = (uint32_t)pathlen - 1; // pathlen max value is equal to MAXPATHLEN
3496 					xnd.ni_cnd.cn_nameptr = xnd.ni_cnd.cn_pnbuf = path;
3497 					xnd.ni_startdir = mvp;
3498 					xnd.ni_usedvp   = mvp;
3499 					xnd.ni_rootdir = rootvnode;
3500 					while ((error = lookup(&xnd)) == ERECYCLE) {
3501 						xnd.ni_cnd.cn_flags = LOCKLEAF;
3502 						xnd.ni_cnd.cn_nameptr = xnd.ni_cnd.cn_pnbuf;
3503 						xnd.ni_usedvp = xnd.ni_dvp = xnd.ni_startdir = mvp;
3504 					}
3505 					if (error) {
3506 						goto out1;
3507 					}
3508 					xvp = xnd.ni_vp;
3509 				}
3510 
3511 				if (vnode_vtype(xvp) != VDIR) {
3512 					error = EINVAL;
3513 					vnode_put(xvp);
3514 					goto out1;
3515 				}
3516 
3517 				/* grab file handle */
3518 				nx->nx_fh.nfh_len = NFSV3_MAX_FID_SIZE;
3519 				error = VFS_VPTOFH(xvp, (int*)&nx->nx_fh.nfh_len, &nx->nx_fh.nfh_fid[0], NULL);
3520 				if (!error && (nx->nx_fh.nfh_len > (int)NFSV3_MAX_FID_SIZE)) {
3521 					error = EIO;
3522 				} else {
3523 					nx->nx_fh.nfh_xh.nxh_fidlen = nx->nx_fh.nfh_len;
3524 					nx->nx_fh.nfh_len += sizeof(nx->nx_fh.nfh_xh);
3525 				}
3526 
3527 				vnode_put(xvp);
3528 				if (error) {
3529 					goto out1;
3530 				}
3531 			} else {
3532 				nx->nx_fh.nfh_xh.nxh_flags = NXHF_INVALIDFH;
3533 				nx->nx_fh.nfh_xh.nxh_fidlen = 0;
3534 				nx->nx_fh.nfh_len = sizeof(nx->nx_fh.nfh_xh);
3535 			}
3536 		}
3537 	} else {
3538 		nx = NULL;
3539 	}
3540 
3541 	/* perform the export changes */
3542 	if (unxa->nxa_flags & NXA_DELETE) {
3543 		if (!nx) {
3544 			/* delete all exports on this file system */
3545 			while ((nx = LIST_FIRST(&nxfs->nxfs_exports))) {
3546 				LIST_REMOVE(nx, nx_next);
3547 				LIST_REMOVE(nx, nx_hash);
3548 				/* delete all netopts for this export */
3549 				nfsrv_free_addrlist(nx, NULL);
3550 				nx->nx_flags &= ~NX_DEFAULTEXPORT;
3551 				if (IS_VALID_CRED(nx->nx_defopt.nxo_cred)) {
3552 					kauth_cred_unref(&nx->nx_defopt.nxo_cred);
3553 				}
3554 				/* delete active user list for this export */
3555 				nfsrv_free_user_list(&nx->nx_user_list);
3556 				kfree_data_addr(nx->nx_path);
3557 				kfree_type(struct nfs_export, nx);
3558 			}
3559 			goto out1;
3560 		} else if (!unxa->nxa_netcount) {
3561 			/* delete all netopts for this export */
3562 			nfsrv_free_addrlist(nx, NULL);
3563 			nx->nx_flags &= ~NX_DEFAULTEXPORT;
3564 			if (IS_VALID_CRED(nx->nx_defopt.nxo_cred)) {
3565 				kauth_cred_unref(&nx->nx_defopt.nxo_cred);
3566 			}
3567 		} else {
3568 			/* delete only the netopts for the given addresses */
3569 			error = nfsrv_free_addrlist(nx, unxa);
3570 			if (error) {
3571 				goto out1;
3572 			}
3573 		}
3574 	}
3575 	if (unxa->nxa_flags & NXA_ADD) {
3576 		/*
3577 		 * If going offline set the export time so that when
3578 		 * coming back on line we will present a new write verifier
3579 		 * to the client.
3580 		 */
3581 		if (unxa->nxa_flags & NXA_OFFLINE) {
3582 			microtime(&nx->nx_exptime);
3583 		}
3584 
3585 		error = nfsrv_hang_addrlist(nx, unxa);
3586 		if (!error && mp) {
3587 			vfs_setflags(mp, MNT_EXPORTED);
3588 		}
3589 	}
3590 
3591 out1:
3592 	if (nx && !nx->nx_expcnt) {
3593 		/* export has no export options */
3594 		LIST_REMOVE(nx, nx_next);
3595 		LIST_REMOVE(nx, nx_hash);
3596 		/* delete active user list for this export */
3597 		nfsrv_free_user_list(&nx->nx_user_list);
3598 		kfree_data_addr(nx->nx_path);
3599 		kfree_type(struct nfs_export, nx);
3600 	}
3601 	if (LIST_EMPTY(&nxfs->nxfs_exports)) {
3602 		/* exported file system has no more exports */
3603 		LIST_REMOVE(nxfs, nxfs_next);
3604 		kfree_data_addr(nxfs->nxfs_path);
3605 		kfree_type(struct nfs_exportfs, nxfs);
3606 		if (mp) {
3607 			vfs_clearflags(mp, MNT_EXPORTED);
3608 		}
3609 	}
3610 
3611 out:
3612 	if (mvp) {
3613 		vnode_put(mvp);
3614 		nameidone(&mnd);
3615 	}
3616 unlock_out:
3617 	if (mp) {
3618 		mount_drop(mp, 0);
3619 	}
3620 	lck_rw_done(&nfsrv_export_rwlock);
3621 	return error;
3622 }
3623 
3624 /*
3625  * Check if there is a least one export that will allow this address.
3626  *
3627  * Return 0, if there is an export that will allow this address,
3628  * else return EACCES
3629  */
3630 int
nfsrv_check_exports_allow_address(mbuf_t nam)3631 nfsrv_check_exports_allow_address(mbuf_t nam)
3632 {
3633 	struct nfs_exportfs             *nxfs;
3634 	struct nfs_export               *nx;
3635 	struct nfs_export_options       *nxo = NULL;
3636 
3637 	if (nam == NULL) {
3638 		return EACCES;
3639 	}
3640 
3641 	lck_rw_lock_shared(&nfsrv_export_rwlock);
3642 	LIST_FOREACH(nxfs, &nfsrv_exports, nxfs_next) {
3643 		LIST_FOREACH(nx, &nxfs->nxfs_exports, nx_next) {
3644 			/* A little optimizing by checking for the default first */
3645 			if (nx->nx_flags & NX_DEFAULTEXPORT) {
3646 				nxo = &nx->nx_defopt;
3647 			}
3648 			if (nxo || (nxo = nfsrv_export_lookup(nx, nam))) {
3649 				goto found;
3650 			}
3651 		}
3652 	}
3653 found:
3654 	lck_rw_done(&nfsrv_export_rwlock);
3655 
3656 	return nxo ? 0 : EACCES;
3657 }
3658 
3659 struct nfs_export_options *
nfsrv_export_lookup(struct nfs_export * nx,mbuf_t nam)3660 nfsrv_export_lookup(struct nfs_export *nx, mbuf_t nam)
3661 {
3662 	struct nfs_export_options *nxo = NULL;
3663 	struct nfs_netopt *no = NULL;
3664 	struct radix_node_head *rnh;
3665 	struct sockaddr *saddr;
3666 
3667 	/* Lookup in the export list first. */
3668 	if (nam != NULL) {
3669 		saddr = mbuf_data(nam);
3670 		if (saddr->sa_family > AF_MAX) {
3671 			/* Bogus sockaddr?  Don't match anything. */
3672 			return NULL;
3673 		}
3674 		rnh = nx->nx_rtable[saddr->sa_family];
3675 		if (rnh != NULL) {
3676 			no = (struct nfs_netopt *)
3677 			    (*rnh->rnh_matchaddr)((caddr_t)saddr, rnh);
3678 			if (no && no->no_rnodes->rn_flags & RNF_ROOT) {
3679 				no = NULL;
3680 			}
3681 			if (no) {
3682 				nxo = &no->no_opt;
3683 			}
3684 		}
3685 	}
3686 	/* If no address match, use the default if it exists. */
3687 	if ((nxo == NULL) && (nx->nx_flags & NX_DEFAULTEXPORT)) {
3688 		nxo = &nx->nx_defopt;
3689 	}
3690 	return nxo;
3691 }
3692 
3693 /* find an export for the given handle */
3694 struct nfs_export *
nfsrv_fhtoexport(struct nfs_filehandle * nfhp)3695 nfsrv_fhtoexport(struct nfs_filehandle *nfhp)
3696 {
3697 	struct nfs_exphandle *nxh = (struct nfs_exphandle*)nfhp->nfh_fhp;
3698 	struct nfs_export *nx;
3699 	uint32_t fsid, expid;
3700 
3701 	if (!nfsrv_export_hashtbl) {
3702 		return NULL;
3703 	}
3704 	fsid = ntohl(nxh->nxh_fsid);
3705 	expid = ntohl(nxh->nxh_expid);
3706 	nx = NFSRVEXPHASH(fsid, expid)->lh_first;
3707 	for (; nx; nx = LIST_NEXT(nx, nx_hash)) {
3708 		if (nx->nx_fs->nxfs_id != fsid) {
3709 			continue;
3710 		}
3711 		if (nx->nx_id != expid) {
3712 			continue;
3713 		}
3714 		break;
3715 	}
3716 	return nx;
3717 }
3718 
3719 struct nfsrv_getvfs_by_mntonname_callback_args {
3720 	const char      *path;          /* IN */
3721 	mount_t         mp;             /* OUT */
3722 };
3723 
3724 static int
nfsrv_getvfs_by_mntonname_callback(mount_t mp,void * v)3725 nfsrv_getvfs_by_mntonname_callback(mount_t mp, void *v)
3726 {
3727 	struct nfsrv_getvfs_by_mntonname_callback_args * const args = v;
3728 	char real_mntonname[MAXPATHLEN];
3729 	int pathbuflen = MAXPATHLEN;
3730 	vnode_t rvp;
3731 	int error;
3732 
3733 	error = VFS_ROOT(mp, &rvp, vfs_context_current());
3734 	if (error) {
3735 		goto out;
3736 	}
3737 	error = vn_getpath_ext(rvp, NULLVP, real_mntonname, &pathbuflen,
3738 	    VN_GETPATH_FSENTER | VN_GETPATH_NO_FIRMLINK);
3739 	vnode_put(rvp);
3740 	if (error) {
3741 		goto out;
3742 	}
3743 	if (strcmp(args->path, real_mntonname) == 0) {
3744 		error = vfs_busy(mp, LK_NOWAIT);
3745 		if (error == 0) {
3746 			args->mp = mp;
3747 		}
3748 		return VFS_RETURNED_DONE;
3749 	}
3750 out:
3751 	return VFS_RETURNED;
3752 }
3753 
3754 static mount_t
nfsrv_getvfs_by_mntonname(char * path)3755 nfsrv_getvfs_by_mntonname(char *path)
3756 {
3757 	struct nfsrv_getvfs_by_mntonname_callback_args args = {
3758 		.path = path,
3759 		.mp = NULL,
3760 	};
3761 	mount_t mp;
3762 	int error;
3763 
3764 	mp = vfs_getvfs_by_mntonname(path);
3765 	if (mp) {
3766 		error = vfs_busy(mp, LK_NOWAIT);
3767 		mount_iterdrop(mp);
3768 		if (error) {
3769 			mp = NULL;
3770 		}
3771 	} else if (vfs_iterate(0, nfsrv_getvfs_by_mntonname_callback,
3772 	    &args) == 0) {
3773 		mp = args.mp;
3774 	}
3775 	return mp;
3776 }
3777 
3778 /*
3779  * nfsrv_fhtovp() - convert FH to vnode and export info
3780  */
3781 int
nfsrv_fhtovp(struct nfs_filehandle * nfhp,struct nfsrv_descript * nd,vnode_t * vpp,struct nfs_export ** nxp,struct nfs_export_options ** nxop)3782 nfsrv_fhtovp(
3783 	struct nfs_filehandle *nfhp,
3784 	struct nfsrv_descript *nd,
3785 	vnode_t *vpp,
3786 	struct nfs_export **nxp,
3787 	struct nfs_export_options **nxop)
3788 {
3789 	struct nfs_exphandle *nxh = (struct nfs_exphandle*)nfhp->nfh_fhp;
3790 	struct nfs_export_options *nxo;
3791 	u_char *fidp;
3792 	int error;
3793 	struct mount *mp;
3794 	mbuf_t nam = NULL;
3795 	uint32_t v;
3796 	int i, valid;
3797 
3798 	*vpp = NULL;
3799 	*nxp = NULL;
3800 	*nxop = NULL;
3801 
3802 	if (nd != NULL) {
3803 		nam = nd->nd_nam;
3804 	}
3805 
3806 	v = ntohl(nxh->nxh_version);
3807 	if (v != NFS_FH_VERSION) {
3808 		/* file handle format not supported */
3809 		return ESTALE;
3810 	}
3811 	if (nfhp->nfh_len > NFSV3_MAX_FH_SIZE) {
3812 		return EBADRPC;
3813 	}
3814 	if (nfhp->nfh_len < (int)sizeof(struct nfs_exphandle)) {
3815 		return ESTALE;
3816 	}
3817 	v = ntohs(nxh->nxh_flags);
3818 	if (v & NXHF_INVALIDFH) {
3819 		return ESTALE;
3820 	}
3821 
3822 	*nxp = nfsrv_fhtoexport(nfhp);
3823 	if (!*nxp) {
3824 		return ESTALE;
3825 	}
3826 
3827 	/* Get the export option structure for this <export, client> tuple. */
3828 	*nxop = nxo = nfsrv_export_lookup(*nxp, nam);
3829 	if (nam && (*nxop == NULL)) {
3830 		return EACCES;
3831 	}
3832 
3833 	if (nd != NULL) {
3834 		/* Validate the security flavor of the request */
3835 		for (i = 0, valid = 0; i < nxo->nxo_sec.count; i++) {
3836 			if (nd->nd_sec == nxo->nxo_sec.flavors[i]) {
3837 				valid = 1;
3838 				break;
3839 			}
3840 		}
3841 		if (!valid) {
3842 			/*
3843 			 * RFC 2623 section 2.3.2 recommends no authentication
3844 			 * requirement for certain NFS procedures used for mounting.
3845 			 * This allows an unauthenticated superuser on the client
3846 			 * to do mounts for the benefit of authenticated users.
3847 			 */
3848 			if (nd->nd_vers == NFS_VER2) {
3849 				if (nd->nd_procnum == NFSV2PROC_GETATTR ||
3850 				    nd->nd_procnum == NFSV2PROC_STATFS) {
3851 					valid = 1;
3852 				}
3853 			}
3854 			if (nd->nd_vers == NFS_VER3) {
3855 				if (nd->nd_procnum == NFSPROC_FSINFO) {
3856 					valid = 1;
3857 				}
3858 			}
3859 
3860 			if (!valid) {
3861 				return NFSERR_AUTHERR | AUTH_REJECTCRED;
3862 			}
3863 		}
3864 	}
3865 
3866 	if (nxo && (nxo->nxo_flags & NX_OFFLINE)) {
3867 		return (nd == NULL || nd->nd_vers == NFS_VER2) ? ESTALE : NFSERR_TRYLATER;
3868 	}
3869 
3870 	/* find mount structure */
3871 	mp = nfsrv_getvfs_by_mntonname((*nxp)->nx_fs->nxfs_path);
3872 	if (!mp) {
3873 		/*
3874 		 * We have an export, but no mount?
3875 		 * Perhaps the export just hasn't been marked offline yet.
3876 		 */
3877 		return (nd == NULL || nd->nd_vers == NFS_VER2) ? ESTALE : NFSERR_TRYLATER;
3878 	}
3879 
3880 	fidp = nfhp->nfh_fhp + sizeof(*nxh);
3881 	error = VFS_FHTOVP(mp, nxh->nxh_fidlen, fidp, vpp, NULL);
3882 	vfs_unbusy(mp);
3883 	if (error) {
3884 		return error;
3885 	}
3886 	/* vnode pointer should be good at this point or ... */
3887 	if (*vpp == NULL) {
3888 		return ESTALE;
3889 	}
3890 	return 0;
3891 }
3892 
3893 /*
3894  * nfsrv_credcheck() - check/map credentials according
3895  * to given export options.
3896  */
3897 int
nfsrv_credcheck(struct nfsrv_descript * nd,vfs_context_t ctx,__unused struct nfs_export * nx,struct nfs_export_options * nxo)3898 nfsrv_credcheck(
3899 	struct nfsrv_descript *nd,
3900 	vfs_context_t ctx,
3901 	__unused struct nfs_export *nx,
3902 	struct nfs_export_options *nxo)
3903 {
3904 	if (nxo && nxo->nxo_cred) {
3905 		if ((nxo->nxo_flags & NX_MAPALL) ||
3906 		    ((nxo->nxo_flags & NX_MAPROOT) && !suser(nd->nd_cr, NULL))) {
3907 			kauth_cred_ref(nxo->nxo_cred);
3908 			kauth_cred_unref(&nd->nd_cr);
3909 			nd->nd_cr = nxo->nxo_cred;
3910 		}
3911 	}
3912 	ctx->vc_ucred = nd->nd_cr;
3913 	return 0;
3914 }
3915 
3916 /*
3917  * nfsrv_vptofh() - convert vnode to file handle for given export
3918  *
3919  * If the caller is passing in a vnode for a ".." directory entry,
3920  * they can pass a directory NFS file handle (dnfhp) which will be
3921  * checked against the root export file handle.  If it matches, we
3922  * refuse to provide the file handle for the out-of-export directory.
3923  */
3924 int
nfsrv_vptofh(struct nfs_export * nx,int nfsvers,struct nfs_filehandle * dnfhp,vnode_t vp,vfs_context_t ctx,struct nfs_filehandle * nfhp)3925 nfsrv_vptofh(
3926 	struct nfs_export *nx,
3927 	int nfsvers,
3928 	struct nfs_filehandle *dnfhp,
3929 	vnode_t vp,
3930 	vfs_context_t ctx,
3931 	struct nfs_filehandle *nfhp)
3932 {
3933 	int error;
3934 	uint32_t maxfidsize;
3935 
3936 	nfhp->nfh_fhp = (u_char*)&nfhp->nfh_xh;
3937 	nfhp->nfh_xh.nxh_version = htonl(NFS_FH_VERSION);
3938 	nfhp->nfh_xh.nxh_fsid = htonl(nx->nx_fs->nxfs_id);
3939 	nfhp->nfh_xh.nxh_expid = htonl(nx->nx_id);
3940 	nfhp->nfh_xh.nxh_flags = 0;
3941 	nfhp->nfh_xh.nxh_reserved = 0;
3942 
3943 	if (nfsvers == NFS_VER2) {
3944 		bzero(&nfhp->nfh_fid[0], NFSV2_MAX_FID_SIZE);
3945 	}
3946 
3947 	/* if directory FH matches export root, return invalid FH */
3948 	if (dnfhp && nfsrv_fhmatch(dnfhp, &nx->nx_fh)) {
3949 		if (nfsvers == NFS_VER2) {
3950 			nfhp->nfh_len = NFSX_V2FH;
3951 		} else {
3952 			nfhp->nfh_len = sizeof(nfhp->nfh_xh);
3953 		}
3954 		nfhp->nfh_xh.nxh_fidlen = 0;
3955 		nfhp->nfh_xh.nxh_flags = htons(NXHF_INVALIDFH);
3956 		return 0;
3957 	}
3958 
3959 	if (nfsvers == NFS_VER2) {
3960 		maxfidsize = NFSV2_MAX_FID_SIZE;
3961 	} else {
3962 		maxfidsize = NFSV3_MAX_FID_SIZE;
3963 	}
3964 	nfhp->nfh_len = maxfidsize;
3965 
3966 	error = VFS_VPTOFH(vp, (int*)&nfhp->nfh_len, &nfhp->nfh_fid[0], ctx);
3967 	if (error) {
3968 		return error;
3969 	}
3970 	if (nfhp->nfh_len > maxfidsize) {
3971 		return EOVERFLOW;
3972 	}
3973 	nfhp->nfh_xh.nxh_fidlen = nfhp->nfh_len;
3974 	nfhp->nfh_len += sizeof(nfhp->nfh_xh);
3975 	if ((nfsvers == NFS_VER2) && (nfhp->nfh_len < NFSX_V2FH)) {
3976 		nfhp->nfh_len = NFSX_V2FH;
3977 	}
3978 
3979 	return 0;
3980 }
3981 
3982 /*
3983  * Compare two file handles to see it they're the same.
3984  * Note that we don't use nfh_len because that may include
3985  * padding in an NFSv2 file handle.
3986  */
3987 int
nfsrv_fhmatch(struct nfs_filehandle * fh1,struct nfs_filehandle * fh2)3988 nfsrv_fhmatch(struct nfs_filehandle *fh1, struct nfs_filehandle *fh2)
3989 {
3990 	struct nfs_exphandle *nxh1, *nxh2;
3991 	int len1, len2;
3992 
3993 	nxh1 = (struct nfs_exphandle *)fh1->nfh_fhp;
3994 	nxh2 = (struct nfs_exphandle *)fh2->nfh_fhp;
3995 	len1 = sizeof(fh1->nfh_xh) + nxh1->nxh_fidlen;
3996 	len2 = sizeof(fh2->nfh_xh) + nxh2->nxh_fidlen;
3997 	if (len1 != len2) {
3998 		return 0;
3999 	}
4000 	if (bcmp(nxh1, nxh2, len1)) {
4001 		return 0;
4002 	}
4003 	return 1;
4004 }
4005 
4006 /*
4007  * Functions for dealing with active user lists
4008  */
4009 
4010 /*
4011  * Search the hash table for a user node with a matching IP address and uid field.
4012  * If found, the node's tm_last timestamp is updated and the node is returned.
4013  *
4014  * If not found, a new node is allocated (or reclaimed via LRU), initialized, and returned.
4015  * Returns NULL if a new node could not be allocated OR saddr length exceeds sizeof(unode->sock).
4016  *
4017  * The list's user_mutex lock MUST be held.
4018  */
4019 struct nfs_user_stat_node *
nfsrv_get_user_stat_node(struct nfs_active_user_list * list,struct sockaddr * saddr,uid_t uid)4020 nfsrv_get_user_stat_node(struct nfs_active_user_list *list, struct sockaddr *saddr, uid_t uid)
4021 {
4022 	struct nfs_user_stat_node               *unode;
4023 	struct timeval                          now;
4024 	struct nfs_user_stat_hashtbl_head       *head;
4025 
4026 	/* seach the hash table */
4027 	head = NFS_USER_STAT_HASH(list->user_hashtbl, uid);
4028 	LIST_FOREACH(unode, head, hash_link) {
4029 		if ((uid == unode->uid) && (nfs_sockaddr_cmp(saddr, (struct sockaddr*)&unode->sock) == 0)) {
4030 			/* found matching node */
4031 			break;
4032 		}
4033 	}
4034 
4035 	if (unode) {
4036 		/* found node in the hash table, now update lru position */
4037 		TAILQ_REMOVE(&list->user_lru, unode, lru_link);
4038 		TAILQ_INSERT_TAIL(&list->user_lru, unode, lru_link);
4039 
4040 		/* update time stamp */
4041 		microtime(&now);
4042 		unode->tm_last = (uint32_t)now.tv_sec;
4043 		return unode;
4044 	}
4045 
4046 	if (saddr->sa_len > sizeof(((struct nfs_user_stat_node *)0)->sock)) {
4047 		/* saddr length exceeds maximum value */
4048 		return NULL;
4049 	}
4050 
4051 	if (list->node_count < nfsrv_user_stat_max_nodes) {
4052 		/* Allocate a new node */
4053 		unode = kalloc_type(struct nfs_user_stat_node,
4054 		    Z_WAITOK | Z_ZERO | Z_NOFAIL);
4055 
4056 		/* increment node count */
4057 		OSAddAtomic(1, &nfsrv_user_stat_node_count);
4058 		list->node_count++;
4059 	} else {
4060 		/* reuse the oldest node in the lru list */
4061 		unode = TAILQ_FIRST(&list->user_lru);
4062 
4063 		if (!unode) {
4064 			return NULL;
4065 		}
4066 
4067 		/* Remove the node */
4068 		TAILQ_REMOVE(&list->user_lru, unode, lru_link);
4069 		LIST_REMOVE(unode, hash_link);
4070 	}
4071 
4072 	/* Initialize the node */
4073 	unode->uid = uid;
4074 	bcopy(saddr, &unode->sock, MIN(saddr->sa_len, sizeof(unode->sock)));
4075 	microtime(&now);
4076 	unode->ops = 0;
4077 	unode->bytes_read = 0;
4078 	unode->bytes_written = 0;
4079 	unode->tm_start = (uint32_t)now.tv_sec;
4080 	unode->tm_last = (uint32_t)now.tv_sec;
4081 
4082 	/* insert the node  */
4083 	TAILQ_INSERT_TAIL(&list->user_lru, unode, lru_link);
4084 	LIST_INSERT_HEAD(head, unode, hash_link);
4085 
4086 	return unode;
4087 }
4088 
4089 void
nfsrv_update_user_stat(struct nfs_export * nx,struct nfsrv_descript * nd,uid_t uid,u_int ops,u_int rd_bytes,u_int wr_bytes)4090 nfsrv_update_user_stat(struct nfs_export *nx, struct nfsrv_descript *nd, uid_t uid, u_int ops, u_int rd_bytes, u_int wr_bytes)
4091 {
4092 	struct nfs_user_stat_node       *unode;
4093 	struct nfs_active_user_list     *ulist;
4094 	struct sockaddr                 *saddr;
4095 
4096 	if ((!nfsrv_user_stat_enabled) || (!nx) || (!nd) || (!nd->nd_nam)) {
4097 		return;
4098 	}
4099 
4100 	saddr = (struct sockaddr *)mbuf_data(nd->nd_nam);
4101 
4102 	/* check address family before going any further */
4103 	if ((saddr->sa_family != AF_INET) && (saddr->sa_family != AF_INET6)) {
4104 		return;
4105 	}
4106 
4107 	ulist = &nx->nx_user_list;
4108 
4109 	/* lock the active user list */
4110 	lck_mtx_lock(&ulist->user_mutex);
4111 
4112 	/* get the user node */
4113 	unode = nfsrv_get_user_stat_node(ulist, saddr, uid);
4114 
4115 	if (!unode) {
4116 		lck_mtx_unlock(&ulist->user_mutex);
4117 		return;
4118 	}
4119 
4120 	/* update counters */
4121 	unode->ops += ops;
4122 	unode->bytes_read += rd_bytes;
4123 	unode->bytes_written += wr_bytes;
4124 
4125 	/* done */
4126 	lck_mtx_unlock(&ulist->user_mutex);
4127 }
4128 
4129 /* initialize an active user list */
4130 void
nfsrv_init_user_list(struct nfs_active_user_list * ulist)4131 nfsrv_init_user_list(struct nfs_active_user_list *ulist)
4132 {
4133 	uint i;
4134 
4135 	/* initialize the lru */
4136 	TAILQ_INIT(&ulist->user_lru);
4137 
4138 	/* initialize the hash table */
4139 	for (i = 0; i < NFS_USER_STAT_HASH_SIZE; i++) {
4140 		LIST_INIT(&ulist->user_hashtbl[i]);
4141 	}
4142 	ulist->node_count = 0;
4143 
4144 	lck_mtx_init(&ulist->user_mutex, &nfsrv_active_user_mutex_group, LCK_ATTR_NULL);
4145 }
4146 
4147 /* Free all nodes in an active user list */
4148 void
nfsrv_free_user_list(struct nfs_active_user_list * ulist)4149 nfsrv_free_user_list(struct nfs_active_user_list *ulist)
4150 {
4151 	struct nfs_user_stat_node *unode;
4152 
4153 	if (!ulist) {
4154 		return;
4155 	}
4156 
4157 	while ((unode = TAILQ_FIRST(&ulist->user_lru))) {
4158 		/* Remove node and free */
4159 		TAILQ_REMOVE(&ulist->user_lru, unode, lru_link);
4160 		LIST_REMOVE(unode, hash_link);
4161 		kfree_type(struct nfs_user_stat_node, unode);
4162 
4163 		/* decrement node count */
4164 		OSAddAtomic(-1, &nfsrv_user_stat_node_count);
4165 	}
4166 	ulist->node_count = 0;
4167 
4168 	lck_mtx_destroy(&ulist->user_mutex, &nfsrv_active_user_mutex_group);
4169 }
4170 
4171 /* Reclaim old expired user nodes from active user lists. */
4172 void
nfsrv_active_user_list_reclaim(void)4173 nfsrv_active_user_list_reclaim(void)
4174 {
4175 	struct nfs_exportfs                     *nxfs;
4176 	struct nfs_export                       *nx;
4177 	struct nfs_active_user_list             *ulist;
4178 	struct nfs_user_stat_hashtbl_head       oldlist;
4179 	struct nfs_user_stat_node               *unode, *unode_next;
4180 	struct timeval                          now;
4181 	long                                    tstale;
4182 
4183 	LIST_INIT(&oldlist);
4184 
4185 	lck_rw_lock_shared(&nfsrv_export_rwlock);
4186 	microtime(&now);
4187 	tstale = now.tv_sec - nfsrv_user_stat_max_idle_sec;
4188 	LIST_FOREACH(nxfs, &nfsrv_exports, nxfs_next) {
4189 		LIST_FOREACH(nx, &nxfs->nxfs_exports, nx_next) {
4190 			/* Scan through all user nodes of this export */
4191 			ulist = &nx->nx_user_list;
4192 			lck_mtx_lock(&ulist->user_mutex);
4193 			for (unode = TAILQ_FIRST(&ulist->user_lru); unode; unode = unode_next) {
4194 				unode_next = TAILQ_NEXT(unode, lru_link);
4195 
4196 				/* check if this node has expired */
4197 				if (unode->tm_last >= tstale) {
4198 					break;
4199 				}
4200 
4201 				/* Remove node from the active user list */
4202 				TAILQ_REMOVE(&ulist->user_lru, unode, lru_link);
4203 				LIST_REMOVE(unode, hash_link);
4204 
4205 				/* Add node to temp list */
4206 				LIST_INSERT_HEAD(&oldlist, unode, hash_link);
4207 
4208 				/* decrement node count */
4209 				OSAddAtomic(-1, &nfsrv_user_stat_node_count);
4210 				ulist->node_count--;
4211 			}
4212 			/* can unlock this export's list now */
4213 			lck_mtx_unlock(&ulist->user_mutex);
4214 		}
4215 	}
4216 	lck_rw_done(&nfsrv_export_rwlock);
4217 
4218 	/* Free expired nodes */
4219 	while ((unode = LIST_FIRST(&oldlist))) {
4220 		LIST_REMOVE(unode, hash_link);
4221 		kfree_type(struct nfs_user_stat_node, unode);
4222 	}
4223 }
4224 
4225 /*
4226  * Maps errno values to nfs error numbers.
4227  * Use NFSERR_IO as the catch all for ones not specifically defined in
4228  * RFC 1094.
4229  */
4230 static u_char nfsrv_v2errmap[] = {
4231 	NFSERR_PERM, NFSERR_NOENT, NFSERR_IO, NFSERR_IO, NFSERR_IO,
4232 	NFSERR_NXIO, NFSERR_IO, NFSERR_IO, NFSERR_IO, NFSERR_IO,
4233 	NFSERR_IO, NFSERR_IO, NFSERR_ACCES, NFSERR_IO, NFSERR_IO,
4234 	NFSERR_IO, NFSERR_EXIST, NFSERR_IO, NFSERR_NODEV, NFSERR_NOTDIR,
4235 	NFSERR_ISDIR, NFSERR_IO, NFSERR_IO, NFSERR_IO, NFSERR_IO,
4236 	NFSERR_IO, NFSERR_FBIG, NFSERR_NOSPC, NFSERR_IO, NFSERR_ROFS,
4237 	NFSERR_IO, NFSERR_IO, NFSERR_IO, NFSERR_IO, NFSERR_IO,
4238 	NFSERR_IO, NFSERR_IO, NFSERR_IO, NFSERR_IO, NFSERR_IO,
4239 	NFSERR_IO, NFSERR_IO, NFSERR_IO, NFSERR_IO, NFSERR_IO,
4240 	NFSERR_IO, NFSERR_IO, NFSERR_IO, NFSERR_IO, NFSERR_IO,
4241 	NFSERR_IO, NFSERR_IO, NFSERR_IO, NFSERR_IO, NFSERR_IO,
4242 	NFSERR_IO, NFSERR_IO, NFSERR_IO, NFSERR_IO, NFSERR_IO,
4243 	NFSERR_IO, NFSERR_IO, NFSERR_NAMETOL, NFSERR_IO, NFSERR_IO,
4244 	NFSERR_NOTEMPTY, NFSERR_IO, NFSERR_IO, NFSERR_DQUOT, NFSERR_STALE,
4245 };
4246 
4247 /*
4248  * Maps errno values to nfs error numbers.
4249  * Although it is not obvious whether or not NFS clients really care if
4250  * a returned error value is in the specified list for the procedure, the
4251  * safest thing to do is filter them appropriately. For Version 2, the
4252  * X/Open XNFS document is the only specification that defines error values
4253  * for each RPC (The RFC simply lists all possible error values for all RPCs),
4254  * so I have decided to not do this for Version 2.
4255  * The first entry is the default error return and the rest are the valid
4256  * errors for that RPC in increasing numeric order.
4257  */
4258 static short nfsv3err_null[] = {
4259 	0,
4260 	0,
4261 };
4262 
4263 static short nfsv3err_getattr[] = {
4264 	NFSERR_IO,
4265 	NFSERR_IO,
4266 	NFSERR_STALE,
4267 	NFSERR_BADHANDLE,
4268 	NFSERR_SERVERFAULT,
4269 	NFSERR_TRYLATER,
4270 	0,
4271 };
4272 
4273 static short nfsv3err_setattr[] = {
4274 	NFSERR_IO,
4275 	NFSERR_PERM,
4276 	NFSERR_IO,
4277 	NFSERR_ACCES,
4278 	NFSERR_INVAL,
4279 	NFSERR_NOSPC,
4280 	NFSERR_ROFS,
4281 	NFSERR_DQUOT,
4282 	NFSERR_STALE,
4283 	NFSERR_BADHANDLE,
4284 	NFSERR_NOT_SYNC,
4285 	NFSERR_SERVERFAULT,
4286 	NFSERR_TRYLATER,
4287 	0,
4288 };
4289 
4290 static short nfsv3err_lookup[] = {
4291 	NFSERR_IO,
4292 	NFSERR_NOENT,
4293 	NFSERR_IO,
4294 	NFSERR_ACCES,
4295 	NFSERR_NOTDIR,
4296 	NFSERR_NAMETOL,
4297 	NFSERR_STALE,
4298 	NFSERR_BADHANDLE,
4299 	NFSERR_SERVERFAULT,
4300 	NFSERR_TRYLATER,
4301 	0,
4302 };
4303 
4304 static short nfsv3err_access[] = {
4305 	NFSERR_IO,
4306 	NFSERR_IO,
4307 	NFSERR_STALE,
4308 	NFSERR_BADHANDLE,
4309 	NFSERR_SERVERFAULT,
4310 	NFSERR_TRYLATER,
4311 	0,
4312 };
4313 
4314 static short nfsv3err_readlink[] = {
4315 	NFSERR_IO,
4316 	NFSERR_IO,
4317 	NFSERR_ACCES,
4318 	NFSERR_INVAL,
4319 	NFSERR_STALE,
4320 	NFSERR_BADHANDLE,
4321 	NFSERR_NOTSUPP,
4322 	NFSERR_SERVERFAULT,
4323 	NFSERR_TRYLATER,
4324 	0,
4325 };
4326 
4327 static short nfsv3err_read[] = {
4328 	NFSERR_IO,
4329 	NFSERR_IO,
4330 	NFSERR_NXIO,
4331 	NFSERR_ACCES,
4332 	NFSERR_INVAL,
4333 	NFSERR_STALE,
4334 	NFSERR_BADHANDLE,
4335 	NFSERR_SERVERFAULT,
4336 	NFSERR_TRYLATER,
4337 	0,
4338 };
4339 
4340 static short nfsv3err_write[] = {
4341 	NFSERR_IO,
4342 	NFSERR_IO,
4343 	NFSERR_ACCES,
4344 	NFSERR_INVAL,
4345 	NFSERR_FBIG,
4346 	NFSERR_NOSPC,
4347 	NFSERR_ROFS,
4348 	NFSERR_DQUOT,
4349 	NFSERR_STALE,
4350 	NFSERR_BADHANDLE,
4351 	NFSERR_SERVERFAULT,
4352 	NFSERR_TRYLATER,
4353 	0,
4354 };
4355 
4356 static short nfsv3err_create[] = {
4357 	NFSERR_IO,
4358 	NFSERR_IO,
4359 	NFSERR_ACCES,
4360 	NFSERR_EXIST,
4361 	NFSERR_NOTDIR,
4362 	NFSERR_NOSPC,
4363 	NFSERR_ROFS,
4364 	NFSERR_NAMETOL,
4365 	NFSERR_DQUOT,
4366 	NFSERR_STALE,
4367 	NFSERR_BADHANDLE,
4368 	NFSERR_NOTSUPP,
4369 	NFSERR_SERVERFAULT,
4370 	NFSERR_TRYLATER,
4371 	0,
4372 };
4373 
4374 static short nfsv3err_mkdir[] = {
4375 	NFSERR_IO,
4376 	NFSERR_IO,
4377 	NFSERR_ACCES,
4378 	NFSERR_EXIST,
4379 	NFSERR_NOTDIR,
4380 	NFSERR_NOSPC,
4381 	NFSERR_ROFS,
4382 	NFSERR_NAMETOL,
4383 	NFSERR_DQUOT,
4384 	NFSERR_STALE,
4385 	NFSERR_BADHANDLE,
4386 	NFSERR_NOTSUPP,
4387 	NFSERR_SERVERFAULT,
4388 	NFSERR_TRYLATER,
4389 	0,
4390 };
4391 
4392 static short nfsv3err_symlink[] = {
4393 	NFSERR_IO,
4394 	NFSERR_IO,
4395 	NFSERR_ACCES,
4396 	NFSERR_EXIST,
4397 	NFSERR_NOTDIR,
4398 	NFSERR_NOSPC,
4399 	NFSERR_ROFS,
4400 	NFSERR_NAMETOL,
4401 	NFSERR_DQUOT,
4402 	NFSERR_STALE,
4403 	NFSERR_BADHANDLE,
4404 	NFSERR_NOTSUPP,
4405 	NFSERR_SERVERFAULT,
4406 	NFSERR_TRYLATER,
4407 	0,
4408 };
4409 
4410 static short nfsv3err_mknod[] = {
4411 	NFSERR_IO,
4412 	NFSERR_IO,
4413 	NFSERR_ACCES,
4414 	NFSERR_EXIST,
4415 	NFSERR_NOTDIR,
4416 	NFSERR_NOSPC,
4417 	NFSERR_ROFS,
4418 	NFSERR_NAMETOL,
4419 	NFSERR_DQUOT,
4420 	NFSERR_STALE,
4421 	NFSERR_BADHANDLE,
4422 	NFSERR_NOTSUPP,
4423 	NFSERR_SERVERFAULT,
4424 	NFSERR_BADTYPE,
4425 	NFSERR_TRYLATER,
4426 	0,
4427 };
4428 
4429 static short nfsv3err_remove[] = {
4430 	NFSERR_IO,
4431 	NFSERR_NOENT,
4432 	NFSERR_IO,
4433 	NFSERR_ACCES,
4434 	NFSERR_NOTDIR,
4435 	NFSERR_ROFS,
4436 	NFSERR_NAMETOL,
4437 	NFSERR_STALE,
4438 	NFSERR_BADHANDLE,
4439 	NFSERR_SERVERFAULT,
4440 	NFSERR_TRYLATER,
4441 	0,
4442 };
4443 
4444 static short nfsv3err_rmdir[] = {
4445 	NFSERR_IO,
4446 	NFSERR_NOENT,
4447 	NFSERR_IO,
4448 	NFSERR_ACCES,
4449 	NFSERR_EXIST,
4450 	NFSERR_NOTDIR,
4451 	NFSERR_INVAL,
4452 	NFSERR_ROFS,
4453 	NFSERR_NAMETOL,
4454 	NFSERR_NOTEMPTY,
4455 	NFSERR_STALE,
4456 	NFSERR_BADHANDLE,
4457 	NFSERR_NOTSUPP,
4458 	NFSERR_SERVERFAULT,
4459 	NFSERR_TRYLATER,
4460 	0,
4461 };
4462 
4463 static short nfsv3err_rename[] = {
4464 	NFSERR_IO,
4465 	NFSERR_NOENT,
4466 	NFSERR_IO,
4467 	NFSERR_ACCES,
4468 	NFSERR_EXIST,
4469 	NFSERR_XDEV,
4470 	NFSERR_NOTDIR,
4471 	NFSERR_ISDIR,
4472 	NFSERR_INVAL,
4473 	NFSERR_NOSPC,
4474 	NFSERR_ROFS,
4475 	NFSERR_MLINK,
4476 	NFSERR_NAMETOL,
4477 	NFSERR_NOTEMPTY,
4478 	NFSERR_DQUOT,
4479 	NFSERR_STALE,
4480 	NFSERR_BADHANDLE,
4481 	NFSERR_NOTSUPP,
4482 	NFSERR_SERVERFAULT,
4483 	NFSERR_TRYLATER,
4484 	0,
4485 };
4486 
4487 static short nfsv3err_link[] = {
4488 	NFSERR_IO,
4489 	NFSERR_IO,
4490 	NFSERR_ACCES,
4491 	NFSERR_EXIST,
4492 	NFSERR_XDEV,
4493 	NFSERR_NOTDIR,
4494 	NFSERR_INVAL,
4495 	NFSERR_NOSPC,
4496 	NFSERR_ROFS,
4497 	NFSERR_MLINK,
4498 	NFSERR_NAMETOL,
4499 	NFSERR_DQUOT,
4500 	NFSERR_STALE,
4501 	NFSERR_BADHANDLE,
4502 	NFSERR_NOTSUPP,
4503 	NFSERR_SERVERFAULT,
4504 	NFSERR_TRYLATER,
4505 	0,
4506 };
4507 
4508 static short nfsv3err_readdir[] = {
4509 	NFSERR_IO,
4510 	NFSERR_IO,
4511 	NFSERR_ACCES,
4512 	NFSERR_NOTDIR,
4513 	NFSERR_STALE,
4514 	NFSERR_BADHANDLE,
4515 	NFSERR_BAD_COOKIE,
4516 	NFSERR_TOOSMALL,
4517 	NFSERR_SERVERFAULT,
4518 	NFSERR_TRYLATER,
4519 	0,
4520 };
4521 
4522 static short nfsv3err_readdirplus[] = {
4523 	NFSERR_IO,
4524 	NFSERR_IO,
4525 	NFSERR_ACCES,
4526 	NFSERR_NOTDIR,
4527 	NFSERR_STALE,
4528 	NFSERR_BADHANDLE,
4529 	NFSERR_BAD_COOKIE,
4530 	NFSERR_NOTSUPP,
4531 	NFSERR_TOOSMALL,
4532 	NFSERR_SERVERFAULT,
4533 	NFSERR_TRYLATER,
4534 	0,
4535 };
4536 
4537 static short nfsv3err_fsstat[] = {
4538 	NFSERR_IO,
4539 	NFSERR_IO,
4540 	NFSERR_STALE,
4541 	NFSERR_BADHANDLE,
4542 	NFSERR_SERVERFAULT,
4543 	NFSERR_TRYLATER,
4544 	0,
4545 };
4546 
4547 static short nfsv3err_fsinfo[] = {
4548 	NFSERR_STALE,
4549 	NFSERR_STALE,
4550 	NFSERR_BADHANDLE,
4551 	NFSERR_SERVERFAULT,
4552 	NFSERR_TRYLATER,
4553 	0,
4554 };
4555 
4556 static short nfsv3err_pathconf[] = {
4557 	NFSERR_STALE,
4558 	NFSERR_STALE,
4559 	NFSERR_BADHANDLE,
4560 	NFSERR_SERVERFAULT,
4561 	NFSERR_TRYLATER,
4562 	0,
4563 };
4564 
4565 static short nfsv3err_commit[] = {
4566 	NFSERR_IO,
4567 	NFSERR_IO,
4568 	NFSERR_STALE,
4569 	NFSERR_BADHANDLE,
4570 	NFSERR_SERVERFAULT,
4571 	NFSERR_TRYLATER,
4572 	0,
4573 };
4574 
4575 static short *nfsrv_v3errmap[] = {
4576 	nfsv3err_null,
4577 	nfsv3err_getattr,
4578 	nfsv3err_setattr,
4579 	nfsv3err_lookup,
4580 	nfsv3err_access,
4581 	nfsv3err_readlink,
4582 	nfsv3err_read,
4583 	nfsv3err_write,
4584 	nfsv3err_create,
4585 	nfsv3err_mkdir,
4586 	nfsv3err_symlink,
4587 	nfsv3err_mknod,
4588 	nfsv3err_remove,
4589 	nfsv3err_rmdir,
4590 	nfsv3err_rename,
4591 	nfsv3err_link,
4592 	nfsv3err_readdir,
4593 	nfsv3err_readdirplus,
4594 	nfsv3err_fsstat,
4595 	nfsv3err_fsinfo,
4596 	nfsv3err_pathconf,
4597 	nfsv3err_commit,
4598 };
4599 
4600 /*
4601  * Map errnos to NFS error numbers. For Version 3 also filter out error
4602  * numbers not specified for the associated procedure.
4603  */
4604 int
nfsrv_errmap(struct nfsrv_descript * nd,int err)4605 nfsrv_errmap(struct nfsrv_descript *nd, int err)
4606 {
4607 	short *defaulterrp, *errp;
4608 
4609 	if (nd->nd_vers == NFS_VER2) {
4610 		if (err <= (int)sizeof(nfsrv_v2errmap)) {
4611 			return (int)nfsrv_v2errmap[err - 1];
4612 		}
4613 		return NFSERR_IO;
4614 	}
4615 	/* NFSv3 */
4616 	if (nd->nd_procnum > NFSPROC_COMMIT) {
4617 		return err & 0xffff;
4618 	}
4619 	errp = defaulterrp = nfsrv_v3errmap[nd->nd_procnum];
4620 	while (*++errp) {
4621 		if (*errp == err) {
4622 			return err;
4623 		} else if (*errp > err) {
4624 			break;
4625 		}
4626 	}
4627 	return (int)*defaulterrp;
4628 }
4629 
4630 #endif /* CONFIG_NFS_SERVER */
4631 
4632 #endif /* CONFIG_NFS */
4633