xref: /freebsd/sys/kern/kern_descrip.c (revision ef9ffb8594eee294334ced627755bf5b46b48f9f)
1 /*-
2  * SPDX-License-Identifier: BSD-3-Clause
3  *
4  * Copyright (c) 1982, 1986, 1989, 1991, 1993
5  *	The Regents of the University of California.  All rights reserved.
6  * (c) UNIX System Laboratories, Inc.
7  * All or some portions of this file are derived from material licensed
8  * to the University of California by American Telephone and Telegraph
9  * Co. or Unix System Laboratories, Inc. and are reproduced herein with
10  * the permission of UNIX System Laboratories, Inc.
11  *
12  * Redistribution and use in source and binary forms, with or without
13  * modification, are permitted provided that the following conditions
14  * are met:
15  * 1. Redistributions of source code must retain the above copyright
16  *    notice, this list of conditions and the following disclaimer.
17  * 2. Redistributions in binary form must reproduce the above copyright
18  *    notice, this list of conditions and the following disclaimer in the
19  *    documentation and/or other materials provided with the distribution.
20  * 3. Neither the name of the University nor the names of its contributors
21  *    may be used to endorse or promote products derived from this software
22  *    without specific prior written permission.
23  *
24  * THIS SOFTWARE IS PROVIDED BY THE REGENTS AND CONTRIBUTORS ``AS IS'' AND
25  * ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
26  * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE
27  * ARE DISCLAIMED.  IN NO EVENT SHALL THE REGENTS OR CONTRIBUTORS BE LIABLE
28  * FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL
29  * DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS
30  * OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION)
31  * HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT
32  * LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY
33  * OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF
34  * SUCH DAMAGE.
35  */
36 
37 #include <sys/cdefs.h>
38 #include "opt_capsicum.h"
39 #include "opt_ddb.h"
40 #include "opt_ktrace.h"
41 
42 #include <sys/param.h>
43 #include <sys/systm.h>
44 
45 #include <sys/capsicum.h>
46 #include <sys/conf.h>
47 #include <sys/fcntl.h>
48 #include <sys/file.h>
49 #include <sys/filedesc.h>
50 #include <sys/filio.h>
51 #include <sys/jail.h>
52 #include <sys/kernel.h>
53 #include <sys/limits.h>
54 #include <sys/lock.h>
55 #include <sys/malloc.h>
56 #include <sys/mount.h>
57 #include <sys/mutex.h>
58 #include <sys/namei.h>
59 #include <sys/selinfo.h>
60 #include <sys/poll.h>
61 #include <sys/priv.h>
62 #include <sys/proc.h>
63 #include <sys/protosw.h>
64 #include <sys/racct.h>
65 #include <sys/resourcevar.h>
66 #include <sys/sbuf.h>
67 #include <sys/signalvar.h>
68 #include <sys/kdb.h>
69 #include <sys/smr.h>
70 #include <sys/stat.h>
71 #include <sys/sx.h>
72 #include <sys/syscallsubr.h>
73 #include <sys/sysctl.h>
74 #include <sys/sysproto.h>
75 #include <sys/unistd.h>
76 #include <sys/user.h>
77 #include <sys/vnode.h>
78 #include <sys/ktrace.h>
79 
80 #include <net/vnet.h>
81 
82 #include <security/audit/audit.h>
83 
84 #include <vm/uma.h>
85 #include <vm/vm.h>
86 
87 #include <ddb/ddb.h>
88 
89 static MALLOC_DEFINE(M_FILEDESC, "filedesc", "Open file descriptor table");
90 static MALLOC_DEFINE(M_PWD, "pwd", "Descriptor table vnodes");
91 static MALLOC_DEFINE(M_PWDDESC, "pwddesc", "Pwd descriptors");
92 static MALLOC_DEFINE(M_FILEDESC_TO_LEADER, "filedesc_to_leader",
93     "file desc to leader structures");
94 static MALLOC_DEFINE(M_SIGIO, "sigio", "sigio structures");
95 MALLOC_DEFINE(M_FILECAPS, "filecaps", "descriptor capabilities");
96 
97 MALLOC_DECLARE(M_FADVISE);
98 
99 static __read_mostly uma_zone_t file_zone;
100 static __read_mostly uma_zone_t filedesc0_zone;
101 __read_mostly uma_zone_t pwd_zone;
102 VFS_SMR_DECLARE;
103 
104 static int	closefp(struct filedesc *fdp, int fd, struct file *fp,
105 		    struct thread *td, bool holdleaders, bool audit);
106 static void	export_file_to_kinfo(struct file *fp, int fd,
107 		    cap_rights_t *rightsp, struct kinfo_file *kif,
108 		    struct filedesc *fdp, int flags);
109 static int	fd_first_free(struct filedesc *fdp, int low, int size);
110 static void	fdgrowtable(struct filedesc *fdp, int nfd);
111 static void	fdgrowtable_exp(struct filedesc *fdp, int nfd);
112 static void	fdunused(struct filedesc *fdp, int fd);
113 static void	fdused(struct filedesc *fdp, int fd);
114 static int	fget_unlocked_seq(struct thread *td, int fd,
115 		    cap_rights_t *needrightsp, struct file **fpp, seqc_t *seqp);
116 static int	getmaxfd(struct thread *td);
117 static u_long	*filecaps_copy_prep(const struct filecaps *src);
118 static void	filecaps_copy_finish(const struct filecaps *src,
119 		    struct filecaps *dst, u_long *ioctls);
120 static u_long 	*filecaps_free_prep(struct filecaps *fcaps);
121 static void	filecaps_free_finish(u_long *ioctls);
122 
123 static struct pwd *pwd_alloc(void);
124 
125 /*
126  * Each process has:
127  *
128  * - An array of open file descriptors (fd_ofiles)
129  * - An array of file flags (fd_ofileflags)
130  * - A bitmap recording which descriptors are in use (fd_map)
131  *
132  * A process starts out with NDFILE descriptors.  The value of NDFILE has
133  * been selected based the historical limit of 20 open files, and an
134  * assumption that the majority of processes, especially short-lived
135  * processes like shells, will never need more.
136  *
137  * If this initial allocation is exhausted, a larger descriptor table and
138  * map are allocated dynamically, and the pointers in the process's struct
139  * filedesc are updated to point to those.  This is repeated every time
140  * the process runs out of file descriptors (provided it hasn't hit its
141  * resource limit).
142  *
143  * Since threads may hold references to individual descriptor table
144  * entries, the tables are never freed.  Instead, they are placed on a
145  * linked list and freed only when the struct filedesc is released.
146  */
147 #define NDFILE		20
148 #define NDSLOTSIZE	sizeof(NDSLOTTYPE)
149 #define	NDENTRIES	(NDSLOTSIZE * __CHAR_BIT)
150 #define NDSLOT(x)	((x) / NDENTRIES)
151 #define NDBIT(x)	((NDSLOTTYPE)1 << ((x) % NDENTRIES))
152 #define	NDSLOTS(x)	(((x) + NDENTRIES - 1) / NDENTRIES)
153 
154 #define	FILEDESC_FOREACH_FDE(fdp, _iterator, _fde)				\
155 	struct filedesc *_fdp = (fdp);						\
156 	int _lastfile = fdlastfile_single(_fdp);				\
157 	for (_iterator = 0; _iterator <= _lastfile; _iterator++)		\
158 		if ((_fde = &_fdp->fd_ofiles[_iterator])->fde_file != NULL)
159 
160 #define	FILEDESC_FOREACH_FP(fdp, _iterator, _fp)				\
161 	struct filedesc *_fdp = (fdp);						\
162 	int _lastfile = fdlastfile_single(_fdp);				\
163 	for (_iterator = 0; _iterator <= _lastfile; _iterator++)		\
164 		if ((_fp = _fdp->fd_ofiles[_iterator].fde_file) != NULL)
165 
166 /*
167  * SLIST entry used to keep track of ofiles which must be reclaimed when
168  * the process exits.
169  */
170 struct freetable {
171 	struct fdescenttbl *ft_table;
172 	SLIST_ENTRY(freetable) ft_next;
173 };
174 
175 /*
176  * Initial allocation: a filedesc structure + the head of SLIST used to
177  * keep track of old ofiles + enough space for NDFILE descriptors.
178  */
179 
180 struct fdescenttbl0 {
181 	int	fdt_nfiles;
182 	struct	filedescent fdt_ofiles[NDFILE];
183 };
184 
185 struct filedesc0 {
186 	struct filedesc fd_fd;
187 	SLIST_HEAD(, freetable) fd_free;
188 	struct	fdescenttbl0 fd_dfiles;
189 	NDSLOTTYPE fd_dmap[NDSLOTS(NDFILE)];
190 };
191 
192 /*
193  * Descriptor management.
194  */
195 static int __exclusive_cache_line openfiles; /* actual number of open files */
196 struct mtx sigio_lock;		/* mtx to protect pointers to sigio */
197 void __read_mostly (*mq_fdclose)(struct thread *td, int fd, struct file *fp);
198 
199 /*
200  * If low >= size, just return low. Otherwise find the first zero bit in the
201  * given bitmap, starting at low and not exceeding size - 1. Return size if
202  * not found.
203  */
204 static int
fd_first_free(struct filedesc * fdp,int low,int size)205 fd_first_free(struct filedesc *fdp, int low, int size)
206 {
207 	NDSLOTTYPE *map = fdp->fd_map;
208 	NDSLOTTYPE mask;
209 	int off, maxoff;
210 
211 	if (low >= size)
212 		return (low);
213 
214 	off = NDSLOT(low);
215 	if (low % NDENTRIES) {
216 		mask = ~(~(NDSLOTTYPE)0 >> (NDENTRIES - (low % NDENTRIES)));
217 		if ((mask &= ~map[off]) != 0UL)
218 			return (off * NDENTRIES + ffsl(mask) - 1);
219 		++off;
220 	}
221 	for (maxoff = NDSLOTS(size); off < maxoff; ++off)
222 		if (map[off] != ~0UL)
223 			return (off * NDENTRIES + ffsl(~map[off]) - 1);
224 	return (size);
225 }
226 
227 /*
228  * Find the last used fd.
229  *
230  * Call this variant if fdp can't be modified by anyone else (e.g, during exec).
231  * Otherwise use fdlastfile.
232  */
233 int
fdlastfile_single(struct filedesc * fdp)234 fdlastfile_single(struct filedesc *fdp)
235 {
236 	NDSLOTTYPE *map = fdp->fd_map;
237 	int off, minoff;
238 
239 	off = NDSLOT(fdp->fd_nfiles - 1);
240 	for (minoff = NDSLOT(0); off >= minoff; --off)
241 		if (map[off] != 0)
242 			return (off * NDENTRIES + flsl(map[off]) - 1);
243 	return (-1);
244 }
245 
246 int
fdlastfile(struct filedesc * fdp)247 fdlastfile(struct filedesc *fdp)
248 {
249 
250 	FILEDESC_LOCK_ASSERT(fdp);
251 	return (fdlastfile_single(fdp));
252 }
253 
254 static int
fdisused(struct filedesc * fdp,int fd)255 fdisused(struct filedesc *fdp, int fd)
256 {
257 
258 	KASSERT(fd >= 0 && fd < fdp->fd_nfiles,
259 	    ("file descriptor %d out of range (0, %d)", fd, fdp->fd_nfiles));
260 
261 	return ((fdp->fd_map[NDSLOT(fd)] & NDBIT(fd)) != 0);
262 }
263 
264 /*
265  * Mark a file descriptor as used.
266  */
267 static void
fdused_init(struct filedesc * fdp,int fd)268 fdused_init(struct filedesc *fdp, int fd)
269 {
270 
271 	KASSERT(!fdisused(fdp, fd), ("fd=%d is already used", fd));
272 
273 	fdp->fd_map[NDSLOT(fd)] |= NDBIT(fd);
274 }
275 
276 static void
fdused(struct filedesc * fdp,int fd)277 fdused(struct filedesc *fdp, int fd)
278 {
279 
280 	FILEDESC_XLOCK_ASSERT(fdp);
281 
282 	fdused_init(fdp, fd);
283 	if (fd == fdp->fd_freefile)
284 		fdp->fd_freefile++;
285 }
286 
287 /*
288  * Mark a file descriptor as unused.
289  */
290 static void
fdunused(struct filedesc * fdp,int fd)291 fdunused(struct filedesc *fdp, int fd)
292 {
293 
294 	FILEDESC_XLOCK_ASSERT(fdp);
295 
296 	KASSERT(fdisused(fdp, fd), ("fd=%d is already unused", fd));
297 	KASSERT(fdp->fd_ofiles[fd].fde_file == NULL,
298 	    ("fd=%d is still in use", fd));
299 
300 	fdp->fd_map[NDSLOT(fd)] &= ~NDBIT(fd);
301 	if (fd < fdp->fd_freefile)
302 		fdp->fd_freefile = fd;
303 }
304 
305 /*
306  * Free a file descriptor.
307  *
308  * Avoid some work if fdp is about to be destroyed.
309  */
310 static inline void
fdefree_last(struct filedescent * fde)311 fdefree_last(struct filedescent *fde)
312 {
313 
314 	filecaps_free(&fde->fde_caps);
315 }
316 
317 static inline void
fdfree(struct filedesc * fdp,int fd)318 fdfree(struct filedesc *fdp, int fd)
319 {
320 	struct filedescent *fde;
321 
322 	FILEDESC_XLOCK_ASSERT(fdp);
323 	fde = &fdp->fd_ofiles[fd];
324 #ifdef CAPABILITIES
325 	seqc_write_begin(&fde->fde_seqc);
326 #endif
327 	fde->fde_file = NULL;
328 #ifdef CAPABILITIES
329 	seqc_write_end(&fde->fde_seqc);
330 #endif
331 	fdefree_last(fde);
332 	fdunused(fdp, fd);
333 }
334 
335 /*
336  * System calls on descriptors.
337  */
338 #ifndef _SYS_SYSPROTO_H_
339 struct getdtablesize_args {
340 	int	dummy;
341 };
342 #endif
343 /* ARGSUSED */
344 int
sys_getdtablesize(struct thread * td,struct getdtablesize_args * uap)345 sys_getdtablesize(struct thread *td, struct getdtablesize_args *uap)
346 {
347 #ifdef	RACCT
348 	uint64_t lim;
349 #endif
350 
351 	td->td_retval[0] = getmaxfd(td);
352 #ifdef	RACCT
353 	PROC_LOCK(td->td_proc);
354 	lim = racct_get_limit(td->td_proc, RACCT_NOFILE);
355 	PROC_UNLOCK(td->td_proc);
356 	if (lim < td->td_retval[0])
357 		td->td_retval[0] = lim;
358 #endif
359 	return (0);
360 }
361 
362 /*
363  * Duplicate a file descriptor to a particular value.
364  *
365  * Note: keep in mind that a potential race condition exists when closing
366  * descriptors from a shared descriptor table (via rfork).
367  */
368 #ifndef _SYS_SYSPROTO_H_
369 struct dup2_args {
370 	u_int	from;
371 	u_int	to;
372 };
373 #endif
374 /* ARGSUSED */
375 int
sys_dup2(struct thread * td,struct dup2_args * uap)376 sys_dup2(struct thread *td, struct dup2_args *uap)
377 {
378 
379 	return (kern_dup(td, FDDUP_FIXED, 0, (int)uap->from, (int)uap->to));
380 }
381 
382 /*
383  * Duplicate a file descriptor.
384  */
385 #ifndef _SYS_SYSPROTO_H_
386 struct dup_args {
387 	u_int	fd;
388 };
389 #endif
390 /* ARGSUSED */
391 int
sys_dup(struct thread * td,struct dup_args * uap)392 sys_dup(struct thread *td, struct dup_args *uap)
393 {
394 
395 	return (kern_dup(td, FDDUP_NORMAL, 0, (int)uap->fd, 0));
396 }
397 
398 /*
399  * The file control system call.
400  */
401 #ifndef _SYS_SYSPROTO_H_
402 struct fcntl_args {
403 	int	fd;
404 	int	cmd;
405 	long	arg;
406 };
407 #endif
408 /* ARGSUSED */
409 int
sys_fcntl(struct thread * td,struct fcntl_args * uap)410 sys_fcntl(struct thread *td, struct fcntl_args *uap)
411 {
412 
413 	return (kern_fcntl_freebsd(td, uap->fd, uap->cmd, uap->arg));
414 }
415 
416 int
kern_fcntl_freebsd(struct thread * td,int fd,int cmd,intptr_t arg)417 kern_fcntl_freebsd(struct thread *td, int fd, int cmd, intptr_t arg)
418 {
419 	struct flock fl;
420 	struct __oflock ofl;
421 	intptr_t arg1;
422 	int error, newcmd;
423 
424 	error = 0;
425 	newcmd = cmd;
426 	switch (cmd) {
427 	case F_OGETLK:
428 	case F_OSETLK:
429 	case F_OSETLKW:
430 		/*
431 		 * Convert old flock structure to new.
432 		 */
433 		error = copyin((void *)arg, &ofl, sizeof(ofl));
434 		fl.l_start = ofl.l_start;
435 		fl.l_len = ofl.l_len;
436 		fl.l_pid = ofl.l_pid;
437 		fl.l_type = ofl.l_type;
438 		fl.l_whence = ofl.l_whence;
439 		fl.l_sysid = 0;
440 
441 		switch (cmd) {
442 		case F_OGETLK:
443 			newcmd = F_GETLK;
444 			break;
445 		case F_OSETLK:
446 			newcmd = F_SETLK;
447 			break;
448 		case F_OSETLKW:
449 			newcmd = F_SETLKW;
450 			break;
451 		}
452 		arg1 = (intptr_t)&fl;
453 		break;
454 	case F_GETLK:
455 	case F_SETLK:
456 	case F_SETLKW:
457 	case F_SETLK_REMOTE:
458 		error = copyin((void *)arg, &fl, sizeof(fl));
459 		arg1 = (intptr_t)&fl;
460 		break;
461 	default:
462 		arg1 = arg;
463 		break;
464 	}
465 	if (error)
466 		return (error);
467 	error = kern_fcntl(td, fd, newcmd, arg1);
468 	if (error)
469 		return (error);
470 	if (cmd == F_OGETLK) {
471 		ofl.l_start = fl.l_start;
472 		ofl.l_len = fl.l_len;
473 		ofl.l_pid = fl.l_pid;
474 		ofl.l_type = fl.l_type;
475 		ofl.l_whence = fl.l_whence;
476 		error = copyout(&ofl, (void *)arg, sizeof(ofl));
477 	} else if (cmd == F_GETLK) {
478 		error = copyout(&fl, (void *)arg, sizeof(fl));
479 	}
480 	return (error);
481 }
482 
483 int
kern_fcntl(struct thread * td,int fd,int cmd,intptr_t arg)484 kern_fcntl(struct thread *td, int fd, int cmd, intptr_t arg)
485 {
486 	struct filedesc *fdp;
487 	struct flock *flp;
488 	struct file *fp, *fp2;
489 	struct filedescent *fde;
490 	struct proc *p;
491 	struct vnode *vp;
492 	struct mount *mp;
493 	struct kinfo_file *kif;
494 	int error, flg, kif_sz, seals, tmp, got_set, got_cleared;
495 	uint64_t bsize;
496 	off_t foffset;
497 
498 	error = 0;
499 	flg = F_POSIX;
500 	p = td->td_proc;
501 	fdp = p->p_fd;
502 
503 	AUDIT_ARG_FD(cmd);
504 	AUDIT_ARG_CMD(cmd);
505 	switch (cmd) {
506 	case F_DUPFD:
507 		tmp = arg;
508 		error = kern_dup(td, FDDUP_FCNTL, 0, fd, tmp);
509 		break;
510 
511 	case F_DUPFD_CLOEXEC:
512 		tmp = arg;
513 		error = kern_dup(td, FDDUP_FCNTL, FDDUP_FLAG_CLOEXEC, fd, tmp);
514 		break;
515 
516 	case F_DUP2FD:
517 		tmp = arg;
518 		error = kern_dup(td, FDDUP_FIXED, 0, fd, tmp);
519 		break;
520 
521 	case F_DUP2FD_CLOEXEC:
522 		tmp = arg;
523 		error = kern_dup(td, FDDUP_FIXED, FDDUP_FLAG_CLOEXEC, fd, tmp);
524 		break;
525 
526 	case F_GETFD:
527 		error = EBADF;
528 		FILEDESC_SLOCK(fdp);
529 		fde = fdeget_noref(fdp, fd);
530 		if (fde != NULL) {
531 			td->td_retval[0] =
532 			    (fde->fde_flags & UF_EXCLOSE) ? FD_CLOEXEC : 0;
533 			error = 0;
534 		}
535 		FILEDESC_SUNLOCK(fdp);
536 		break;
537 
538 	case F_SETFD:
539 		error = EBADF;
540 		FILEDESC_XLOCK(fdp);
541 		fde = fdeget_noref(fdp, fd);
542 		if (fde != NULL) {
543 			fde->fde_flags = (fde->fde_flags & ~UF_EXCLOSE) |
544 			    (arg & FD_CLOEXEC ? UF_EXCLOSE : 0);
545 			error = 0;
546 		}
547 		FILEDESC_XUNLOCK(fdp);
548 		break;
549 
550 	case F_GETFL:
551 		error = fget_fcntl(td, fd, &cap_fcntl_rights, F_GETFL, &fp);
552 		if (error != 0)
553 			break;
554 		td->td_retval[0] = OFLAGS(fp->f_flag);
555 		fdrop(fp, td);
556 		break;
557 
558 	case F_SETFL:
559 		error = fget_fcntl(td, fd, &cap_fcntl_rights, F_SETFL, &fp);
560 		if (error != 0)
561 			break;
562 		if (fp->f_ops == &path_fileops) {
563 			fdrop(fp, td);
564 			error = EBADF;
565 			break;
566 		}
567 		do {
568 			tmp = flg = fp->f_flag;
569 			tmp &= ~FCNTLFLAGS;
570 			tmp |= FFLAGS(arg & ~O_ACCMODE) & FCNTLFLAGS;
571 		} while (atomic_cmpset_int(&fp->f_flag, flg, tmp) == 0);
572 		got_set = tmp & ~flg;
573 		got_cleared = flg & ~tmp;
574 		tmp = fp->f_flag & FNONBLOCK;
575 		error = fo_ioctl(fp, FIONBIO, &tmp, td->td_ucred, td);
576 		if (error != 0)
577 			goto revert_f_setfl;
578 		tmp = fp->f_flag & FASYNC;
579 		error = fo_ioctl(fp, FIOASYNC, &tmp, td->td_ucred, td);
580 		if (error == 0) {
581 			fdrop(fp, td);
582 			break;
583 		}
584 		atomic_clear_int(&fp->f_flag, FNONBLOCK);
585 		tmp = 0;
586 		(void)fo_ioctl(fp, FIONBIO, &tmp, td->td_ucred, td);
587 revert_f_setfl:
588 		do {
589 			tmp = flg = fp->f_flag;
590 			tmp &= ~FCNTLFLAGS;
591 			tmp |= got_cleared;
592 			tmp &= ~got_set;
593 		} while (atomic_cmpset_int(&fp->f_flag, flg, tmp) == 0);
594 		fdrop(fp, td);
595 		break;
596 
597 	case F_GETOWN:
598 		error = fget_fcntl(td, fd, &cap_fcntl_rights, F_GETOWN, &fp);
599 		if (error != 0)
600 			break;
601 		error = fo_ioctl(fp, FIOGETOWN, &tmp, td->td_ucred, td);
602 		if (error == 0)
603 			td->td_retval[0] = tmp;
604 		fdrop(fp, td);
605 		break;
606 
607 	case F_SETOWN:
608 		error = fget_fcntl(td, fd, &cap_fcntl_rights, F_SETOWN, &fp);
609 		if (error != 0)
610 			break;
611 		tmp = arg;
612 		error = fo_ioctl(fp, FIOSETOWN, &tmp, td->td_ucred, td);
613 		fdrop(fp, td);
614 		break;
615 
616 	case F_SETLK_REMOTE:
617 		error = priv_check(td, PRIV_NFS_LOCKD);
618 		if (error != 0)
619 			return (error);
620 		flg = F_REMOTE;
621 		goto do_setlk;
622 
623 	case F_SETLKW:
624 		flg |= F_WAIT;
625 		/* FALLTHROUGH F_SETLK */
626 
627 	case F_SETLK:
628 	do_setlk:
629 		flp = (struct flock *)arg;
630 		if ((flg & F_REMOTE) != 0 && flp->l_sysid == 0) {
631 			error = EINVAL;
632 			break;
633 		}
634 
635 		error = fget_unlocked(td, fd, &cap_flock_rights, &fp);
636 		if (error != 0)
637 			break;
638 		if (fp->f_type != DTYPE_VNODE || fp->f_ops == &path_fileops) {
639 			error = EBADF;
640 			fdrop(fp, td);
641 			break;
642 		}
643 
644 		if (flp->l_whence == SEEK_CUR) {
645 			foffset = foffset_get(fp);
646 			if (foffset < 0 ||
647 			    (flp->l_start > 0 &&
648 			     foffset > OFF_MAX - flp->l_start)) {
649 				error = EOVERFLOW;
650 				fdrop(fp, td);
651 				break;
652 			}
653 			flp->l_start += foffset;
654 		}
655 
656 		vp = fp->f_vnode;
657 		switch (flp->l_type) {
658 		case F_RDLCK:
659 			if ((fp->f_flag & FREAD) == 0) {
660 				error = EBADF;
661 				break;
662 			}
663 			if ((p->p_leader->p_flag & P_ADVLOCK) == 0) {
664 				PROC_LOCK(p->p_leader);
665 				p->p_leader->p_flag |= P_ADVLOCK;
666 				PROC_UNLOCK(p->p_leader);
667 			}
668 			error = VOP_ADVLOCK(vp, (caddr_t)p->p_leader, F_SETLK,
669 			    flp, flg);
670 			break;
671 		case F_WRLCK:
672 			if ((fp->f_flag & FWRITE) == 0) {
673 				error = EBADF;
674 				break;
675 			}
676 			if ((p->p_leader->p_flag & P_ADVLOCK) == 0) {
677 				PROC_LOCK(p->p_leader);
678 				p->p_leader->p_flag |= P_ADVLOCK;
679 				PROC_UNLOCK(p->p_leader);
680 			}
681 			error = VOP_ADVLOCK(vp, (caddr_t)p->p_leader, F_SETLK,
682 			    flp, flg);
683 			break;
684 		case F_UNLCK:
685 			error = VOP_ADVLOCK(vp, (caddr_t)p->p_leader, F_UNLCK,
686 			    flp, flg);
687 			break;
688 		case F_UNLCKSYS:
689 			if (flg != F_REMOTE) {
690 				error = EINVAL;
691 				break;
692 			}
693 			error = VOP_ADVLOCK(vp, (caddr_t)p->p_leader,
694 			    F_UNLCKSYS, flp, flg);
695 			break;
696 		default:
697 			error = EINVAL;
698 			break;
699 		}
700 		if (error != 0 || flp->l_type == F_UNLCK ||
701 		    flp->l_type == F_UNLCKSYS) {
702 			fdrop(fp, td);
703 			break;
704 		}
705 
706 		/*
707 		 * Check for a race with close.
708 		 *
709 		 * The vnode is now advisory locked (or unlocked, but this case
710 		 * is not really important) as the caller requested.
711 		 * We had to drop the filedesc lock, so we need to recheck if
712 		 * the descriptor is still valid, because if it was closed
713 		 * in the meantime we need to remove advisory lock from the
714 		 * vnode - close on any descriptor leading to an advisory
715 		 * locked vnode, removes that lock.
716 		 * We will return 0 on purpose in that case, as the result of
717 		 * successful advisory lock might have been externally visible
718 		 * already. This is fine - effectively we pretend to the caller
719 		 * that the closing thread was a bit slower and that the
720 		 * advisory lock succeeded before the close.
721 		 */
722 		error = fget_unlocked(td, fd, &cap_no_rights, &fp2);
723 		if (error != 0) {
724 			fdrop(fp, td);
725 			break;
726 		}
727 		if (fp != fp2) {
728 			flp->l_whence = SEEK_SET;
729 			flp->l_start = 0;
730 			flp->l_len = 0;
731 			flp->l_type = F_UNLCK;
732 			(void) VOP_ADVLOCK(vp, (caddr_t)p->p_leader,
733 			    F_UNLCK, flp, F_POSIX);
734 		}
735 		fdrop(fp, td);
736 		fdrop(fp2, td);
737 		break;
738 
739 	case F_GETLK:
740 		error = fget_unlocked(td, fd, &cap_flock_rights, &fp);
741 		if (error != 0)
742 			break;
743 		if (fp->f_type != DTYPE_VNODE || fp->f_ops == &path_fileops) {
744 			error = EBADF;
745 			fdrop(fp, td);
746 			break;
747 		}
748 		flp = (struct flock *)arg;
749 		if (flp->l_type != F_RDLCK && flp->l_type != F_WRLCK &&
750 		    flp->l_type != F_UNLCK) {
751 			error = EINVAL;
752 			fdrop(fp, td);
753 			break;
754 		}
755 		if (flp->l_whence == SEEK_CUR) {
756 			foffset = foffset_get(fp);
757 			if ((flp->l_start > 0 &&
758 			    foffset > OFF_MAX - flp->l_start) ||
759 			    (flp->l_start < 0 &&
760 			    foffset < OFF_MIN - flp->l_start)) {
761 				error = EOVERFLOW;
762 				fdrop(fp, td);
763 				break;
764 			}
765 			flp->l_start += foffset;
766 		}
767 		vp = fp->f_vnode;
768 		error = VOP_ADVLOCK(vp, (caddr_t)p->p_leader, F_GETLK, flp,
769 		    F_POSIX);
770 		fdrop(fp, td);
771 		break;
772 
773 	case F_ADD_SEALS:
774 		error = fget_unlocked(td, fd, &cap_no_rights, &fp);
775 		if (error != 0)
776 			break;
777 		error = fo_add_seals(fp, arg);
778 		fdrop(fp, td);
779 		break;
780 
781 	case F_GET_SEALS:
782 		error = fget_unlocked(td, fd, &cap_no_rights, &fp);
783 		if (error != 0)
784 			break;
785 		if (fo_get_seals(fp, &seals) == 0)
786 			td->td_retval[0] = seals;
787 		else
788 			error = EINVAL;
789 		fdrop(fp, td);
790 		break;
791 
792 	case F_RDAHEAD:
793 		arg = arg ? 128 * 1024: 0;
794 		/* FALLTHROUGH */
795 	case F_READAHEAD:
796 		error = fget_unlocked(td, fd, &cap_no_rights, &fp);
797 		if (error != 0)
798 			break;
799 		if (fp->f_type != DTYPE_VNODE || fp->f_ops == &path_fileops) {
800 			fdrop(fp, td);
801 			error = EBADF;
802 			break;
803 		}
804 		vp = fp->f_vnode;
805 		if (vp->v_type != VREG) {
806 			fdrop(fp, td);
807 			error = ENOTTY;
808 			break;
809 		}
810 
811 		/*
812 		 * Exclusive lock synchronizes against f_seqcount reads and
813 		 * writes in sequential_heuristic().
814 		 */
815 		error = vn_lock(vp, LK_EXCLUSIVE);
816 		if (error != 0) {
817 			fdrop(fp, td);
818 			break;
819 		}
820 		if (arg >= 0) {
821 			bsize = fp->f_vnode->v_mount->mnt_stat.f_iosize;
822 			arg = MIN(arg, INT_MAX - bsize + 1);
823 			fp->f_seqcount[UIO_READ] = MIN(IO_SEQMAX,
824 			    (arg + bsize - 1) / bsize);
825 			atomic_set_int(&fp->f_flag, FRDAHEAD);
826 		} else {
827 			atomic_clear_int(&fp->f_flag, FRDAHEAD);
828 		}
829 		VOP_UNLOCK(vp);
830 		fdrop(fp, td);
831 		break;
832 
833 	case F_ISUNIONSTACK:
834 		/*
835 		 * Check if the vnode is part of a union stack (either the
836 		 * "union" flag from mount(2) or unionfs).
837 		 *
838 		 * Prior to introduction of this op libc's readdir would call
839 		 * fstatfs(2), in effect unnecessarily copying kilobytes of
840 		 * data just to check fs name and a mount flag.
841 		 *
842 		 * Fixing the code to handle everything in the kernel instead
843 		 * is a non-trivial endeavor and has low priority, thus this
844 		 * horrible kludge facilitates the current behavior in a much
845 		 * cheaper manner until someone(tm) sorts this out.
846 		 */
847 		error = fget_unlocked(td, fd, &cap_no_rights, &fp);
848 		if (error != 0)
849 			break;
850 		if (fp->f_type != DTYPE_VNODE) {
851 			fdrop(fp, td);
852 			error = EBADF;
853 			break;
854 		}
855 		vp = fp->f_vnode;
856 		/*
857 		 * Since we don't prevent dooming the vnode even non-null mp
858 		 * found can become immediately stale. This is tolerable since
859 		 * mount points are type-stable (providing safe memory access)
860 		 * and any vfs op on this vnode going forward will return an
861 		 * error (meaning return value in this case is meaningless).
862 		 */
863 		mp = atomic_load_ptr(&vp->v_mount);
864 		if (__predict_false(mp == NULL)) {
865 			fdrop(fp, td);
866 			error = EBADF;
867 			break;
868 		}
869 		td->td_retval[0] = 0;
870 		if (mp->mnt_kern_flag & MNTK_UNIONFS ||
871 		    mp->mnt_flag & MNT_UNION)
872 			td->td_retval[0] = 1;
873 		fdrop(fp, td);
874 		break;
875 
876 	case F_KINFO:
877 #ifdef CAPABILITY_MODE
878 		if (CAP_TRACING(td))
879 			ktrcapfail(CAPFAIL_SYSCALL, &cmd);
880 		if (IN_CAPABILITY_MODE(td)) {
881 			error = ECAPMODE;
882 			break;
883 		}
884 #endif
885 		error = copyin((void *)arg, &kif_sz, sizeof(kif_sz));
886 		if (error != 0)
887 			break;
888 		if (kif_sz != sizeof(*kif)) {
889 			error = EINVAL;
890 			break;
891 		}
892 		kif = malloc(sizeof(*kif), M_TEMP, M_WAITOK | M_ZERO);
893 		FILEDESC_SLOCK(fdp);
894 		error = fget_cap_noref(fdp, fd, &cap_fcntl_rights, &fp, NULL);
895 		if (error == 0 && fhold(fp)) {
896 			export_file_to_kinfo(fp, fd, NULL, kif, fdp, 0);
897 			FILEDESC_SUNLOCK(fdp);
898 			fdrop(fp, td);
899 			if ((kif->kf_status & KF_ATTR_VALID) != 0) {
900 				kif->kf_structsize = sizeof(*kif);
901 				error = copyout(kif, (void *)arg, sizeof(*kif));
902 			} else {
903 				error = EBADF;
904 			}
905 		} else {
906 			FILEDESC_SUNLOCK(fdp);
907 			if (error == 0)
908 				error = EBADF;
909 		}
910 		free(kif, M_TEMP);
911 		break;
912 
913 	default:
914 		error = EINVAL;
915 		break;
916 	}
917 	return (error);
918 }
919 
920 static int
getmaxfd(struct thread * td)921 getmaxfd(struct thread *td)
922 {
923 
924 	return (min((int)lim_cur(td, RLIMIT_NOFILE), maxfilesperproc));
925 }
926 
927 /*
928  * Common code for dup, dup2, fcntl(F_DUPFD) and fcntl(F_DUP2FD).
929  */
930 int
kern_dup(struct thread * td,u_int mode,int flags,int old,int new)931 kern_dup(struct thread *td, u_int mode, int flags, int old, int new)
932 {
933 	struct filedesc *fdp;
934 	struct filedescent *oldfde, *newfde;
935 	struct proc *p;
936 	struct file *delfp, *oldfp;
937 	u_long *oioctls, *nioctls;
938 	int error, maxfd;
939 
940 	p = td->td_proc;
941 	fdp = p->p_fd;
942 	oioctls = NULL;
943 
944 	MPASS((flags & ~(FDDUP_FLAG_CLOEXEC)) == 0);
945 	MPASS(mode < FDDUP_LASTMODE);
946 
947 	AUDIT_ARG_FD(old);
948 	/* XXXRW: if (flags & FDDUP_FIXED) AUDIT_ARG_FD2(new); */
949 
950 	/*
951 	 * Verify we have a valid descriptor to dup from and possibly to
952 	 * dup to. Unlike dup() and dup2(), fcntl()'s F_DUPFD should
953 	 * return EINVAL when the new descriptor is out of bounds.
954 	 */
955 	if (old < 0)
956 		return (EBADF);
957 	if (new < 0)
958 		return (mode == FDDUP_FCNTL ? EINVAL : EBADF);
959 	maxfd = getmaxfd(td);
960 	if (new >= maxfd)
961 		return (mode == FDDUP_FCNTL ? EINVAL : EBADF);
962 
963 	error = EBADF;
964 	FILEDESC_XLOCK(fdp);
965 	if (fget_noref(fdp, old) == NULL)
966 		goto unlock;
967 	if (mode == FDDUP_FIXED && old == new) {
968 		td->td_retval[0] = new;
969 		if (flags & FDDUP_FLAG_CLOEXEC)
970 			fdp->fd_ofiles[new].fde_flags |= UF_EXCLOSE;
971 		error = 0;
972 		goto unlock;
973 	}
974 
975 	oldfde = &fdp->fd_ofiles[old];
976 	oldfp = oldfde->fde_file;
977 	if (!fhold(oldfp))
978 		goto unlock;
979 
980 	/*
981 	 * If the caller specified a file descriptor, make sure the file
982 	 * table is large enough to hold it, and grab it.  Otherwise, just
983 	 * allocate a new descriptor the usual way.
984 	 */
985 	switch (mode) {
986 	case FDDUP_NORMAL:
987 	case FDDUP_FCNTL:
988 		if ((error = fdalloc(td, new, &new)) != 0) {
989 			fdrop(oldfp, td);
990 			goto unlock;
991 		}
992 		break;
993 	case FDDUP_FIXED:
994 		if (new >= fdp->fd_nfiles) {
995 			/*
996 			 * The resource limits are here instead of e.g.
997 			 * fdalloc(), because the file descriptor table may be
998 			 * shared between processes, so we can't really use
999 			 * racct_add()/racct_sub().  Instead of counting the
1000 			 * number of actually allocated descriptors, just put
1001 			 * the limit on the size of the file descriptor table.
1002 			 */
1003 #ifdef RACCT
1004 			if (RACCT_ENABLED()) {
1005 				error = racct_set_unlocked(p, RACCT_NOFILE, new + 1);
1006 				if (error != 0) {
1007 					error = EMFILE;
1008 					fdrop(oldfp, td);
1009 					goto unlock;
1010 				}
1011 			}
1012 #endif
1013 			fdgrowtable_exp(fdp, new + 1);
1014 		}
1015 		if (!fdisused(fdp, new))
1016 			fdused(fdp, new);
1017 		break;
1018 	default:
1019 		KASSERT(0, ("%s unsupported mode %d", __func__, mode));
1020 	}
1021 
1022 	KASSERT(old != new, ("new fd is same as old"));
1023 
1024 	/* Refetch oldfde because the table may have grown and old one freed. */
1025 	oldfde = &fdp->fd_ofiles[old];
1026 	KASSERT(oldfp == oldfde->fde_file,
1027 	    ("fdt_ofiles shift from growth observed at fd %d",
1028 	    old));
1029 
1030 	newfde = &fdp->fd_ofiles[new];
1031 	delfp = newfde->fde_file;
1032 
1033 	nioctls = filecaps_copy_prep(&oldfde->fde_caps);
1034 
1035 	/*
1036 	 * Duplicate the source descriptor.
1037 	 */
1038 #ifdef CAPABILITIES
1039 	seqc_write_begin(&newfde->fde_seqc);
1040 #endif
1041 	oioctls = filecaps_free_prep(&newfde->fde_caps);
1042 	fde_copy(oldfde, newfde);
1043 	filecaps_copy_finish(&oldfde->fde_caps, &newfde->fde_caps,
1044 	    nioctls);
1045 	if ((flags & FDDUP_FLAG_CLOEXEC) != 0)
1046 		newfde->fde_flags = oldfde->fde_flags | UF_EXCLOSE;
1047 	else
1048 		newfde->fde_flags = oldfde->fde_flags & ~UF_EXCLOSE;
1049 #ifdef CAPABILITIES
1050 	seqc_write_end(&newfde->fde_seqc);
1051 #endif
1052 	td->td_retval[0] = new;
1053 
1054 	error = 0;
1055 
1056 	if (delfp != NULL) {
1057 		(void) closefp(fdp, new, delfp, td, true, false);
1058 		FILEDESC_UNLOCK_ASSERT(fdp);
1059 	} else {
1060 unlock:
1061 		FILEDESC_XUNLOCK(fdp);
1062 	}
1063 
1064 	filecaps_free_finish(oioctls);
1065 	return (error);
1066 }
1067 
1068 static void
sigiofree(struct sigio * sigio)1069 sigiofree(struct sigio *sigio)
1070 {
1071 	crfree(sigio->sio_ucred);
1072 	free(sigio, M_SIGIO);
1073 }
1074 
1075 static struct sigio *
funsetown_locked(struct sigio * sigio)1076 funsetown_locked(struct sigio *sigio)
1077 {
1078 	struct proc *p;
1079 	struct pgrp *pg;
1080 
1081 	SIGIO_ASSERT_LOCKED();
1082 
1083 	if (sigio == NULL)
1084 		return (NULL);
1085 	*sigio->sio_myref = NULL;
1086 	if (sigio->sio_pgid < 0) {
1087 		pg = sigio->sio_pgrp;
1088 		PGRP_LOCK(pg);
1089 		SLIST_REMOVE(&pg->pg_sigiolst, sigio, sigio, sio_pgsigio);
1090 		PGRP_UNLOCK(pg);
1091 	} else {
1092 		p = sigio->sio_proc;
1093 		PROC_LOCK(p);
1094 		SLIST_REMOVE(&p->p_sigiolst, sigio, sigio, sio_pgsigio);
1095 		PROC_UNLOCK(p);
1096 	}
1097 	return (sigio);
1098 }
1099 
1100 /*
1101  * If sigio is on the list associated with a process or process group,
1102  * disable signalling from the device, remove sigio from the list and
1103  * free sigio.
1104  */
1105 void
funsetown(struct sigio ** sigiop)1106 funsetown(struct sigio **sigiop)
1107 {
1108 	struct sigio *sigio;
1109 
1110 	/* Racy check, consumers must provide synchronization. */
1111 	if (*sigiop == NULL)
1112 		return;
1113 
1114 	SIGIO_LOCK();
1115 	sigio = funsetown_locked(*sigiop);
1116 	SIGIO_UNLOCK();
1117 	if (sigio != NULL)
1118 		sigiofree(sigio);
1119 }
1120 
1121 /*
1122  * Free a list of sigio structures.  The caller must ensure that new sigio
1123  * structures cannot be added after this point.  For process groups this is
1124  * guaranteed using the proctree lock; for processes, the P_WEXIT flag serves
1125  * as an interlock.
1126  */
1127 void
funsetownlst(struct sigiolst * sigiolst)1128 funsetownlst(struct sigiolst *sigiolst)
1129 {
1130 	struct proc *p;
1131 	struct pgrp *pg;
1132 	struct sigio *sigio, *tmp;
1133 
1134 	/* Racy check. */
1135 	sigio = SLIST_FIRST(sigiolst);
1136 	if (sigio == NULL)
1137 		return;
1138 
1139 	p = NULL;
1140 	pg = NULL;
1141 
1142 	SIGIO_LOCK();
1143 	sigio = SLIST_FIRST(sigiolst);
1144 	if (sigio == NULL) {
1145 		SIGIO_UNLOCK();
1146 		return;
1147 	}
1148 
1149 	/*
1150 	 * Every entry of the list should belong to a single proc or pgrp.
1151 	 */
1152 	if (sigio->sio_pgid < 0) {
1153 		pg = sigio->sio_pgrp;
1154 		sx_assert(&proctree_lock, SX_XLOCKED);
1155 		PGRP_LOCK(pg);
1156 	} else /* if (sigio->sio_pgid > 0) */ {
1157 		p = sigio->sio_proc;
1158 		PROC_LOCK(p);
1159 		KASSERT((p->p_flag & P_WEXIT) != 0,
1160 		    ("%s: process %p is not exiting", __func__, p));
1161 	}
1162 
1163 	SLIST_FOREACH(sigio, sigiolst, sio_pgsigio) {
1164 		*sigio->sio_myref = NULL;
1165 		if (pg != NULL) {
1166 			KASSERT(sigio->sio_pgid < 0,
1167 			    ("Proc sigio in pgrp sigio list"));
1168 			KASSERT(sigio->sio_pgrp == pg,
1169 			    ("Bogus pgrp in sigio list"));
1170 		} else /* if (p != NULL) */ {
1171 			KASSERT(sigio->sio_pgid > 0,
1172 			    ("Pgrp sigio in proc sigio list"));
1173 			KASSERT(sigio->sio_proc == p,
1174 			    ("Bogus proc in sigio list"));
1175 		}
1176 	}
1177 
1178 	if (pg != NULL)
1179 		PGRP_UNLOCK(pg);
1180 	else
1181 		PROC_UNLOCK(p);
1182 	SIGIO_UNLOCK();
1183 
1184 	SLIST_FOREACH_SAFE(sigio, sigiolst, sio_pgsigio, tmp)
1185 		sigiofree(sigio);
1186 }
1187 
1188 /*
1189  * This is common code for FIOSETOWN ioctl called by fcntl(fd, F_SETOWN, arg).
1190  *
1191  * After permission checking, add a sigio structure to the sigio list for
1192  * the process or process group.
1193  */
1194 int
fsetown(pid_t pgid,struct sigio ** sigiop)1195 fsetown(pid_t pgid, struct sigio **sigiop)
1196 {
1197 	struct proc *proc;
1198 	struct pgrp *pgrp;
1199 	struct sigio *osigio, *sigio;
1200 	int ret;
1201 
1202 	if (pgid == 0) {
1203 		funsetown(sigiop);
1204 		return (0);
1205 	}
1206 
1207 	sigio = malloc(sizeof(struct sigio), M_SIGIO, M_WAITOK);
1208 	sigio->sio_pgid = pgid;
1209 	sigio->sio_ucred = crhold(curthread->td_ucred);
1210 	sigio->sio_myref = sigiop;
1211 
1212 	ret = 0;
1213 	if (pgid > 0) {
1214 		ret = pget(pgid, PGET_NOTWEXIT | PGET_NOTID | PGET_HOLD, &proc);
1215 		SIGIO_LOCK();
1216 		osigio = funsetown_locked(*sigiop);
1217 		if (ret == 0) {
1218 			PROC_LOCK(proc);
1219 			_PRELE(proc);
1220 			if ((proc->p_flag & P_WEXIT) != 0) {
1221 				ret = ESRCH;
1222 			} else if (proc->p_session !=
1223 			    curthread->td_proc->p_session) {
1224 				/*
1225 				 * Policy - Don't allow a process to FSETOWN a
1226 				 * process in another session.
1227 				 *
1228 				 * Remove this test to allow maximum flexibility
1229 				 * or restrict FSETOWN to the current process or
1230 				 * process group for maximum safety.
1231 				 */
1232 				ret = EPERM;
1233 			} else {
1234 				sigio->sio_proc = proc;
1235 				SLIST_INSERT_HEAD(&proc->p_sigiolst, sigio,
1236 				    sio_pgsigio);
1237 			}
1238 			PROC_UNLOCK(proc);
1239 		}
1240 	} else /* if (pgid < 0) */ {
1241 		sx_slock(&proctree_lock);
1242 		SIGIO_LOCK();
1243 		osigio = funsetown_locked(*sigiop);
1244 		pgrp = pgfind(-pgid);
1245 		if (pgrp == NULL) {
1246 			ret = ESRCH;
1247 		} else {
1248 			if (pgrp->pg_session != curthread->td_proc->p_session) {
1249 				/*
1250 				 * Policy - Don't allow a process to FSETOWN a
1251 				 * process in another session.
1252 				 *
1253 				 * Remove this test to allow maximum flexibility
1254 				 * or restrict FSETOWN to the current process or
1255 				 * process group for maximum safety.
1256 				 */
1257 				ret = EPERM;
1258 			} else {
1259 				sigio->sio_pgrp = pgrp;
1260 				SLIST_INSERT_HEAD(&pgrp->pg_sigiolst, sigio,
1261 				    sio_pgsigio);
1262 			}
1263 			PGRP_UNLOCK(pgrp);
1264 		}
1265 		sx_sunlock(&proctree_lock);
1266 	}
1267 	if (ret == 0)
1268 		*sigiop = sigio;
1269 	SIGIO_UNLOCK();
1270 	if (osigio != NULL)
1271 		sigiofree(osigio);
1272 	return (ret);
1273 }
1274 
1275 /*
1276  * This is common code for FIOGETOWN ioctl called by fcntl(fd, F_GETOWN, arg).
1277  */
1278 pid_t
fgetown(struct sigio ** sigiop)1279 fgetown(struct sigio **sigiop)
1280 {
1281 	pid_t pgid;
1282 
1283 	SIGIO_LOCK();
1284 	pgid = (*sigiop != NULL) ? (*sigiop)->sio_pgid : 0;
1285 	SIGIO_UNLOCK();
1286 	return (pgid);
1287 }
1288 
1289 static int
closefp_impl(struct filedesc * fdp,int fd,struct file * fp,struct thread * td,bool audit)1290 closefp_impl(struct filedesc *fdp, int fd, struct file *fp, struct thread *td,
1291     bool audit)
1292 {
1293 	int error;
1294 
1295 	FILEDESC_XLOCK_ASSERT(fdp);
1296 
1297 	/*
1298 	 * We now hold the fp reference that used to be owned by the
1299 	 * descriptor array.  We have to unlock the FILEDESC *AFTER*
1300 	 * knote_fdclose to prevent a race of the fd getting opened, a knote
1301 	 * added, and deleteing a knote for the new fd.
1302 	 */
1303 	if (__predict_false(!TAILQ_EMPTY(&fdp->fd_kqlist)))
1304 		knote_fdclose(td, fd);
1305 
1306 	/*
1307 	 * We need to notify mqueue if the object is of type mqueue.
1308 	 */
1309 	if (__predict_false(fp->f_type == DTYPE_MQUEUE))
1310 		mq_fdclose(td, fd, fp);
1311 	FILEDESC_XUNLOCK(fdp);
1312 
1313 #ifdef AUDIT
1314 	if (AUDITING_TD(td) && audit)
1315 		audit_sysclose(td, fd, fp);
1316 #endif
1317 	error = closef(fp, td);
1318 
1319 	/*
1320 	 * All paths leading up to closefp() will have already removed or
1321 	 * replaced the fd in the filedesc table, so a restart would not
1322 	 * operate on the same file.
1323 	 */
1324 	if (error == ERESTART)
1325 		error = EINTR;
1326 
1327 	return (error);
1328 }
1329 
1330 static int
closefp_hl(struct filedesc * fdp,int fd,struct file * fp,struct thread * td,bool holdleaders,bool audit)1331 closefp_hl(struct filedesc *fdp, int fd, struct file *fp, struct thread *td,
1332     bool holdleaders, bool audit)
1333 {
1334 	int error;
1335 
1336 	FILEDESC_XLOCK_ASSERT(fdp);
1337 
1338 	if (holdleaders) {
1339 		if (td->td_proc->p_fdtol != NULL) {
1340 			/*
1341 			 * Ask fdfree() to sleep to ensure that all relevant
1342 			 * process leaders can be traversed in closef().
1343 			 */
1344 			fdp->fd_holdleaderscount++;
1345 		} else {
1346 			holdleaders = false;
1347 		}
1348 	}
1349 
1350 	error = closefp_impl(fdp, fd, fp, td, audit);
1351 	if (holdleaders) {
1352 		FILEDESC_XLOCK(fdp);
1353 		fdp->fd_holdleaderscount--;
1354 		if (fdp->fd_holdleaderscount == 0 &&
1355 		    fdp->fd_holdleaderswakeup != 0) {
1356 			fdp->fd_holdleaderswakeup = 0;
1357 			wakeup(&fdp->fd_holdleaderscount);
1358 		}
1359 		FILEDESC_XUNLOCK(fdp);
1360 	}
1361 	return (error);
1362 }
1363 
1364 static int
closefp(struct filedesc * fdp,int fd,struct file * fp,struct thread * td,bool holdleaders,bool audit)1365 closefp(struct filedesc *fdp, int fd, struct file *fp, struct thread *td,
1366     bool holdleaders, bool audit)
1367 {
1368 
1369 	FILEDESC_XLOCK_ASSERT(fdp);
1370 
1371 	if (__predict_false(td->td_proc->p_fdtol != NULL)) {
1372 		return (closefp_hl(fdp, fd, fp, td, holdleaders, audit));
1373 	} else {
1374 		return (closefp_impl(fdp, fd, fp, td, audit));
1375 	}
1376 }
1377 
1378 /*
1379  * Close a file descriptor.
1380  */
1381 #ifndef _SYS_SYSPROTO_H_
1382 struct close_args {
1383 	int     fd;
1384 };
1385 #endif
1386 /* ARGSUSED */
1387 int
sys_close(struct thread * td,struct close_args * uap)1388 sys_close(struct thread *td, struct close_args *uap)
1389 {
1390 
1391 	return (kern_close(td, uap->fd));
1392 }
1393 
1394 int
kern_close(struct thread * td,int fd)1395 kern_close(struct thread *td, int fd)
1396 {
1397 	struct filedesc *fdp;
1398 	struct file *fp;
1399 
1400 	fdp = td->td_proc->p_fd;
1401 
1402 	FILEDESC_XLOCK(fdp);
1403 	if ((fp = fget_noref(fdp, fd)) == NULL) {
1404 		FILEDESC_XUNLOCK(fdp);
1405 		return (EBADF);
1406 	}
1407 	fdfree(fdp, fd);
1408 
1409 	/* closefp() drops the FILEDESC lock for us. */
1410 	return (closefp(fdp, fd, fp, td, true, true));
1411 }
1412 
1413 static int
close_range_cloexec(struct thread * td,u_int lowfd,u_int highfd)1414 close_range_cloexec(struct thread *td, u_int lowfd, u_int highfd)
1415 {
1416 	struct filedesc *fdp;
1417 	struct fdescenttbl *fdt;
1418 	struct filedescent *fde;
1419 	int fd;
1420 
1421 	fdp = td->td_proc->p_fd;
1422 	FILEDESC_XLOCK(fdp);
1423 	fdt = atomic_load_ptr(&fdp->fd_files);
1424 	highfd = MIN(highfd, fdt->fdt_nfiles - 1);
1425 	fd = lowfd;
1426 	if (__predict_false(fd > highfd)) {
1427 		goto out_locked;
1428 	}
1429 	for (; fd <= highfd; fd++) {
1430 		fde = &fdt->fdt_ofiles[fd];
1431 		if (fde->fde_file != NULL)
1432 			fde->fde_flags |= UF_EXCLOSE;
1433 	}
1434 out_locked:
1435 	FILEDESC_XUNLOCK(fdp);
1436 	return (0);
1437 }
1438 
1439 static int
close_range_impl(struct thread * td,u_int lowfd,u_int highfd)1440 close_range_impl(struct thread *td, u_int lowfd, u_int highfd)
1441 {
1442 	struct filedesc *fdp;
1443 	const struct fdescenttbl *fdt;
1444 	struct file *fp;
1445 	int fd;
1446 
1447 	fdp = td->td_proc->p_fd;
1448 	FILEDESC_XLOCK(fdp);
1449 	fdt = atomic_load_ptr(&fdp->fd_files);
1450 	highfd = MIN(highfd, fdt->fdt_nfiles - 1);
1451 	fd = lowfd;
1452 	if (__predict_false(fd > highfd)) {
1453 		goto out_locked;
1454 	}
1455 	for (;;) {
1456 		fp = fdt->fdt_ofiles[fd].fde_file;
1457 		if (fp == NULL) {
1458 			if (fd == highfd)
1459 				goto out_locked;
1460 		} else {
1461 			fdfree(fdp, fd);
1462 			(void) closefp(fdp, fd, fp, td, true, true);
1463 			if (fd == highfd)
1464 				goto out_unlocked;
1465 			FILEDESC_XLOCK(fdp);
1466 			fdt = atomic_load_ptr(&fdp->fd_files);
1467 		}
1468 		fd++;
1469 	}
1470 out_locked:
1471 	FILEDESC_XUNLOCK(fdp);
1472 out_unlocked:
1473 	return (0);
1474 }
1475 
1476 int
kern_close_range(struct thread * td,int flags,u_int lowfd,u_int highfd)1477 kern_close_range(struct thread *td, int flags, u_int lowfd, u_int highfd)
1478 {
1479 
1480 	/*
1481 	 * Check this prior to clamping; closefrom(3) with only fd 0, 1, and 2
1482 	 * open should not be a usage error.  From a close_range() perspective,
1483 	 * close_range(3, ~0U, 0) in the same scenario should also likely not
1484 	 * be a usage error as all fd above 3 are in-fact already closed.
1485 	 */
1486 	if (highfd < lowfd) {
1487 		return (EINVAL);
1488 	}
1489 
1490 	if ((flags & CLOSE_RANGE_CLOEXEC) != 0)
1491 		return (close_range_cloexec(td, lowfd, highfd));
1492 
1493 	return (close_range_impl(td, lowfd, highfd));
1494 }
1495 
1496 #ifndef _SYS_SYSPROTO_H_
1497 struct close_range_args {
1498 	u_int	lowfd;
1499 	u_int	highfd;
1500 	int	flags;
1501 };
1502 #endif
1503 int
sys_close_range(struct thread * td,struct close_range_args * uap)1504 sys_close_range(struct thread *td, struct close_range_args *uap)
1505 {
1506 
1507 	AUDIT_ARG_FD(uap->lowfd);
1508 	AUDIT_ARG_CMD(uap->highfd);
1509 	AUDIT_ARG_FFLAGS(uap->flags);
1510 
1511 	if ((uap->flags & ~(CLOSE_RANGE_CLOEXEC)) != 0)
1512 		return (EINVAL);
1513 	return (kern_close_range(td, uap->flags, uap->lowfd, uap->highfd));
1514 }
1515 
1516 #ifdef COMPAT_FREEBSD12
1517 /*
1518  * Close open file descriptors.
1519  */
1520 #ifndef _SYS_SYSPROTO_H_
1521 struct freebsd12_closefrom_args {
1522 	int	lowfd;
1523 };
1524 #endif
1525 /* ARGSUSED */
1526 int
freebsd12_closefrom(struct thread * td,struct freebsd12_closefrom_args * uap)1527 freebsd12_closefrom(struct thread *td, struct freebsd12_closefrom_args *uap)
1528 {
1529 	u_int lowfd;
1530 
1531 	AUDIT_ARG_FD(uap->lowfd);
1532 
1533 	/*
1534 	 * Treat negative starting file descriptor values identical to
1535 	 * closefrom(0) which closes all files.
1536 	 */
1537 	lowfd = MAX(0, uap->lowfd);
1538 	return (kern_close_range(td, 0, lowfd, ~0U));
1539 }
1540 #endif	/* COMPAT_FREEBSD12 */
1541 
1542 #if defined(COMPAT_43)
1543 /*
1544  * Return status information about a file descriptor.
1545  */
1546 #ifndef _SYS_SYSPROTO_H_
1547 struct ofstat_args {
1548 	int	fd;
1549 	struct	ostat *sb;
1550 };
1551 #endif
1552 /* ARGSUSED */
1553 int
ofstat(struct thread * td,struct ofstat_args * uap)1554 ofstat(struct thread *td, struct ofstat_args *uap)
1555 {
1556 	struct ostat oub;
1557 	struct stat ub;
1558 	int error;
1559 
1560 	error = kern_fstat(td, uap->fd, &ub);
1561 	if (error == 0) {
1562 		cvtstat(&ub, &oub);
1563 		error = copyout(&oub, uap->sb, sizeof(oub));
1564 	}
1565 	return (error);
1566 }
1567 #endif /* COMPAT_43 */
1568 
1569 #if defined(COMPAT_FREEBSD11)
1570 int
freebsd11_fstat(struct thread * td,struct freebsd11_fstat_args * uap)1571 freebsd11_fstat(struct thread *td, struct freebsd11_fstat_args *uap)
1572 {
1573 	struct stat sb;
1574 	struct freebsd11_stat osb;
1575 	int error;
1576 
1577 	error = kern_fstat(td, uap->fd, &sb);
1578 	if (error != 0)
1579 		return (error);
1580 	error = freebsd11_cvtstat(&sb, &osb);
1581 	if (error == 0)
1582 		error = copyout(&osb, uap->sb, sizeof(osb));
1583 	return (error);
1584 }
1585 #endif	/* COMPAT_FREEBSD11 */
1586 
1587 /*
1588  * Return status information about a file descriptor.
1589  */
1590 #ifndef _SYS_SYSPROTO_H_
1591 struct fstat_args {
1592 	int	fd;
1593 	struct	stat *sb;
1594 };
1595 #endif
1596 /* ARGSUSED */
1597 int
sys_fstat(struct thread * td,struct fstat_args * uap)1598 sys_fstat(struct thread *td, struct fstat_args *uap)
1599 {
1600 	struct stat ub;
1601 	int error;
1602 
1603 	error = kern_fstat(td, uap->fd, &ub);
1604 	if (error == 0)
1605 		error = copyout(&ub, uap->sb, sizeof(ub));
1606 	return (error);
1607 }
1608 
1609 int
kern_fstat(struct thread * td,int fd,struct stat * sbp)1610 kern_fstat(struct thread *td, int fd, struct stat *sbp)
1611 {
1612 	struct file *fp;
1613 	int error;
1614 
1615 	AUDIT_ARG_FD(fd);
1616 
1617 	error = fget(td, fd, &cap_fstat_rights, &fp);
1618 	if (__predict_false(error != 0))
1619 		return (error);
1620 
1621 	AUDIT_ARG_FILE(td->td_proc, fp);
1622 
1623 	error = fo_stat(fp, sbp, td->td_ucred);
1624 	fdrop(fp, td);
1625 #ifdef __STAT_TIME_T_EXT
1626 	sbp->st_atim_ext = 0;
1627 	sbp->st_mtim_ext = 0;
1628 	sbp->st_ctim_ext = 0;
1629 	sbp->st_btim_ext = 0;
1630 #endif
1631 #ifdef KTRACE
1632 	if (KTRPOINT(td, KTR_STRUCT))
1633 		ktrstat_error(sbp, error);
1634 #endif
1635 	return (error);
1636 }
1637 
1638 #if defined(COMPAT_FREEBSD11)
1639 /*
1640  * Return status information about a file descriptor.
1641  */
1642 #ifndef _SYS_SYSPROTO_H_
1643 struct freebsd11_nfstat_args {
1644 	int	fd;
1645 	struct	nstat *sb;
1646 };
1647 #endif
1648 /* ARGSUSED */
1649 int
freebsd11_nfstat(struct thread * td,struct freebsd11_nfstat_args * uap)1650 freebsd11_nfstat(struct thread *td, struct freebsd11_nfstat_args *uap)
1651 {
1652 	struct nstat nub;
1653 	struct stat ub;
1654 	int error;
1655 
1656 	error = kern_fstat(td, uap->fd, &ub);
1657 	if (error != 0)
1658 		return (error);
1659 	error = freebsd11_cvtnstat(&ub, &nub);
1660 	if (error != 0)
1661 		error = copyout(&nub, uap->sb, sizeof(nub));
1662 	return (error);
1663 }
1664 #endif /* COMPAT_FREEBSD11 */
1665 
1666 /*
1667  * Return pathconf information about a file descriptor.
1668  */
1669 #ifndef _SYS_SYSPROTO_H_
1670 struct fpathconf_args {
1671 	int	fd;
1672 	int	name;
1673 };
1674 #endif
1675 /* ARGSUSED */
1676 int
sys_fpathconf(struct thread * td,struct fpathconf_args * uap)1677 sys_fpathconf(struct thread *td, struct fpathconf_args *uap)
1678 {
1679 	long value;
1680 	int error;
1681 
1682 	error = kern_fpathconf(td, uap->fd, uap->name, &value);
1683 	if (error == 0)
1684 		td->td_retval[0] = value;
1685 	return (error);
1686 }
1687 
1688 int
kern_fpathconf(struct thread * td,int fd,int name,long * valuep)1689 kern_fpathconf(struct thread *td, int fd, int name, long *valuep)
1690 {
1691 	struct file *fp;
1692 	struct vnode *vp;
1693 	int error;
1694 
1695 	error = fget(td, fd, &cap_fpathconf_rights, &fp);
1696 	if (error != 0)
1697 		return (error);
1698 
1699 	if (name == _PC_ASYNC_IO) {
1700 		*valuep = _POSIX_ASYNCHRONOUS_IO;
1701 		goto out;
1702 	}
1703 	vp = fp->f_vnode;
1704 	if (vp != NULL) {
1705 		vn_lock(vp, LK_SHARED | LK_RETRY);
1706 		error = VOP_PATHCONF(vp, name, valuep);
1707 		VOP_UNLOCK(vp);
1708 	} else if (fp->f_type == DTYPE_PIPE || fp->f_type == DTYPE_SOCKET) {
1709 		if (name != _PC_PIPE_BUF) {
1710 			error = EINVAL;
1711 		} else {
1712 			*valuep = PIPE_BUF;
1713 			error = 0;
1714 		}
1715 	} else {
1716 		error = EOPNOTSUPP;
1717 	}
1718 out:
1719 	fdrop(fp, td);
1720 	return (error);
1721 }
1722 
1723 /*
1724  * Copy filecaps structure allocating memory for ioctls array if needed.
1725  *
1726  * The last parameter indicates whether the fdtable is locked. If it is not and
1727  * ioctls are encountered, copying fails and the caller must lock the table.
1728  *
1729  * Note that if the table was not locked, the caller has to check the relevant
1730  * sequence counter to determine whether the operation was successful.
1731  */
1732 bool
filecaps_copy(const struct filecaps * src,struct filecaps * dst,bool locked)1733 filecaps_copy(const struct filecaps *src, struct filecaps *dst, bool locked)
1734 {
1735 	size_t size;
1736 
1737 	if (src->fc_ioctls != NULL && !locked)
1738 		return (false);
1739 	memcpy(dst, src, sizeof(*src));
1740 	if (src->fc_ioctls == NULL)
1741 		return (true);
1742 
1743 	KASSERT(src->fc_nioctls > 0,
1744 	    ("fc_ioctls != NULL, but fc_nioctls=%hd", src->fc_nioctls));
1745 
1746 	size = sizeof(src->fc_ioctls[0]) * src->fc_nioctls;
1747 	dst->fc_ioctls = malloc(size, M_FILECAPS, M_WAITOK);
1748 	memcpy(dst->fc_ioctls, src->fc_ioctls, size);
1749 	return (true);
1750 }
1751 
1752 static u_long *
filecaps_copy_prep(const struct filecaps * src)1753 filecaps_copy_prep(const struct filecaps *src)
1754 {
1755 	u_long *ioctls;
1756 	size_t size;
1757 
1758 	if (__predict_true(src->fc_ioctls == NULL))
1759 		return (NULL);
1760 
1761 	KASSERT(src->fc_nioctls > 0,
1762 	    ("fc_ioctls != NULL, but fc_nioctls=%hd", src->fc_nioctls));
1763 
1764 	size = sizeof(src->fc_ioctls[0]) * src->fc_nioctls;
1765 	ioctls = malloc(size, M_FILECAPS, M_WAITOK);
1766 	return (ioctls);
1767 }
1768 
1769 static void
filecaps_copy_finish(const struct filecaps * src,struct filecaps * dst,u_long * ioctls)1770 filecaps_copy_finish(const struct filecaps *src, struct filecaps *dst,
1771     u_long *ioctls)
1772 {
1773 	size_t size;
1774 
1775 	*dst = *src;
1776 	if (__predict_true(src->fc_ioctls == NULL)) {
1777 		MPASS(ioctls == NULL);
1778 		return;
1779 	}
1780 
1781 	size = sizeof(src->fc_ioctls[0]) * src->fc_nioctls;
1782 	dst->fc_ioctls = ioctls;
1783 	bcopy(src->fc_ioctls, dst->fc_ioctls, size);
1784 }
1785 
1786 /*
1787  * Move filecaps structure to the new place and clear the old place.
1788  */
1789 void
filecaps_move(struct filecaps * src,struct filecaps * dst)1790 filecaps_move(struct filecaps *src, struct filecaps *dst)
1791 {
1792 
1793 	*dst = *src;
1794 	bzero(src, sizeof(*src));
1795 }
1796 
1797 /*
1798  * Fill the given filecaps structure with full rights.
1799  */
1800 static void
filecaps_fill(struct filecaps * fcaps)1801 filecaps_fill(struct filecaps *fcaps)
1802 {
1803 
1804 	CAP_ALL(&fcaps->fc_rights);
1805 	fcaps->fc_ioctls = NULL;
1806 	fcaps->fc_nioctls = -1;
1807 	fcaps->fc_fcntls = CAP_FCNTL_ALL;
1808 }
1809 
1810 /*
1811  * Free memory allocated within filecaps structure.
1812  */
1813 static void
filecaps_free_ioctl(struct filecaps * fcaps)1814 filecaps_free_ioctl(struct filecaps *fcaps)
1815 {
1816 
1817 	free(fcaps->fc_ioctls, M_FILECAPS);
1818 	fcaps->fc_ioctls = NULL;
1819 }
1820 
1821 void
filecaps_free(struct filecaps * fcaps)1822 filecaps_free(struct filecaps *fcaps)
1823 {
1824 
1825 	filecaps_free_ioctl(fcaps);
1826 	bzero(fcaps, sizeof(*fcaps));
1827 }
1828 
1829 static u_long *
filecaps_free_prep(struct filecaps * fcaps)1830 filecaps_free_prep(struct filecaps *fcaps)
1831 {
1832 	u_long *ioctls;
1833 
1834 	ioctls = fcaps->fc_ioctls;
1835 	bzero(fcaps, sizeof(*fcaps));
1836 	return (ioctls);
1837 }
1838 
1839 static void
filecaps_free_finish(u_long * ioctls)1840 filecaps_free_finish(u_long *ioctls)
1841 {
1842 
1843 	free(ioctls, M_FILECAPS);
1844 }
1845 
1846 /*
1847  * Validate the given filecaps structure.
1848  */
1849 static void
filecaps_validate(const struct filecaps * fcaps,const char * func)1850 filecaps_validate(const struct filecaps *fcaps, const char *func)
1851 {
1852 
1853 	KASSERT(cap_rights_is_valid(&fcaps->fc_rights),
1854 	    ("%s: invalid rights", func));
1855 	KASSERT((fcaps->fc_fcntls & ~CAP_FCNTL_ALL) == 0,
1856 	    ("%s: invalid fcntls", func));
1857 	KASSERT(fcaps->fc_fcntls == 0 ||
1858 	    cap_rights_is_set(&fcaps->fc_rights, CAP_FCNTL),
1859 	    ("%s: fcntls without CAP_FCNTL", func));
1860 	/*
1861 	 * open calls without WANTIOCTLCAPS free caps but leave the counter
1862 	 */
1863 #if 0
1864 	KASSERT(fcaps->fc_ioctls != NULL ? fcaps->fc_nioctls > 0 :
1865 	    (fcaps->fc_nioctls == -1 || fcaps->fc_nioctls == 0),
1866 	    ("%s: invalid ioctls", func));
1867 #endif
1868 	KASSERT(fcaps->fc_nioctls == 0 ||
1869 	    cap_rights_is_set(&fcaps->fc_rights, CAP_IOCTL),
1870 	    ("%s: ioctls without CAP_IOCTL", func));
1871 }
1872 
1873 static void
fdgrowtable_exp(struct filedesc * fdp,int nfd)1874 fdgrowtable_exp(struct filedesc *fdp, int nfd)
1875 {
1876 	int nfd1;
1877 
1878 	FILEDESC_XLOCK_ASSERT(fdp);
1879 
1880 	nfd1 = fdp->fd_nfiles * 2;
1881 	if (nfd1 < nfd)
1882 		nfd1 = nfd;
1883 	fdgrowtable(fdp, nfd1);
1884 }
1885 
1886 /*
1887  * Grow the file table to accommodate (at least) nfd descriptors.
1888  */
1889 static void
fdgrowtable(struct filedesc * fdp,int nfd)1890 fdgrowtable(struct filedesc *fdp, int nfd)
1891 {
1892 	struct filedesc0 *fdp0;
1893 	struct freetable *ft;
1894 	struct fdescenttbl *ntable;
1895 	struct fdescenttbl *otable;
1896 	int nnfiles, onfiles;
1897 	NDSLOTTYPE *nmap, *omap;
1898 
1899 	KASSERT(fdp->fd_nfiles > 0, ("zero-length file table"));
1900 
1901 	/* save old values */
1902 	onfiles = fdp->fd_nfiles;
1903 	otable = fdp->fd_files;
1904 	omap = fdp->fd_map;
1905 
1906 	/* compute the size of the new table */
1907 	nnfiles = NDSLOTS(nfd) * NDENTRIES; /* round up */
1908 	if (nnfiles <= onfiles)
1909 		/* the table is already large enough */
1910 		return;
1911 
1912 	/*
1913 	 * Allocate a new table.  We need enough space for the number of
1914 	 * entries, file entries themselves and the struct freetable we will use
1915 	 * when we decommission the table and place it on the freelist.
1916 	 * We place the struct freetable in the middle so we don't have
1917 	 * to worry about padding.
1918 	 */
1919 	ntable = malloc(offsetof(struct fdescenttbl, fdt_ofiles) +
1920 	    nnfiles * sizeof(ntable->fdt_ofiles[0]) +
1921 	    sizeof(struct freetable),
1922 	    M_FILEDESC, M_ZERO | M_WAITOK);
1923 	/* copy the old data */
1924 	ntable->fdt_nfiles = nnfiles;
1925 	memcpy(ntable->fdt_ofiles, otable->fdt_ofiles,
1926 	    onfiles * sizeof(ntable->fdt_ofiles[0]));
1927 
1928 	/*
1929 	 * Allocate a new map only if the old is not large enough.  It will
1930 	 * grow at a slower rate than the table as it can map more
1931 	 * entries than the table can hold.
1932 	 */
1933 	if (NDSLOTS(nnfiles) > NDSLOTS(onfiles)) {
1934 		nmap = malloc(NDSLOTS(nnfiles) * NDSLOTSIZE, M_FILEDESC,
1935 		    M_ZERO | M_WAITOK);
1936 		/* copy over the old data and update the pointer */
1937 		memcpy(nmap, omap, NDSLOTS(onfiles) * sizeof(*omap));
1938 		fdp->fd_map = nmap;
1939 	}
1940 
1941 	/*
1942 	 * Make sure that ntable is correctly initialized before we replace
1943 	 * fd_files poiner. Otherwise fget_unlocked() may see inconsistent
1944 	 * data.
1945 	 */
1946 	atomic_store_rel_ptr((volatile void *)&fdp->fd_files, (uintptr_t)ntable);
1947 
1948 	/*
1949 	 * Free the old file table when not shared by other threads or processes.
1950 	 * The old file table is considered to be shared when either are true:
1951 	 * - The process has more than one thread.
1952 	 * - The file descriptor table has been shared via fdshare().
1953 	 *
1954 	 * When shared, the old file table will be placed on a freelist
1955 	 * which will be processed when the struct filedesc is released.
1956 	 *
1957 	 * Note that if onfiles == NDFILE, we're dealing with the original
1958 	 * static allocation contained within (struct filedesc0 *)fdp,
1959 	 * which must not be freed.
1960 	 */
1961 	if (onfiles > NDFILE) {
1962 		/*
1963 		 * Note we may be called here from fdinit while allocating a
1964 		 * table for a new process in which case ->p_fd points
1965 		 * elsewhere.
1966 		 */
1967 		if (curproc->p_fd != fdp || FILEDESC_IS_ONLY_USER(fdp)) {
1968 			free(otable, M_FILEDESC);
1969 		} else {
1970 			ft = (struct freetable *)&otable->fdt_ofiles[onfiles];
1971 			fdp0 = (struct filedesc0 *)fdp;
1972 			ft->ft_table = otable;
1973 			SLIST_INSERT_HEAD(&fdp0->fd_free, ft, ft_next);
1974 		}
1975 	}
1976 	/*
1977 	 * The map does not have the same possibility of threads still
1978 	 * holding references to it.  So always free it as long as it
1979 	 * does not reference the original static allocation.
1980 	 */
1981 	if (NDSLOTS(onfiles) > NDSLOTS(NDFILE))
1982 		free(omap, M_FILEDESC);
1983 }
1984 
1985 /*
1986  * Allocate a file descriptor for the process.
1987  */
1988 int
fdalloc(struct thread * td,int minfd,int * result)1989 fdalloc(struct thread *td, int minfd, int *result)
1990 {
1991 	struct proc *p = td->td_proc;
1992 	struct filedesc *fdp = p->p_fd;
1993 	int fd, maxfd, allocfd;
1994 #ifdef RACCT
1995 	int error;
1996 #endif
1997 
1998 	FILEDESC_XLOCK_ASSERT(fdp);
1999 
2000 	if (fdp->fd_freefile > minfd)
2001 		minfd = fdp->fd_freefile;
2002 
2003 	maxfd = getmaxfd(td);
2004 
2005 	/*
2006 	 * Search the bitmap for a free descriptor starting at minfd.
2007 	 * If none is found, grow the file table.
2008 	 */
2009 	fd = fd_first_free(fdp, minfd, fdp->fd_nfiles);
2010 	if (__predict_false(fd >= maxfd))
2011 		return (EMFILE);
2012 	if (__predict_false(fd >= fdp->fd_nfiles)) {
2013 		allocfd = min(fd * 2, maxfd);
2014 #ifdef RACCT
2015 		if (RACCT_ENABLED()) {
2016 			error = racct_set_unlocked(p, RACCT_NOFILE, allocfd);
2017 			if (error != 0)
2018 				return (EMFILE);
2019 		}
2020 #endif
2021 		/*
2022 		 * fd is already equal to first free descriptor >= minfd, so
2023 		 * we only need to grow the table and we are done.
2024 		 */
2025 		fdgrowtable_exp(fdp, allocfd);
2026 	}
2027 
2028 	/*
2029 	 * Perform some sanity checks, then mark the file descriptor as
2030 	 * used and return it to the caller.
2031 	 */
2032 	KASSERT(fd >= 0 && fd < min(maxfd, fdp->fd_nfiles),
2033 	    ("invalid descriptor %d", fd));
2034 	KASSERT(!fdisused(fdp, fd),
2035 	    ("fd_first_free() returned non-free descriptor"));
2036 	KASSERT(fdp->fd_ofiles[fd].fde_file == NULL,
2037 	    ("file descriptor isn't free"));
2038 	fdused(fdp, fd);
2039 	*result = fd;
2040 	return (0);
2041 }
2042 
2043 /*
2044  * Allocate n file descriptors for the process.
2045  */
2046 int
fdallocn(struct thread * td,int minfd,int * fds,int n)2047 fdallocn(struct thread *td, int minfd, int *fds, int n)
2048 {
2049 	struct proc *p = td->td_proc;
2050 	struct filedesc *fdp = p->p_fd;
2051 	int i;
2052 
2053 	FILEDESC_XLOCK_ASSERT(fdp);
2054 
2055 	for (i = 0; i < n; i++)
2056 		if (fdalloc(td, 0, &fds[i]) != 0)
2057 			break;
2058 
2059 	if (i < n) {
2060 		for (i--; i >= 0; i--)
2061 			fdunused(fdp, fds[i]);
2062 		return (EMFILE);
2063 	}
2064 
2065 	return (0);
2066 }
2067 
2068 /*
2069  * Create a new open file structure and allocate a file descriptor for the
2070  * process that refers to it.  We add one reference to the file for the
2071  * descriptor table and one reference for resultfp. This is to prevent us
2072  * being preempted and the entry in the descriptor table closed after we
2073  * release the FILEDESC lock.
2074  */
2075 int
falloc_caps(struct thread * td,struct file ** resultfp,int * resultfd,int flags,struct filecaps * fcaps)2076 falloc_caps(struct thread *td, struct file **resultfp, int *resultfd, int flags,
2077     struct filecaps *fcaps)
2078 {
2079 	struct file *fp;
2080 	int error, fd;
2081 
2082 	MPASS(resultfp != NULL);
2083 	MPASS(resultfd != NULL);
2084 
2085 	error = _falloc_noinstall(td, &fp, 2);
2086 	if (__predict_false(error != 0)) {
2087 		return (error);
2088 	}
2089 
2090 	error = finstall_refed(td, fp, &fd, flags, fcaps);
2091 	if (__predict_false(error != 0)) {
2092 		falloc_abort(td, fp);
2093 		return (error);
2094 	}
2095 
2096 	*resultfp = fp;
2097 	*resultfd = fd;
2098 
2099 	return (0);
2100 }
2101 
2102 /*
2103  * Create a new open file structure without allocating a file descriptor.
2104  */
2105 int
_falloc_noinstall(struct thread * td,struct file ** resultfp,u_int n)2106 _falloc_noinstall(struct thread *td, struct file **resultfp, u_int n)
2107 {
2108 	struct file *fp;
2109 	int maxuserfiles = maxfiles - (maxfiles / 20);
2110 	int openfiles_new;
2111 	static struct timeval lastfail;
2112 	static int curfail;
2113 
2114 	KASSERT(resultfp != NULL, ("%s: resultfp == NULL", __func__));
2115 	MPASS(n > 0);
2116 
2117 	openfiles_new = atomic_fetchadd_int(&openfiles, 1) + 1;
2118 	if ((openfiles_new >= maxuserfiles &&
2119 	    priv_check(td, PRIV_MAXFILES) != 0) ||
2120 	    openfiles_new >= maxfiles) {
2121 		atomic_subtract_int(&openfiles, 1);
2122 		if (ppsratecheck(&lastfail, &curfail, 1)) {
2123 			printf("kern.maxfiles limit exceeded by uid %i, (%s) "
2124 			    "please see tuning(7).\n", td->td_ucred->cr_ruid, td->td_proc->p_comm);
2125 		}
2126 		return (ENFILE);
2127 	}
2128 	fp = uma_zalloc(file_zone, M_WAITOK);
2129 	bzero(fp, sizeof(*fp));
2130 	refcount_init(&fp->f_count, n);
2131 	fp->f_cred = crhold(td->td_ucred);
2132 	fp->f_ops = &badfileops;
2133 	*resultfp = fp;
2134 	return (0);
2135 }
2136 
2137 void
falloc_abort(struct thread * td,struct file * fp)2138 falloc_abort(struct thread *td, struct file *fp)
2139 {
2140 
2141 	/*
2142 	 * For assertion purposes.
2143 	 */
2144 	refcount_init(&fp->f_count, 0);
2145 	_fdrop(fp, td);
2146 }
2147 
2148 /*
2149  * Install a file in a file descriptor table.
2150  */
2151 void
_finstall(struct filedesc * fdp,struct file * fp,int fd,int flags,struct filecaps * fcaps)2152 _finstall(struct filedesc *fdp, struct file *fp, int fd, int flags,
2153     struct filecaps *fcaps)
2154 {
2155 	struct filedescent *fde;
2156 
2157 	MPASS(fp != NULL);
2158 	if (fcaps != NULL)
2159 		filecaps_validate(fcaps, __func__);
2160 	FILEDESC_XLOCK_ASSERT(fdp);
2161 
2162 	fde = &fdp->fd_ofiles[fd];
2163 #ifdef CAPABILITIES
2164 	seqc_write_begin(&fde->fde_seqc);
2165 #endif
2166 	fde->fde_file = fp;
2167 	fde->fde_flags = (flags & O_CLOEXEC) != 0 ? UF_EXCLOSE : 0;
2168 	if (fcaps != NULL)
2169 		filecaps_move(fcaps, &fde->fde_caps);
2170 	else
2171 		filecaps_fill(&fde->fde_caps);
2172 #ifdef CAPABILITIES
2173 	seqc_write_end(&fde->fde_seqc);
2174 #endif
2175 }
2176 
2177 int
finstall_refed(struct thread * td,struct file * fp,int * fd,int flags,struct filecaps * fcaps)2178 finstall_refed(struct thread *td, struct file *fp, int *fd, int flags,
2179     struct filecaps *fcaps)
2180 {
2181 	struct filedesc *fdp = td->td_proc->p_fd;
2182 	int error;
2183 
2184 	MPASS(fd != NULL);
2185 
2186 	FILEDESC_XLOCK(fdp);
2187 	error = fdalloc(td, 0, fd);
2188 	if (__predict_true(error == 0)) {
2189 		_finstall(fdp, fp, *fd, flags, fcaps);
2190 	}
2191 	FILEDESC_XUNLOCK(fdp);
2192 	return (error);
2193 }
2194 
2195 int
finstall(struct thread * td,struct file * fp,int * fd,int flags,struct filecaps * fcaps)2196 finstall(struct thread *td, struct file *fp, int *fd, int flags,
2197     struct filecaps *fcaps)
2198 {
2199 	int error;
2200 
2201 	MPASS(fd != NULL);
2202 
2203 	if (!fhold(fp))
2204 		return (EBADF);
2205 	error = finstall_refed(td, fp, fd, flags, fcaps);
2206 	if (__predict_false(error != 0)) {
2207 		fdrop(fp, td);
2208 	}
2209 	return (error);
2210 }
2211 
2212 /*
2213  * Build a new filedesc structure from another.
2214  *
2215  * If fdp is not NULL, return with it shared locked.
2216  */
2217 struct filedesc *
fdinit(void)2218 fdinit(void)
2219 {
2220 	struct filedesc0 *newfdp0;
2221 	struct filedesc *newfdp;
2222 
2223 	newfdp0 = uma_zalloc(filedesc0_zone, M_WAITOK | M_ZERO);
2224 	newfdp = &newfdp0->fd_fd;
2225 
2226 	/* Create the file descriptor table. */
2227 	FILEDESC_LOCK_INIT(newfdp);
2228 	refcount_init(&newfdp->fd_refcnt, 1);
2229 	refcount_init(&newfdp->fd_holdcnt, 1);
2230 	newfdp->fd_map = newfdp0->fd_dmap;
2231 	newfdp->fd_files = (struct fdescenttbl *)&newfdp0->fd_dfiles;
2232 	newfdp->fd_files->fdt_nfiles = NDFILE;
2233 
2234 	return (newfdp);
2235 }
2236 
2237 /*
2238  * Build a pwddesc structure from another.
2239  * Copy the current, root, and jail root vnode references.
2240  *
2241  * If pdp is not NULL and keeplock is true, return with it (exclusively) locked.
2242  */
2243 struct pwddesc *
pdinit(struct pwddesc * pdp,bool keeplock)2244 pdinit(struct pwddesc *pdp, bool keeplock)
2245 {
2246 	struct pwddesc *newpdp;
2247 	struct pwd *newpwd;
2248 
2249 	newpdp = malloc(sizeof(*newpdp), M_PWDDESC, M_WAITOK | M_ZERO);
2250 
2251 	PWDDESC_LOCK_INIT(newpdp);
2252 	refcount_init(&newpdp->pd_refcount, 1);
2253 	newpdp->pd_cmask = CMASK;
2254 
2255 	if (pdp == NULL) {
2256 		newpwd = pwd_alloc();
2257 		smr_serialized_store(&newpdp->pd_pwd, newpwd, true);
2258 		return (newpdp);
2259 	}
2260 
2261 	PWDDESC_XLOCK(pdp);
2262 	newpwd = pwd_hold_pwddesc(pdp);
2263 	smr_serialized_store(&newpdp->pd_pwd, newpwd, true);
2264 	if (!keeplock)
2265 		PWDDESC_XUNLOCK(pdp);
2266 	return (newpdp);
2267 }
2268 
2269 /*
2270  * Hold either filedesc or pwddesc of the passed process.
2271  *
2272  * The process lock is used to synchronize against the target exiting and
2273  * freeing the data.
2274  *
2275  * Clearing can be ilustrated in 3 steps:
2276  * 1. set the pointer to NULL. Either routine can race against it, hence
2277  *   atomic_load_ptr.
2278  * 2. observe the process lock as not taken. Until then fdhold/pdhold can
2279  *   race to either still see the pointer or find NULL. It is still safe to
2280  *   grab a reference as clearing is stalled.
2281  * 3. after the lock is observed as not taken, any fdhold/pdhold calls are
2282  *   guaranteed to see NULL, making it safe to finish clearing
2283  */
2284 static struct filedesc *
fdhold(struct proc * p)2285 fdhold(struct proc *p)
2286 {
2287 	struct filedesc *fdp;
2288 
2289 	PROC_LOCK_ASSERT(p, MA_OWNED);
2290 	fdp = atomic_load_ptr(&p->p_fd);
2291 	if (fdp != NULL)
2292 		refcount_acquire(&fdp->fd_holdcnt);
2293 	return (fdp);
2294 }
2295 
2296 static struct pwddesc *
pdhold(struct proc * p)2297 pdhold(struct proc *p)
2298 {
2299 	struct pwddesc *pdp;
2300 
2301 	PROC_LOCK_ASSERT(p, MA_OWNED);
2302 	pdp = atomic_load_ptr(&p->p_pd);
2303 	if (pdp != NULL)
2304 		refcount_acquire(&pdp->pd_refcount);
2305 	return (pdp);
2306 }
2307 
2308 static void
fddrop(struct filedesc * fdp)2309 fddrop(struct filedesc *fdp)
2310 {
2311 
2312 	if (refcount_load(&fdp->fd_holdcnt) > 1) {
2313 		if (refcount_release(&fdp->fd_holdcnt) == 0)
2314 			return;
2315 	}
2316 
2317 	FILEDESC_LOCK_DESTROY(fdp);
2318 	uma_zfree(filedesc0_zone, fdp);
2319 }
2320 
2321 static void
pddrop(struct pwddesc * pdp)2322 pddrop(struct pwddesc *pdp)
2323 {
2324 	struct pwd *pwd;
2325 
2326 	if (refcount_release_if_not_last(&pdp->pd_refcount))
2327 		return;
2328 
2329 	PWDDESC_XLOCK(pdp);
2330 	if (refcount_release(&pdp->pd_refcount) == 0) {
2331 		PWDDESC_XUNLOCK(pdp);
2332 		return;
2333 	}
2334 	pwd = PWDDESC_XLOCKED_LOAD_PWD(pdp);
2335 	pwd_set(pdp, NULL);
2336 	PWDDESC_XUNLOCK(pdp);
2337 	pwd_drop(pwd);
2338 
2339 	PWDDESC_LOCK_DESTROY(pdp);
2340 	free(pdp, M_PWDDESC);
2341 }
2342 
2343 /*
2344  * Share a filedesc structure.
2345  */
2346 struct filedesc *
fdshare(struct filedesc * fdp)2347 fdshare(struct filedesc *fdp)
2348 {
2349 
2350 	refcount_acquire(&fdp->fd_refcnt);
2351 	return (fdp);
2352 }
2353 
2354 /*
2355  * Share a pwddesc structure.
2356  */
2357 struct pwddesc *
pdshare(struct pwddesc * pdp)2358 pdshare(struct pwddesc *pdp)
2359 {
2360 	refcount_acquire(&pdp->pd_refcount);
2361 	return (pdp);
2362 }
2363 
2364 /*
2365  * Unshare a filedesc structure, if necessary by making a copy
2366  */
2367 void
fdunshare(struct thread * td)2368 fdunshare(struct thread *td)
2369 {
2370 	struct filedesc *tmp;
2371 	struct proc *p = td->td_proc;
2372 
2373 	if (refcount_load(&p->p_fd->fd_refcnt) == 1)
2374 		return;
2375 
2376 	tmp = fdcopy(p->p_fd);
2377 	fdescfree(td);
2378 	p->p_fd = tmp;
2379 }
2380 
2381 /*
2382  * Unshare a pwddesc structure.
2383  */
2384 void
pdunshare(struct thread * td)2385 pdunshare(struct thread *td)
2386 {
2387 	struct pwddesc *pdp;
2388 	struct proc *p;
2389 
2390 	p = td->td_proc;
2391 	/* Not shared. */
2392 	if (refcount_load(&p->p_pd->pd_refcount) == 1)
2393 		return;
2394 
2395 	pdp = pdcopy(p->p_pd);
2396 	pdescfree(td);
2397 	p->p_pd = pdp;
2398 }
2399 
2400 /*
2401  * Copy a filedesc structure.  A NULL pointer in returns a NULL reference,
2402  * this is to ease callers, not catch errors.
2403  */
2404 struct filedesc *
fdcopy(struct filedesc * fdp)2405 fdcopy(struct filedesc *fdp)
2406 {
2407 	struct filedesc *newfdp;
2408 	struct filedescent *nfde, *ofde;
2409 	int i, lastfile;
2410 
2411 	MPASS(fdp != NULL);
2412 
2413 	newfdp = fdinit();
2414 	FILEDESC_SLOCK(fdp);
2415 	for (;;) {
2416 		lastfile = fdlastfile(fdp);
2417 		if (lastfile < newfdp->fd_nfiles)
2418 			break;
2419 		FILEDESC_SUNLOCK(fdp);
2420 		fdgrowtable(newfdp, lastfile + 1);
2421 		FILEDESC_SLOCK(fdp);
2422 	}
2423 	/* copy all passable descriptors (i.e. not kqueue) */
2424 	newfdp->fd_freefile = fdp->fd_freefile;
2425 	FILEDESC_FOREACH_FDE(fdp, i, ofde) {
2426 		if ((ofde->fde_file->f_ops->fo_flags & DFLAG_PASSABLE) == 0 ||
2427 		    !fhold(ofde->fde_file)) {
2428 			if (newfdp->fd_freefile == fdp->fd_freefile)
2429 				newfdp->fd_freefile = i;
2430 			continue;
2431 		}
2432 		nfde = &newfdp->fd_ofiles[i];
2433 		*nfde = *ofde;
2434 		filecaps_copy(&ofde->fde_caps, &nfde->fde_caps, true);
2435 		fdused_init(newfdp, i);
2436 	}
2437 	MPASS(newfdp->fd_freefile != -1);
2438 	FILEDESC_SUNLOCK(fdp);
2439 	return (newfdp);
2440 }
2441 
2442 /*
2443  * Copy a pwddesc structure.
2444  */
2445 struct pwddesc *
pdcopy(struct pwddesc * pdp)2446 pdcopy(struct pwddesc *pdp)
2447 {
2448 	struct pwddesc *newpdp;
2449 
2450 	MPASS(pdp != NULL);
2451 
2452 	newpdp = pdinit(pdp, true);
2453 	newpdp->pd_cmask = pdp->pd_cmask;
2454 	PWDDESC_XUNLOCK(pdp);
2455 	return (newpdp);
2456 }
2457 
2458 /*
2459  * Clear POSIX style locks. This is only used when fdp looses a reference (i.e.
2460  * one of processes using it exits) and the table used to be shared.
2461  */
2462 static void
fdclearlocks(struct thread * td)2463 fdclearlocks(struct thread *td)
2464 {
2465 	struct filedesc *fdp;
2466 	struct filedesc_to_leader *fdtol;
2467 	struct flock lf;
2468 	struct file *fp;
2469 	struct proc *p;
2470 	struct vnode *vp;
2471 	int i;
2472 
2473 	p = td->td_proc;
2474 	fdp = p->p_fd;
2475 	fdtol = p->p_fdtol;
2476 	MPASS(fdtol != NULL);
2477 
2478 	FILEDESC_XLOCK(fdp);
2479 	KASSERT(fdtol->fdl_refcount > 0,
2480 	    ("filedesc_to_refcount botch: fdl_refcount=%d",
2481 	    fdtol->fdl_refcount));
2482 	if (fdtol->fdl_refcount == 1 &&
2483 	    (p->p_leader->p_flag & P_ADVLOCK) != 0) {
2484 		FILEDESC_FOREACH_FP(fdp, i, fp) {
2485 			if (fp->f_type != DTYPE_VNODE ||
2486 			    !fhold(fp))
2487 				continue;
2488 			FILEDESC_XUNLOCK(fdp);
2489 			lf.l_whence = SEEK_SET;
2490 			lf.l_start = 0;
2491 			lf.l_len = 0;
2492 			lf.l_type = F_UNLCK;
2493 			vp = fp->f_vnode;
2494 			(void) VOP_ADVLOCK(vp,
2495 			    (caddr_t)p->p_leader, F_UNLCK,
2496 			    &lf, F_POSIX);
2497 			FILEDESC_XLOCK(fdp);
2498 			fdrop(fp, td);
2499 		}
2500 	}
2501 retry:
2502 	if (fdtol->fdl_refcount == 1) {
2503 		if (fdp->fd_holdleaderscount > 0 &&
2504 		    (p->p_leader->p_flag & P_ADVLOCK) != 0) {
2505 			/*
2506 			 * close() or kern_dup() has cleared a reference
2507 			 * in a shared file descriptor table.
2508 			 */
2509 			fdp->fd_holdleaderswakeup = 1;
2510 			sx_sleep(&fdp->fd_holdleaderscount,
2511 			    FILEDESC_LOCK(fdp), PLOCK, "fdlhold", 0);
2512 			goto retry;
2513 		}
2514 		if (fdtol->fdl_holdcount > 0) {
2515 			/*
2516 			 * Ensure that fdtol->fdl_leader remains
2517 			 * valid in closef().
2518 			 */
2519 			fdtol->fdl_wakeup = 1;
2520 			sx_sleep(fdtol, FILEDESC_LOCK(fdp), PLOCK,
2521 			    "fdlhold", 0);
2522 			goto retry;
2523 		}
2524 	}
2525 	fdtol->fdl_refcount--;
2526 	if (fdtol->fdl_refcount == 0 &&
2527 	    fdtol->fdl_holdcount == 0) {
2528 		fdtol->fdl_next->fdl_prev = fdtol->fdl_prev;
2529 		fdtol->fdl_prev->fdl_next = fdtol->fdl_next;
2530 	} else
2531 		fdtol = NULL;
2532 	p->p_fdtol = NULL;
2533 	FILEDESC_XUNLOCK(fdp);
2534 	if (fdtol != NULL)
2535 		free(fdtol, M_FILEDESC_TO_LEADER);
2536 }
2537 
2538 /*
2539  * Release a filedesc structure.
2540  */
2541 static void
fdescfree_fds(struct thread * td,struct filedesc * fdp)2542 fdescfree_fds(struct thread *td, struct filedesc *fdp)
2543 {
2544 	struct filedesc0 *fdp0;
2545 	struct freetable *ft, *tft;
2546 	struct filedescent *fde;
2547 	struct file *fp;
2548 	int i;
2549 
2550 	KASSERT(refcount_load(&fdp->fd_refcnt) == 0,
2551 	    ("%s: fd table %p carries references", __func__, fdp));
2552 
2553 	/*
2554 	 * Serialize with threads iterating over the table, if any.
2555 	 */
2556 	if (refcount_load(&fdp->fd_holdcnt) > 1) {
2557 		FILEDESC_XLOCK(fdp);
2558 		FILEDESC_XUNLOCK(fdp);
2559 	}
2560 
2561 	FILEDESC_FOREACH_FDE(fdp, i, fde) {
2562 		fp = fde->fde_file;
2563 		fdefree_last(fde);
2564 		(void) closef(fp, td);
2565 	}
2566 
2567 	if (NDSLOTS(fdp->fd_nfiles) > NDSLOTS(NDFILE))
2568 		free(fdp->fd_map, M_FILEDESC);
2569 	if (fdp->fd_nfiles > NDFILE)
2570 		free(fdp->fd_files, M_FILEDESC);
2571 
2572 	fdp0 = (struct filedesc0 *)fdp;
2573 	SLIST_FOREACH_SAFE(ft, &fdp0->fd_free, ft_next, tft)
2574 		free(ft->ft_table, M_FILEDESC);
2575 
2576 	fddrop(fdp);
2577 }
2578 
2579 void
fdescfree(struct thread * td)2580 fdescfree(struct thread *td)
2581 {
2582 	struct proc *p;
2583 	struct filedesc *fdp;
2584 
2585 	p = td->td_proc;
2586 	fdp = p->p_fd;
2587 	MPASS(fdp != NULL);
2588 
2589 #ifdef RACCT
2590 	if (RACCT_ENABLED())
2591 		racct_set_unlocked(p, RACCT_NOFILE, 0);
2592 #endif
2593 
2594 	if (p->p_fdtol != NULL)
2595 		fdclearlocks(td);
2596 
2597 	/*
2598 	 * Check fdhold for an explanation.
2599 	 */
2600 	atomic_store_ptr(&p->p_fd, NULL);
2601 	atomic_thread_fence_seq_cst();
2602 	PROC_WAIT_UNLOCKED(p);
2603 
2604 	if (refcount_release(&fdp->fd_refcnt) == 0)
2605 		return;
2606 
2607 	fdescfree_fds(td, fdp);
2608 }
2609 
2610 void
pdescfree(struct thread * td)2611 pdescfree(struct thread *td)
2612 {
2613 	struct proc *p;
2614 	struct pwddesc *pdp;
2615 
2616 	p = td->td_proc;
2617 	pdp = p->p_pd;
2618 	MPASS(pdp != NULL);
2619 
2620 	/*
2621 	 * Check pdhold for an explanation.
2622 	 */
2623 	atomic_store_ptr(&p->p_pd, NULL);
2624 	atomic_thread_fence_seq_cst();
2625 	PROC_WAIT_UNLOCKED(p);
2626 
2627 	pddrop(pdp);
2628 }
2629 
2630 /*
2631  * For setugid programs, we don't want to people to use that setugidness
2632  * to generate error messages which write to a file which otherwise would
2633  * otherwise be off-limits to the process.  We check for filesystems where
2634  * the vnode can change out from under us after execve (like [lin]procfs).
2635  *
2636  * Since fdsetugidsafety calls this only for fd 0, 1 and 2, this check is
2637  * sufficient.  We also don't check for setugidness since we know we are.
2638  */
2639 static bool
is_unsafe(struct file * fp)2640 is_unsafe(struct file *fp)
2641 {
2642 	struct vnode *vp;
2643 
2644 	if (fp->f_type != DTYPE_VNODE)
2645 		return (false);
2646 
2647 	vp = fp->f_vnode;
2648 	return ((vp->v_vflag & VV_PROCDEP) != 0);
2649 }
2650 
2651 /*
2652  * Make this setguid thing safe, if at all possible.
2653  */
2654 void
fdsetugidsafety(struct thread * td)2655 fdsetugidsafety(struct thread *td)
2656 {
2657 	struct filedesc *fdp;
2658 	struct file *fp;
2659 	int i;
2660 
2661 	fdp = td->td_proc->p_fd;
2662 	KASSERT(refcount_load(&fdp->fd_refcnt) == 1,
2663 	    ("the fdtable should not be shared"));
2664 	MPASS(fdp->fd_nfiles >= 3);
2665 	for (i = 0; i <= 2; i++) {
2666 		fp = fdp->fd_ofiles[i].fde_file;
2667 		if (fp != NULL && is_unsafe(fp)) {
2668 			FILEDESC_XLOCK(fdp);
2669 			knote_fdclose(td, i);
2670 			/*
2671 			 * NULL-out descriptor prior to close to avoid
2672 			 * a race while close blocks.
2673 			 */
2674 			fdfree(fdp, i);
2675 			FILEDESC_XUNLOCK(fdp);
2676 			(void) closef(fp, td);
2677 		}
2678 	}
2679 }
2680 
2681 /*
2682  * If a specific file object occupies a specific file descriptor, close the
2683  * file descriptor entry and drop a reference on the file object.  This is a
2684  * convenience function to handle a subsequent error in a function that calls
2685  * falloc() that handles the race that another thread might have closed the
2686  * file descriptor out from under the thread creating the file object.
2687  */
2688 void
fdclose(struct thread * td,struct file * fp,int idx)2689 fdclose(struct thread *td, struct file *fp, int idx)
2690 {
2691 	struct filedesc *fdp = td->td_proc->p_fd;
2692 
2693 	FILEDESC_XLOCK(fdp);
2694 	if (fdp->fd_ofiles[idx].fde_file == fp) {
2695 		fdfree(fdp, idx);
2696 		FILEDESC_XUNLOCK(fdp);
2697 		fdrop(fp, td);
2698 	} else
2699 		FILEDESC_XUNLOCK(fdp);
2700 }
2701 
2702 /*
2703  * Close any files on exec?
2704  */
2705 void
fdcloseexec(struct thread * td)2706 fdcloseexec(struct thread *td)
2707 {
2708 	struct filedesc *fdp;
2709 	struct filedescent *fde;
2710 	struct file *fp;
2711 	int i;
2712 
2713 	fdp = td->td_proc->p_fd;
2714 	KASSERT(refcount_load(&fdp->fd_refcnt) == 1,
2715 	    ("the fdtable should not be shared"));
2716 	FILEDESC_FOREACH_FDE(fdp, i, fde) {
2717 		fp = fde->fde_file;
2718 		if (fp->f_type == DTYPE_MQUEUE ||
2719 		    (fde->fde_flags & UF_EXCLOSE)) {
2720 			FILEDESC_XLOCK(fdp);
2721 			fdfree(fdp, i);
2722 			(void) closefp(fdp, i, fp, td, false, false);
2723 			FILEDESC_UNLOCK_ASSERT(fdp);
2724 		}
2725 	}
2726 }
2727 
2728 /*
2729  * It is unsafe for set[ug]id processes to be started with file
2730  * descriptors 0..2 closed, as these descriptors are given implicit
2731  * significance in the Standard C library.  fdcheckstd() will create a
2732  * descriptor referencing /dev/null for each of stdin, stdout, and
2733  * stderr that is not already open.
2734  */
2735 int
fdcheckstd(struct thread * td)2736 fdcheckstd(struct thread *td)
2737 {
2738 	struct filedesc *fdp;
2739 	register_t save;
2740 	int i, error, devnull;
2741 
2742 	fdp = td->td_proc->p_fd;
2743 	KASSERT(refcount_load(&fdp->fd_refcnt) == 1,
2744 	    ("the fdtable should not be shared"));
2745 	MPASS(fdp->fd_nfiles >= 3);
2746 	devnull = -1;
2747 	for (i = 0; i <= 2; i++) {
2748 		if (fdp->fd_ofiles[i].fde_file != NULL)
2749 			continue;
2750 
2751 		save = td->td_retval[0];
2752 		if (devnull != -1) {
2753 			error = kern_dup(td, FDDUP_FIXED, 0, devnull, i);
2754 		} else {
2755 			error = kern_openat(td, AT_FDCWD, "/dev/null",
2756 			    UIO_SYSSPACE, O_RDWR, 0);
2757 			if (error == 0) {
2758 				devnull = td->td_retval[0];
2759 				KASSERT(devnull == i, ("we didn't get our fd"));
2760 			}
2761 		}
2762 		td->td_retval[0] = save;
2763 		if (error != 0)
2764 			return (error);
2765 	}
2766 	return (0);
2767 }
2768 
2769 /*
2770  * Internal form of close.  Decrement reference count on file structure.
2771  * Note: td may be NULL when closing a file that was being passed in a
2772  * message.
2773  */
2774 int
closef(struct file * fp,struct thread * td)2775 closef(struct file *fp, struct thread *td)
2776 {
2777 	struct vnode *vp;
2778 	struct flock lf;
2779 	struct filedesc_to_leader *fdtol;
2780 	struct filedesc *fdp;
2781 
2782 	MPASS(td != NULL);
2783 
2784 	/*
2785 	 * POSIX record locking dictates that any close releases ALL
2786 	 * locks owned by this process.  This is handled by setting
2787 	 * a flag in the unlock to free ONLY locks obeying POSIX
2788 	 * semantics, and not to free BSD-style file locks.
2789 	 * If the descriptor was in a message, POSIX-style locks
2790 	 * aren't passed with the descriptor, and the thread pointer
2791 	 * will be NULL.  Callers should be careful only to pass a
2792 	 * NULL thread pointer when there really is no owning
2793 	 * context that might have locks, or the locks will be
2794 	 * leaked.
2795 	 */
2796 	if (fp->f_type == DTYPE_VNODE) {
2797 		vp = fp->f_vnode;
2798 		if ((td->td_proc->p_leader->p_flag & P_ADVLOCK) != 0) {
2799 			lf.l_whence = SEEK_SET;
2800 			lf.l_start = 0;
2801 			lf.l_len = 0;
2802 			lf.l_type = F_UNLCK;
2803 			(void) VOP_ADVLOCK(vp, (caddr_t)td->td_proc->p_leader,
2804 			    F_UNLCK, &lf, F_POSIX);
2805 		}
2806 		fdtol = td->td_proc->p_fdtol;
2807 		if (fdtol != NULL) {
2808 			/*
2809 			 * Handle special case where file descriptor table is
2810 			 * shared between multiple process leaders.
2811 			 */
2812 			fdp = td->td_proc->p_fd;
2813 			FILEDESC_XLOCK(fdp);
2814 			for (fdtol = fdtol->fdl_next;
2815 			    fdtol != td->td_proc->p_fdtol;
2816 			    fdtol = fdtol->fdl_next) {
2817 				if ((fdtol->fdl_leader->p_flag &
2818 				    P_ADVLOCK) == 0)
2819 					continue;
2820 				fdtol->fdl_holdcount++;
2821 				FILEDESC_XUNLOCK(fdp);
2822 				lf.l_whence = SEEK_SET;
2823 				lf.l_start = 0;
2824 				lf.l_len = 0;
2825 				lf.l_type = F_UNLCK;
2826 				vp = fp->f_vnode;
2827 				(void) VOP_ADVLOCK(vp,
2828 				    (caddr_t)fdtol->fdl_leader, F_UNLCK, &lf,
2829 				    F_POSIX);
2830 				FILEDESC_XLOCK(fdp);
2831 				fdtol->fdl_holdcount--;
2832 				if (fdtol->fdl_holdcount == 0 &&
2833 				    fdtol->fdl_wakeup != 0) {
2834 					fdtol->fdl_wakeup = 0;
2835 					wakeup(fdtol);
2836 				}
2837 			}
2838 			FILEDESC_XUNLOCK(fdp);
2839 		}
2840 	}
2841 	return (fdrop_close(fp, td));
2842 }
2843 
2844 /*
2845  * Hack for file descriptor passing code.
2846  */
2847 void
closef_nothread(struct file * fp)2848 closef_nothread(struct file *fp)
2849 {
2850 
2851 	fdrop(fp, NULL);
2852 }
2853 
2854 /*
2855  * Initialize the file pointer with the specified properties.
2856  *
2857  * The ops are set with release semantics to be certain that the flags, type,
2858  * and data are visible when ops is.  This is to prevent ops methods from being
2859  * called with bad data.
2860  */
2861 void
finit(struct file * fp,u_int flag,short type,void * data,const struct fileops * ops)2862 finit(struct file *fp, u_int flag, short type, void *data,
2863     const struct fileops *ops)
2864 {
2865 	fp->f_data = data;
2866 	fp->f_flag = flag;
2867 	fp->f_type = type;
2868 	atomic_store_rel_ptr((volatile uintptr_t *)&fp->f_ops, (uintptr_t)ops);
2869 }
2870 
2871 void
finit_vnode(struct file * fp,u_int flag,void * data,const struct fileops * ops)2872 finit_vnode(struct file *fp, u_int flag, void *data, const struct fileops *ops)
2873 {
2874 	fp->f_seqcount[UIO_READ] = 1;
2875 	fp->f_seqcount[UIO_WRITE] = 1;
2876 	finit(fp, (flag & FMASK) | (fp->f_flag & FHASLOCK), DTYPE_VNODE,
2877 	    data, ops);
2878 }
2879 
2880 int
fget_cap_noref(struct filedesc * fdp,int fd,cap_rights_t * needrightsp,struct file ** fpp,struct filecaps * havecapsp)2881 fget_cap_noref(struct filedesc *fdp, int fd, cap_rights_t *needrightsp,
2882     struct file **fpp, struct filecaps *havecapsp)
2883 {
2884 	struct filedescent *fde;
2885 	int error;
2886 
2887 	FILEDESC_LOCK_ASSERT(fdp);
2888 
2889 	*fpp = NULL;
2890 	fde = fdeget_noref(fdp, fd);
2891 	if (fde == NULL) {
2892 		error = EBADF;
2893 		goto out;
2894 	}
2895 
2896 #ifdef CAPABILITIES
2897 	error = cap_check(cap_rights_fde_inline(fde), needrightsp);
2898 	if (error != 0)
2899 		goto out;
2900 #endif
2901 
2902 	if (havecapsp != NULL)
2903 		filecaps_copy(&fde->fde_caps, havecapsp, true);
2904 
2905 	*fpp = fde->fde_file;
2906 
2907 	error = 0;
2908 out:
2909 	return (error);
2910 }
2911 
2912 #ifdef CAPABILITIES
2913 int
fget_cap(struct thread * td,int fd,cap_rights_t * needrightsp,struct file ** fpp,struct filecaps * havecapsp)2914 fget_cap(struct thread *td, int fd, cap_rights_t *needrightsp,
2915     struct file **fpp, struct filecaps *havecapsp)
2916 {
2917 	struct filedesc *fdp = td->td_proc->p_fd;
2918 	int error;
2919 	struct file *fp;
2920 	seqc_t seq;
2921 
2922 	*fpp = NULL;
2923 	for (;;) {
2924 		error = fget_unlocked_seq(td, fd, needrightsp, &fp, &seq);
2925 		if (error != 0)
2926 			return (error);
2927 
2928 		if (havecapsp != NULL) {
2929 			if (!filecaps_copy(&fdp->fd_ofiles[fd].fde_caps,
2930 			    havecapsp, false)) {
2931 				fdrop(fp, td);
2932 				goto get_locked;
2933 			}
2934 		}
2935 
2936 		if (!fd_modified(fdp, fd, seq))
2937 			break;
2938 		fdrop(fp, td);
2939 	}
2940 
2941 	*fpp = fp;
2942 	return (0);
2943 
2944 get_locked:
2945 	FILEDESC_SLOCK(fdp);
2946 	error = fget_cap_noref(fdp, fd, needrightsp, fpp, havecapsp);
2947 	if (error == 0 && !fhold(*fpp))
2948 		error = EBADF;
2949 	FILEDESC_SUNLOCK(fdp);
2950 	return (error);
2951 }
2952 #else
2953 int
fget_cap(struct thread * td,int fd,cap_rights_t * needrightsp,struct file ** fpp,struct filecaps * havecapsp)2954 fget_cap(struct thread *td, int fd, cap_rights_t *needrightsp,
2955     struct file **fpp, struct filecaps *havecapsp)
2956 {
2957 	int error;
2958 	error = fget_unlocked(td, fd, needrightsp, fpp);
2959 	if (havecapsp != NULL && error == 0)
2960 		filecaps_fill(havecapsp);
2961 
2962 	return (error);
2963 }
2964 #endif
2965 
2966 int
fget_remote(struct thread * td,struct proc * p,int fd,struct file ** fpp)2967 fget_remote(struct thread *td, struct proc *p, int fd, struct file **fpp)
2968 {
2969 	struct filedesc *fdp;
2970 	struct file *fp;
2971 	int error;
2972 
2973 	if (p == td->td_proc)	/* curproc */
2974 		return (fget_unlocked(td, fd, &cap_no_rights, fpp));
2975 
2976 	PROC_LOCK(p);
2977 	fdp = fdhold(p);
2978 	PROC_UNLOCK(p);
2979 	if (fdp == NULL)
2980 		return (ENOENT);
2981 	FILEDESC_SLOCK(fdp);
2982 	if (refcount_load(&fdp->fd_refcnt) != 0) {
2983 		fp = fget_noref(fdp, fd);
2984 		if (fp != NULL && fhold(fp)) {
2985 			*fpp = fp;
2986 			error = 0;
2987 		} else {
2988 			error = EBADF;
2989 		}
2990 	} else {
2991 		error = ENOENT;
2992 	}
2993 	FILEDESC_SUNLOCK(fdp);
2994 	fddrop(fdp);
2995 	return (error);
2996 }
2997 
2998 #ifdef CAPABILITIES
2999 int
fgetvp_lookup_smr(struct nameidata * ndp,struct vnode ** vpp,bool * fsearch)3000 fgetvp_lookup_smr(struct nameidata *ndp, struct vnode **vpp, bool *fsearch)
3001 {
3002 	const struct filedescent *fde;
3003 	const struct fdescenttbl *fdt;
3004 	struct filedesc *fdp;
3005 	struct file *fp;
3006 	struct vnode *vp;
3007 	const cap_rights_t *haverights;
3008 	cap_rights_t rights;
3009 	seqc_t seq;
3010 	int fd;
3011 
3012 	VFS_SMR_ASSERT_ENTERED();
3013 
3014 	fd = ndp->ni_dirfd;
3015 	rights = *ndp->ni_rightsneeded;
3016 	cap_rights_set_one(&rights, CAP_LOOKUP);
3017 
3018 	fdp = curproc->p_fd;
3019 	fdt = fdp->fd_files;
3020 	if (__predict_false((u_int)fd >= fdt->fdt_nfiles))
3021 		return (EBADF);
3022 	seq = seqc_read_notmodify(fd_seqc(fdt, fd));
3023 	fde = &fdt->fdt_ofiles[fd];
3024 	haverights = cap_rights_fde_inline(fde);
3025 	fp = fde->fde_file;
3026 	if (__predict_false(fp == NULL))
3027 		return (EAGAIN);
3028 	if (__predict_false(cap_check_inline_transient(haverights, &rights)))
3029 		return (EAGAIN);
3030 	*fsearch = ((fp->f_flag & FSEARCH) != 0);
3031 	vp = fp->f_vnode;
3032 	if (__predict_false(vp == NULL)) {
3033 		return (EAGAIN);
3034 	}
3035 	if (!filecaps_copy(&fde->fde_caps, &ndp->ni_filecaps, false)) {
3036 		return (EAGAIN);
3037 	}
3038 	/*
3039 	 * Use an acquire barrier to force re-reading of fdt so it is
3040 	 * refreshed for verification.
3041 	 */
3042 	atomic_thread_fence_acq();
3043 	fdt = fdp->fd_files;
3044 	if (__predict_false(!seqc_consistent_no_fence(fd_seqc(fdt, fd), seq)))
3045 		return (EAGAIN);
3046 	/*
3047 	 * If file descriptor doesn't have all rights,
3048 	 * all lookups relative to it must also be
3049 	 * strictly relative.
3050 	 *
3051 	 * Not yet supported by fast path.
3052 	 */
3053 	CAP_ALL(&rights);
3054 	if (!cap_rights_contains(&ndp->ni_filecaps.fc_rights, &rights) ||
3055 	    ndp->ni_filecaps.fc_fcntls != CAP_FCNTL_ALL ||
3056 	    ndp->ni_filecaps.fc_nioctls != -1) {
3057 #ifdef notyet
3058 		ndp->ni_lcf |= NI_LCF_STRICTREL;
3059 #else
3060 		return (EAGAIN);
3061 #endif
3062 	}
3063 	*vpp = vp;
3064 	return (0);
3065 }
3066 #else
3067 int
fgetvp_lookup_smr(struct nameidata * ndp,struct vnode ** vpp,bool * fsearch)3068 fgetvp_lookup_smr(struct nameidata *ndp, struct vnode **vpp, bool *fsearch)
3069 {
3070 	const struct fdescenttbl *fdt;
3071 	struct filedesc *fdp;
3072 	struct file *fp;
3073 	struct vnode *vp;
3074 	int fd;
3075 
3076 	VFS_SMR_ASSERT_ENTERED();
3077 
3078 	fd = ndp->ni_dirfd;
3079 	fdp = curproc->p_fd;
3080 	fdt = fdp->fd_files;
3081 	if (__predict_false((u_int)fd >= fdt->fdt_nfiles))
3082 		return (EBADF);
3083 	fp = fdt->fdt_ofiles[fd].fde_file;
3084 	if (__predict_false(fp == NULL))
3085 		return (EAGAIN);
3086 	*fsearch = ((fp->f_flag & FSEARCH) != 0);
3087 	vp = fp->f_vnode;
3088 	if (__predict_false(vp == NULL || vp->v_type != VDIR)) {
3089 		return (EAGAIN);
3090 	}
3091 	/*
3092 	 * Use an acquire barrier to force re-reading of fdt so it is
3093 	 * refreshed for verification.
3094 	 */
3095 	atomic_thread_fence_acq();
3096 	fdt = fdp->fd_files;
3097 	if (__predict_false(fp != fdt->fdt_ofiles[fd].fde_file))
3098 		return (EAGAIN);
3099 	filecaps_fill(&ndp->ni_filecaps);
3100 	*vpp = vp;
3101 	return (0);
3102 }
3103 #endif
3104 
3105 int
fgetvp_lookup(struct nameidata * ndp,struct vnode ** vpp)3106 fgetvp_lookup(struct nameidata *ndp, struct vnode **vpp)
3107 {
3108 	struct thread *td;
3109 	struct file *fp;
3110 	struct vnode *vp;
3111 	struct componentname *cnp;
3112 	cap_rights_t rights;
3113 	int error;
3114 
3115 	td = curthread;
3116 	rights = *ndp->ni_rightsneeded;
3117 	cap_rights_set_one(&rights, CAP_LOOKUP);
3118 	cnp = &ndp->ni_cnd;
3119 
3120 	error = fget_cap(td, ndp->ni_dirfd, &rights, &fp, &ndp->ni_filecaps);
3121 	if (__predict_false(error != 0))
3122 		return (error);
3123 	if (__predict_false(fp->f_ops == &badfileops)) {
3124 		error = EBADF;
3125 		goto out_free;
3126 	}
3127 	vp = fp->f_vnode;
3128 	if (__predict_false(vp == NULL)) {
3129 		error = ENOTDIR;
3130 		goto out_free;
3131 	}
3132 	vrefact(vp);
3133 	/*
3134 	 * XXX does not check for VDIR, handled by namei_setup
3135 	 */
3136 	if ((fp->f_flag & FSEARCH) != 0)
3137 		cnp->cn_flags |= NOEXECCHECK;
3138 	fdrop(fp, td);
3139 
3140 #ifdef CAPABILITIES
3141 	/*
3142 	 * If file descriptor doesn't have all rights,
3143 	 * all lookups relative to it must also be
3144 	 * strictly relative.
3145 	 */
3146 	CAP_ALL(&rights);
3147 	if (!cap_rights_contains(&ndp->ni_filecaps.fc_rights, &rights) ||
3148 	    ndp->ni_filecaps.fc_fcntls != CAP_FCNTL_ALL ||
3149 	    ndp->ni_filecaps.fc_nioctls != -1) {
3150 		ndp->ni_lcf |= NI_LCF_STRICTREL;
3151 		ndp->ni_resflags |= NIRES_STRICTREL;
3152 	}
3153 #endif
3154 
3155 	/*
3156 	 * TODO: avoid copying ioctl caps if it can be helped to begin with
3157 	 */
3158 	if ((cnp->cn_flags & WANTIOCTLCAPS) == 0)
3159 		filecaps_free_ioctl(&ndp->ni_filecaps);
3160 
3161 	*vpp = vp;
3162 	return (0);
3163 
3164 out_free:
3165 	filecaps_free(&ndp->ni_filecaps);
3166 	fdrop(fp, td);
3167 	return (error);
3168 }
3169 
3170 /*
3171  * Fetch the descriptor locklessly.
3172  *
3173  * We avoid fdrop() races by never raising a refcount above 0.  To accomplish
3174  * this we have to use a cmpset loop rather than an atomic_add.  The descriptor
3175  * must be re-verified once we acquire a reference to be certain that the
3176  * identity is still correct and we did not lose a race due to preemption.
3177  *
3178  * Force a reload of fdt when looping. Another thread could reallocate
3179  * the table before this fd was closed, so it is possible that there is
3180  * a stale fp pointer in cached version.
3181  */
3182 #ifdef CAPABILITIES
3183 static int
fget_unlocked_seq(struct thread * td,int fd,cap_rights_t * needrightsp,struct file ** fpp,seqc_t * seqp)3184 fget_unlocked_seq(struct thread *td, int fd, cap_rights_t *needrightsp,
3185     struct file **fpp, seqc_t *seqp)
3186 {
3187 	struct filedesc *fdp;
3188 	const struct filedescent *fde;
3189 	const struct fdescenttbl *fdt;
3190 	struct file *fp;
3191 	seqc_t seq;
3192 	cap_rights_t haverights;
3193 	int error;
3194 
3195 	fdp = td->td_proc->p_fd;
3196 	fdt = fdp->fd_files;
3197 	if (__predict_false((u_int)fd >= fdt->fdt_nfiles))
3198 		return (EBADF);
3199 
3200 	for (;;) {
3201 		seq = seqc_read_notmodify(fd_seqc(fdt, fd));
3202 		fde = &fdt->fdt_ofiles[fd];
3203 		haverights = *cap_rights_fde_inline(fde);
3204 		fp = fde->fde_file;
3205 		if (__predict_false(fp == NULL)) {
3206 			if (seqc_consistent(fd_seqc(fdt, fd), seq))
3207 				return (EBADF);
3208 			fdt = atomic_load_ptr(&fdp->fd_files);
3209 			continue;
3210 		}
3211 		error = cap_check_inline(&haverights, needrightsp);
3212 		if (__predict_false(error != 0)) {
3213 			if (seqc_consistent(fd_seqc(fdt, fd), seq))
3214 				return (error);
3215 			fdt = atomic_load_ptr(&fdp->fd_files);
3216 			continue;
3217 		}
3218 		if (__predict_false(!refcount_acquire_if_not_zero(&fp->f_count))) {
3219 			fdt = atomic_load_ptr(&fdp->fd_files);
3220 			continue;
3221 		}
3222 		/*
3223 		 * Use an acquire barrier to force re-reading of fdt so it is
3224 		 * refreshed for verification.
3225 		 */
3226 		atomic_thread_fence_acq();
3227 		fdt = fdp->fd_files;
3228 		if (seqc_consistent_no_fence(fd_seqc(fdt, fd), seq))
3229 			break;
3230 		fdrop(fp, td);
3231 	}
3232 	*fpp = fp;
3233 	if (seqp != NULL) {
3234 		*seqp = seq;
3235 	}
3236 	return (0);
3237 }
3238 #else
3239 static int
fget_unlocked_seq(struct thread * td,int fd,cap_rights_t * needrightsp,struct file ** fpp,seqc_t * seqp __unused)3240 fget_unlocked_seq(struct thread *td, int fd, cap_rights_t *needrightsp,
3241     struct file **fpp, seqc_t *seqp __unused)
3242 {
3243 	struct filedesc *fdp;
3244 	const struct fdescenttbl *fdt;
3245 	struct file *fp;
3246 
3247 	fdp = td->td_proc->p_fd;
3248 	fdt = fdp->fd_files;
3249 	if (__predict_false((u_int)fd >= fdt->fdt_nfiles))
3250 		return (EBADF);
3251 
3252 	for (;;) {
3253 		fp = fdt->fdt_ofiles[fd].fde_file;
3254 		if (__predict_false(fp == NULL))
3255 			return (EBADF);
3256 		if (__predict_false(!refcount_acquire_if_not_zero(&fp->f_count))) {
3257 			fdt = atomic_load_ptr(&fdp->fd_files);
3258 			continue;
3259 		}
3260 		/*
3261 		 * Use an acquire barrier to force re-reading of fdt so it is
3262 		 * refreshed for verification.
3263 		 */
3264 		atomic_thread_fence_acq();
3265 		fdt = fdp->fd_files;
3266 		if (__predict_true(fp == fdt->fdt_ofiles[fd].fde_file))
3267 			break;
3268 		fdrop(fp, td);
3269 	}
3270 	*fpp = fp;
3271 	return (0);
3272 }
3273 #endif
3274 
3275 /*
3276  * See the comments in fget_unlocked_seq for an explanation of how this works.
3277  *
3278  * This is a simplified variant which bails out to the aforementioned routine
3279  * if anything goes wrong. In practice this only happens when userspace is
3280  * racing with itself.
3281  */
3282 int
fget_unlocked(struct thread * td,int fd,cap_rights_t * needrightsp,struct file ** fpp)3283 fget_unlocked(struct thread *td, int fd, cap_rights_t *needrightsp,
3284     struct file **fpp)
3285 {
3286 	struct filedesc *fdp;
3287 #ifdef CAPABILITIES
3288 	const struct filedescent *fde;
3289 #endif
3290 	const struct fdescenttbl *fdt;
3291 	struct file *fp;
3292 #ifdef CAPABILITIES
3293 	seqc_t seq;
3294 	const cap_rights_t *haverights;
3295 #endif
3296 
3297 	fdp = td->td_proc->p_fd;
3298 	fdt = fdp->fd_files;
3299 	if (__predict_false((u_int)fd >= fdt->fdt_nfiles)) {
3300 		*fpp = NULL;
3301 		return (EBADF);
3302 	}
3303 #ifdef CAPABILITIES
3304 	seq = seqc_read_notmodify(fd_seqc(fdt, fd));
3305 	fde = &fdt->fdt_ofiles[fd];
3306 	haverights = cap_rights_fde_inline(fde);
3307 	fp = fde->fde_file;
3308 #else
3309 	fp = fdt->fdt_ofiles[fd].fde_file;
3310 #endif
3311 	if (__predict_false(fp == NULL))
3312 		goto out_fallback;
3313 #ifdef CAPABILITIES
3314 	if (__predict_false(cap_check_inline_transient(haverights, needrightsp)))
3315 		goto out_fallback;
3316 #endif
3317 	if (__predict_false(!refcount_acquire_if_not_zero(&fp->f_count)))
3318 		goto out_fallback;
3319 
3320 	/*
3321 	 * Use an acquire barrier to force re-reading of fdt so it is
3322 	 * refreshed for verification.
3323 	 */
3324 	atomic_thread_fence_acq();
3325 	fdt = fdp->fd_files;
3326 #ifdef	CAPABILITIES
3327 	if (__predict_false(!seqc_consistent_no_fence(fd_seqc(fdt, fd), seq)))
3328 #else
3329 	if (__predict_false(fp != fdt->fdt_ofiles[fd].fde_file))
3330 #endif
3331 		goto out_fdrop;
3332 	*fpp = fp;
3333 	return (0);
3334 out_fdrop:
3335 	fdrop(fp, td);
3336 out_fallback:
3337 	*fpp = NULL;
3338 	return (fget_unlocked_seq(td, fd, needrightsp, fpp, NULL));
3339 }
3340 
3341 /*
3342  * Translate fd -> file when the caller guarantees the file descriptor table
3343  * can't be changed by others.
3344  *
3345  * Note this does not mean the file object itself is only visible to the caller,
3346  * merely that it wont disappear without having to be referenced.
3347  *
3348  * Must be paired with fput_only_user.
3349  */
3350 #ifdef	CAPABILITIES
3351 int
fget_only_user(struct filedesc * fdp,int fd,cap_rights_t * needrightsp,struct file ** fpp)3352 fget_only_user(struct filedesc *fdp, int fd, cap_rights_t *needrightsp,
3353     struct file **fpp)
3354 {
3355 	const struct filedescent *fde;
3356 	const struct fdescenttbl *fdt;
3357 	const cap_rights_t *haverights;
3358 	struct file *fp;
3359 	int error;
3360 
3361 	MPASS(FILEDESC_IS_ONLY_USER(fdp));
3362 
3363 	*fpp = NULL;
3364 	if (__predict_false(fd >= fdp->fd_nfiles))
3365 		return (EBADF);
3366 
3367 	fdt = fdp->fd_files;
3368 	fde = &fdt->fdt_ofiles[fd];
3369 	fp = fde->fde_file;
3370 	if (__predict_false(fp == NULL))
3371 		return (EBADF);
3372 	MPASS(refcount_load(&fp->f_count) > 0);
3373 	haverights = cap_rights_fde_inline(fde);
3374 	error = cap_check_inline(haverights, needrightsp);
3375 	if (__predict_false(error != 0))
3376 		return (error);
3377 	*fpp = fp;
3378 	return (0);
3379 }
3380 #else
3381 int
fget_only_user(struct filedesc * fdp,int fd,cap_rights_t * needrightsp,struct file ** fpp)3382 fget_only_user(struct filedesc *fdp, int fd, cap_rights_t *needrightsp,
3383     struct file **fpp)
3384 {
3385 	struct file *fp;
3386 
3387 	MPASS(FILEDESC_IS_ONLY_USER(fdp));
3388 
3389 	*fpp = NULL;
3390 	if (__predict_false(fd >= fdp->fd_nfiles))
3391 		return (EBADF);
3392 
3393 	fp = fdp->fd_ofiles[fd].fde_file;
3394 	if (__predict_false(fp == NULL))
3395 		return (EBADF);
3396 
3397 	MPASS(refcount_load(&fp->f_count) > 0);
3398 	*fpp = fp;
3399 	return (0);
3400 }
3401 #endif
3402 
3403 /*
3404  * Extract the file pointer associated with the specified descriptor for the
3405  * current user process.
3406  *
3407  * If the descriptor doesn't exist or doesn't match 'flags', EBADF is
3408  * returned.
3409  *
3410  * File's rights will be checked against the capability rights mask.
3411  *
3412  * If an error occurred the non-zero error is returned and *fpp is set to
3413  * NULL.  Otherwise *fpp is held and set and zero is returned.  Caller is
3414  * responsible for fdrop().
3415  */
3416 static __inline int
_fget(struct thread * td,int fd,struct file ** fpp,int flags,cap_rights_t * needrightsp)3417 _fget(struct thread *td, int fd, struct file **fpp, int flags,
3418     cap_rights_t *needrightsp)
3419 {
3420 	struct file *fp;
3421 	int error;
3422 
3423 	*fpp = NULL;
3424 	error = fget_unlocked(td, fd, needrightsp, &fp);
3425 	if (__predict_false(error != 0))
3426 		return (error);
3427 	if (__predict_false(fp->f_ops == &badfileops)) {
3428 		fdrop(fp, td);
3429 		return (EBADF);
3430 	}
3431 
3432 	/*
3433 	 * FREAD and FWRITE failure return EBADF as per POSIX.
3434 	 */
3435 	error = 0;
3436 	switch (flags) {
3437 	case FREAD:
3438 	case FWRITE:
3439 		if ((fp->f_flag & flags) == 0)
3440 			error = EBADF;
3441 		break;
3442 	case FEXEC:
3443 		if (fp->f_ops != &path_fileops &&
3444 		    ((fp->f_flag & (FREAD | FEXEC)) == 0 ||
3445 		    (fp->f_flag & FWRITE) != 0))
3446 			error = EBADF;
3447 		break;
3448 	case 0:
3449 		break;
3450 	default:
3451 		KASSERT(0, ("wrong flags"));
3452 	}
3453 
3454 	if (error != 0) {
3455 		fdrop(fp, td);
3456 		return (error);
3457 	}
3458 
3459 	*fpp = fp;
3460 	return (0);
3461 }
3462 
3463 int
fget(struct thread * td,int fd,cap_rights_t * rightsp,struct file ** fpp)3464 fget(struct thread *td, int fd, cap_rights_t *rightsp, struct file **fpp)
3465 {
3466 
3467 	return (_fget(td, fd, fpp, 0, rightsp));
3468 }
3469 
3470 int
fget_mmap(struct thread * td,int fd,cap_rights_t * rightsp,vm_prot_t * maxprotp,struct file ** fpp)3471 fget_mmap(struct thread *td, int fd, cap_rights_t *rightsp, vm_prot_t *maxprotp,
3472     struct file **fpp)
3473 {
3474 	int error;
3475 #ifndef CAPABILITIES
3476 	error = _fget(td, fd, fpp, 0, rightsp);
3477 	if (maxprotp != NULL)
3478 		*maxprotp = VM_PROT_ALL;
3479 	return (error);
3480 #else
3481 	cap_rights_t fdrights;
3482 	struct filedesc *fdp;
3483 	struct file *fp;
3484 	seqc_t seq;
3485 
3486 	*fpp = NULL;
3487 	fdp = td->td_proc->p_fd;
3488 	MPASS(cap_rights_is_set(rightsp, CAP_MMAP));
3489 	for (;;) {
3490 		error = fget_unlocked_seq(td, fd, rightsp, &fp, &seq);
3491 		if (__predict_false(error != 0))
3492 			return (error);
3493 		if (__predict_false(fp->f_ops == &badfileops)) {
3494 			fdrop(fp, td);
3495 			return (EBADF);
3496 		}
3497 		if (maxprotp != NULL)
3498 			fdrights = *cap_rights(fdp, fd);
3499 		if (!fd_modified(fdp, fd, seq))
3500 			break;
3501 		fdrop(fp, td);
3502 	}
3503 
3504 	/*
3505 	 * If requested, convert capability rights to access flags.
3506 	 */
3507 	if (maxprotp != NULL)
3508 		*maxprotp = cap_rights_to_vmprot(&fdrights);
3509 	*fpp = fp;
3510 	return (0);
3511 #endif
3512 }
3513 
3514 int
fget_read(struct thread * td,int fd,cap_rights_t * rightsp,struct file ** fpp)3515 fget_read(struct thread *td, int fd, cap_rights_t *rightsp, struct file **fpp)
3516 {
3517 
3518 	return (_fget(td, fd, fpp, FREAD, rightsp));
3519 }
3520 
3521 int
fget_write(struct thread * td,int fd,cap_rights_t * rightsp,struct file ** fpp)3522 fget_write(struct thread *td, int fd, cap_rights_t *rightsp, struct file **fpp)
3523 {
3524 
3525 	return (_fget(td, fd, fpp, FWRITE, rightsp));
3526 }
3527 
3528 int
fget_fcntl(struct thread * td,int fd,cap_rights_t * rightsp,int needfcntl,struct file ** fpp)3529 fget_fcntl(struct thread *td, int fd, cap_rights_t *rightsp, int needfcntl,
3530     struct file **fpp)
3531 {
3532 #ifndef CAPABILITIES
3533 	return (fget_unlocked(td, fd, rightsp, fpp));
3534 #else
3535 	struct filedesc *fdp = td->td_proc->p_fd;
3536 	struct file *fp;
3537 	int error;
3538 	seqc_t seq;
3539 
3540 	*fpp = NULL;
3541 	MPASS(cap_rights_is_set(rightsp, CAP_FCNTL));
3542 	for (;;) {
3543 		error = fget_unlocked_seq(td, fd, rightsp, &fp, &seq);
3544 		if (error != 0)
3545 			return (error);
3546 		error = cap_fcntl_check(fdp, fd, needfcntl);
3547 		if (!fd_modified(fdp, fd, seq))
3548 			break;
3549 		fdrop(fp, td);
3550 	}
3551 	if (error != 0) {
3552 		fdrop(fp, td);
3553 		return (error);
3554 	}
3555 	*fpp = fp;
3556 	return (0);
3557 #endif
3558 }
3559 
3560 /*
3561  * Like fget() but loads the underlying vnode, or returns an error if the
3562  * descriptor does not represent a vnode.  Note that pipes use vnodes but
3563  * never have VM objects.  The returned vnode will be vref()'d.
3564  *
3565  * XXX: what about the unused flags ?
3566  */
3567 static __inline int
_fgetvp(struct thread * td,int fd,int flags,cap_rights_t * needrightsp,struct vnode ** vpp)3568 _fgetvp(struct thread *td, int fd, int flags, cap_rights_t *needrightsp,
3569     struct vnode **vpp)
3570 {
3571 	struct file *fp;
3572 	int error;
3573 
3574 	*vpp = NULL;
3575 	error = _fget(td, fd, &fp, flags, needrightsp);
3576 	if (error != 0)
3577 		return (error);
3578 	if (fp->f_vnode == NULL) {
3579 		error = EINVAL;
3580 	} else {
3581 		*vpp = fp->f_vnode;
3582 		vrefact(*vpp);
3583 	}
3584 	fdrop(fp, td);
3585 
3586 	return (error);
3587 }
3588 
3589 int
fgetvp(struct thread * td,int fd,cap_rights_t * rightsp,struct vnode ** vpp)3590 fgetvp(struct thread *td, int fd, cap_rights_t *rightsp, struct vnode **vpp)
3591 {
3592 
3593 	return (_fgetvp(td, fd, 0, rightsp, vpp));
3594 }
3595 
3596 int
fgetvp_rights(struct thread * td,int fd,cap_rights_t * needrightsp,struct filecaps * havecaps,struct vnode ** vpp)3597 fgetvp_rights(struct thread *td, int fd, cap_rights_t *needrightsp,
3598     struct filecaps *havecaps, struct vnode **vpp)
3599 {
3600 	struct filecaps caps;
3601 	struct file *fp;
3602 	int error;
3603 
3604 	error = fget_cap(td, fd, needrightsp, &fp, &caps);
3605 	if (error != 0)
3606 		return (error);
3607 	if (fp->f_ops == &badfileops) {
3608 		error = EBADF;
3609 		goto out;
3610 	}
3611 	if (fp->f_vnode == NULL) {
3612 		error = EINVAL;
3613 		goto out;
3614 	}
3615 
3616 	*havecaps = caps;
3617 	*vpp = fp->f_vnode;
3618 	vrefact(*vpp);
3619 	fdrop(fp, td);
3620 
3621 	return (0);
3622 out:
3623 	filecaps_free(&caps);
3624 	fdrop(fp, td);
3625 	return (error);
3626 }
3627 
3628 int
fgetvp_read(struct thread * td,int fd,cap_rights_t * rightsp,struct vnode ** vpp)3629 fgetvp_read(struct thread *td, int fd, cap_rights_t *rightsp, struct vnode **vpp)
3630 {
3631 
3632 	return (_fgetvp(td, fd, FREAD, rightsp, vpp));
3633 }
3634 
3635 int
fgetvp_exec(struct thread * td,int fd,cap_rights_t * rightsp,struct vnode ** vpp)3636 fgetvp_exec(struct thread *td, int fd, cap_rights_t *rightsp, struct vnode **vpp)
3637 {
3638 
3639 	return (_fgetvp(td, fd, FEXEC, rightsp, vpp));
3640 }
3641 
3642 #ifdef notyet
3643 int
fgetvp_write(struct thread * td,int fd,cap_rights_t * rightsp,struct vnode ** vpp)3644 fgetvp_write(struct thread *td, int fd, cap_rights_t *rightsp,
3645     struct vnode **vpp)
3646 {
3647 
3648 	return (_fgetvp(td, fd, FWRITE, rightsp, vpp));
3649 }
3650 #endif
3651 
3652 /*
3653  * Handle the last reference to a file being closed.
3654  *
3655  * Without the noinline attribute clang keeps inlining the func thorough this
3656  * file when fdrop is used.
3657  */
3658 int __noinline
_fdrop(struct file * fp,struct thread * td)3659 _fdrop(struct file *fp, struct thread *td)
3660 {
3661 	int error;
3662 #ifdef INVARIANTS
3663 	int count;
3664 
3665 	count = refcount_load(&fp->f_count);
3666 	if (count != 0)
3667 		panic("fdrop: fp %p count %d", fp, count);
3668 #endif
3669 	error = fo_close(fp, td);
3670 	atomic_subtract_int(&openfiles, 1);
3671 	crfree(fp->f_cred);
3672 	free(fp->f_advice, M_FADVISE);
3673 	uma_zfree(file_zone, fp);
3674 
3675 	return (error);
3676 }
3677 
3678 /*
3679  * Apply an advisory lock on a file descriptor.
3680  *
3681  * Just attempt to get a record lock of the requested type on the entire file
3682  * (l_whence = SEEK_SET, l_start = 0, l_len = 0).
3683  */
3684 #ifndef _SYS_SYSPROTO_H_
3685 struct flock_args {
3686 	int	fd;
3687 	int	how;
3688 };
3689 #endif
3690 /* ARGSUSED */
3691 int
sys_flock(struct thread * td,struct flock_args * uap)3692 sys_flock(struct thread *td, struct flock_args *uap)
3693 {
3694 	struct file *fp;
3695 	struct vnode *vp;
3696 	struct flock lf;
3697 	int error;
3698 
3699 	error = fget(td, uap->fd, &cap_flock_rights, &fp);
3700 	if (error != 0)
3701 		return (error);
3702 	error = EOPNOTSUPP;
3703 	if (fp->f_type != DTYPE_VNODE && fp->f_type != DTYPE_FIFO) {
3704 		goto done;
3705 	}
3706 	if (fp->f_ops == &path_fileops) {
3707 		goto done;
3708 	}
3709 
3710 	error = 0;
3711 	vp = fp->f_vnode;
3712 	lf.l_whence = SEEK_SET;
3713 	lf.l_start = 0;
3714 	lf.l_len = 0;
3715 	if (uap->how & LOCK_UN) {
3716 		lf.l_type = F_UNLCK;
3717 		atomic_clear_int(&fp->f_flag, FHASLOCK);
3718 		error = VOP_ADVLOCK(vp, (caddr_t)fp, F_UNLCK, &lf, F_FLOCK);
3719 		goto done;
3720 	}
3721 	if (uap->how & LOCK_EX)
3722 		lf.l_type = F_WRLCK;
3723 	else if (uap->how & LOCK_SH)
3724 		lf.l_type = F_RDLCK;
3725 	else {
3726 		error = EBADF;
3727 		goto done;
3728 	}
3729 	atomic_set_int(&fp->f_flag, FHASLOCK);
3730 	error = VOP_ADVLOCK(vp, (caddr_t)fp, F_SETLK, &lf,
3731 	    (uap->how & LOCK_NB) ? F_FLOCK : F_FLOCK | F_WAIT);
3732 done:
3733 	fdrop(fp, td);
3734 	return (error);
3735 }
3736 /*
3737  * Duplicate the specified descriptor to a free descriptor.
3738  */
3739 int
dupfdopen(struct thread * td,struct filedesc * fdp,int dfd,int mode,int openerror,int * indxp)3740 dupfdopen(struct thread *td, struct filedesc *fdp, int dfd, int mode,
3741     int openerror, int *indxp)
3742 {
3743 	struct filedescent *newfde, *oldfde;
3744 	struct file *fp;
3745 	u_long *ioctls;
3746 	int error, indx;
3747 
3748 	KASSERT(openerror == ENODEV || openerror == ENXIO,
3749 	    ("unexpected error %d in %s", openerror, __func__));
3750 
3751 	/*
3752 	 * If the to-be-dup'd fd number is greater than the allowed number
3753 	 * of file descriptors, or the fd to be dup'd has already been
3754 	 * closed, then reject.
3755 	 */
3756 	FILEDESC_XLOCK(fdp);
3757 	if ((fp = fget_noref(fdp, dfd)) == NULL) {
3758 		FILEDESC_XUNLOCK(fdp);
3759 		return (EBADF);
3760 	}
3761 
3762 	error = fdalloc(td, 0, &indx);
3763 	if (error != 0) {
3764 		FILEDESC_XUNLOCK(fdp);
3765 		return (error);
3766 	}
3767 
3768 	/*
3769 	 * There are two cases of interest here.
3770 	 *
3771 	 * For ENODEV simply dup (dfd) to file descriptor (indx) and return.
3772 	 *
3773 	 * For ENXIO steal away the file structure from (dfd) and store it in
3774 	 * (indx).  (dfd) is effectively closed by this operation.
3775 	 */
3776 	switch (openerror) {
3777 	case ENODEV:
3778 		/*
3779 		 * Check that the mode the file is being opened for is a
3780 		 * subset of the mode of the existing descriptor.
3781 		 */
3782 		if (((mode & (FREAD|FWRITE)) | fp->f_flag) != fp->f_flag) {
3783 			fdunused(fdp, indx);
3784 			FILEDESC_XUNLOCK(fdp);
3785 			return (EACCES);
3786 		}
3787 		if (!fhold(fp)) {
3788 			fdunused(fdp, indx);
3789 			FILEDESC_XUNLOCK(fdp);
3790 			return (EBADF);
3791 		}
3792 		newfde = &fdp->fd_ofiles[indx];
3793 		oldfde = &fdp->fd_ofiles[dfd];
3794 		ioctls = filecaps_copy_prep(&oldfde->fde_caps);
3795 #ifdef CAPABILITIES
3796 		seqc_write_begin(&newfde->fde_seqc);
3797 #endif
3798 		fde_copy(oldfde, newfde);
3799 		filecaps_copy_finish(&oldfde->fde_caps, &newfde->fde_caps,
3800 		    ioctls);
3801 #ifdef CAPABILITIES
3802 		seqc_write_end(&newfde->fde_seqc);
3803 #endif
3804 		break;
3805 	case ENXIO:
3806 		/*
3807 		 * Steal away the file pointer from dfd and stuff it into indx.
3808 		 */
3809 		newfde = &fdp->fd_ofiles[indx];
3810 		oldfde = &fdp->fd_ofiles[dfd];
3811 #ifdef CAPABILITIES
3812 		seqc_write_begin(&oldfde->fde_seqc);
3813 		seqc_write_begin(&newfde->fde_seqc);
3814 #endif
3815 		fde_copy(oldfde, newfde);
3816 		oldfde->fde_file = NULL;
3817 		fdunused(fdp, dfd);
3818 #ifdef CAPABILITIES
3819 		seqc_write_end(&newfde->fde_seqc);
3820 		seqc_write_end(&oldfde->fde_seqc);
3821 #endif
3822 		break;
3823 	}
3824 	FILEDESC_XUNLOCK(fdp);
3825 	*indxp = indx;
3826 	return (0);
3827 }
3828 
3829 /*
3830  * This sysctl determines if we will allow a process to chroot(2) if it
3831  * has a directory open:
3832  *	0: disallowed for all processes.
3833  *	1: allowed for processes that were not already chroot(2)'ed.
3834  *	2: allowed for all processes.
3835  */
3836 
3837 static int chroot_allow_open_directories = 1;
3838 
3839 SYSCTL_INT(_kern, OID_AUTO, chroot_allow_open_directories, CTLFLAG_RW,
3840     &chroot_allow_open_directories, 0,
3841     "Allow a process to chroot(2) if it has a directory open");
3842 
3843 /*
3844  * Helper function for raised chroot(2) security function:  Refuse if
3845  * any filedescriptors are open directories.
3846  */
3847 static int
chroot_refuse_vdir_fds(struct filedesc * fdp)3848 chroot_refuse_vdir_fds(struct filedesc *fdp)
3849 {
3850 	struct vnode *vp;
3851 	struct file *fp;
3852 	int i;
3853 
3854 	FILEDESC_LOCK_ASSERT(fdp);
3855 
3856 	FILEDESC_FOREACH_FP(fdp, i, fp) {
3857 		if (fp->f_type == DTYPE_VNODE) {
3858 			vp = fp->f_vnode;
3859 			if (vp->v_type == VDIR)
3860 				return (EPERM);
3861 		}
3862 	}
3863 	return (0);
3864 }
3865 
3866 static void
pwd_fill(struct pwd * oldpwd,struct pwd * newpwd)3867 pwd_fill(struct pwd *oldpwd, struct pwd *newpwd)
3868 {
3869 
3870 	if (newpwd->pwd_cdir == NULL && oldpwd->pwd_cdir != NULL) {
3871 		vrefact(oldpwd->pwd_cdir);
3872 		newpwd->pwd_cdir = oldpwd->pwd_cdir;
3873 	}
3874 
3875 	if (newpwd->pwd_rdir == NULL && oldpwd->pwd_rdir != NULL) {
3876 		vrefact(oldpwd->pwd_rdir);
3877 		newpwd->pwd_rdir = oldpwd->pwd_rdir;
3878 	}
3879 
3880 	if (newpwd->pwd_jdir == NULL && oldpwd->pwd_jdir != NULL) {
3881 		vrefact(oldpwd->pwd_jdir);
3882 		newpwd->pwd_jdir = oldpwd->pwd_jdir;
3883 	}
3884 
3885 	if (newpwd->pwd_adir == NULL && oldpwd->pwd_adir != NULL) {
3886 		vrefact(oldpwd->pwd_adir);
3887 		newpwd->pwd_adir = oldpwd->pwd_adir;
3888 	}
3889 }
3890 
3891 struct pwd *
pwd_hold_pwddesc(struct pwddesc * pdp)3892 pwd_hold_pwddesc(struct pwddesc *pdp)
3893 {
3894 	struct pwd *pwd;
3895 
3896 	PWDDESC_ASSERT_XLOCKED(pdp);
3897 	pwd = PWDDESC_XLOCKED_LOAD_PWD(pdp);
3898 	if (pwd != NULL)
3899 		refcount_acquire(&pwd->pwd_refcount);
3900 	return (pwd);
3901 }
3902 
3903 bool
pwd_hold_smr(struct pwd * pwd)3904 pwd_hold_smr(struct pwd *pwd)
3905 {
3906 
3907 	MPASS(pwd != NULL);
3908 	if (__predict_true(refcount_acquire_if_not_zero(&pwd->pwd_refcount))) {
3909 		return (true);
3910 	}
3911 	return (false);
3912 }
3913 
3914 struct pwd *
pwd_hold(struct thread * td)3915 pwd_hold(struct thread *td)
3916 {
3917 	struct pwddesc *pdp;
3918 	struct pwd *pwd;
3919 
3920 	pdp = td->td_proc->p_pd;
3921 
3922 	vfs_smr_enter();
3923 	pwd = vfs_smr_entered_load(&pdp->pd_pwd);
3924 	if (pwd_hold_smr(pwd)) {
3925 		vfs_smr_exit();
3926 		return (pwd);
3927 	}
3928 	vfs_smr_exit();
3929 	PWDDESC_XLOCK(pdp);
3930 	pwd = pwd_hold_pwddesc(pdp);
3931 	MPASS(pwd != NULL);
3932 	PWDDESC_XUNLOCK(pdp);
3933 	return (pwd);
3934 }
3935 
3936 struct pwd *
pwd_hold_proc(struct proc * p)3937 pwd_hold_proc(struct proc *p)
3938 {
3939 	struct pwddesc *pdp;
3940 	struct pwd *pwd;
3941 
3942 	PROC_ASSERT_HELD(p);
3943 	PROC_LOCK(p);
3944 	pdp = pdhold(p);
3945 	MPASS(pdp != NULL);
3946 	PROC_UNLOCK(p);
3947 
3948 	PWDDESC_XLOCK(pdp);
3949 	pwd = pwd_hold_pwddesc(pdp);
3950 	MPASS(pwd != NULL);
3951 	PWDDESC_XUNLOCK(pdp);
3952 	pddrop(pdp);
3953 	return (pwd);
3954 }
3955 
3956 static struct pwd *
pwd_alloc(void)3957 pwd_alloc(void)
3958 {
3959 	struct pwd *pwd;
3960 
3961 	pwd = uma_zalloc_smr(pwd_zone, M_WAITOK);
3962 	bzero(pwd, sizeof(*pwd));
3963 	refcount_init(&pwd->pwd_refcount, 1);
3964 	return (pwd);
3965 }
3966 
3967 void
pwd_drop(struct pwd * pwd)3968 pwd_drop(struct pwd *pwd)
3969 {
3970 
3971 	if (!refcount_release(&pwd->pwd_refcount))
3972 		return;
3973 
3974 	if (pwd->pwd_cdir != NULL)
3975 		vrele(pwd->pwd_cdir);
3976 	if (pwd->pwd_rdir != NULL)
3977 		vrele(pwd->pwd_rdir);
3978 	if (pwd->pwd_jdir != NULL)
3979 		vrele(pwd->pwd_jdir);
3980 	if (pwd->pwd_adir != NULL)
3981 		vrele(pwd->pwd_adir);
3982 	uma_zfree_smr(pwd_zone, pwd);
3983 }
3984 
3985 /*
3986 * The caller is responsible for invoking priv_check() and
3987 * mac_vnode_check_chroot() to authorize this operation.
3988 */
3989 int
pwd_chroot(struct thread * td,struct vnode * vp)3990 pwd_chroot(struct thread *td, struct vnode *vp)
3991 {
3992 	struct pwddesc *pdp;
3993 	struct filedesc *fdp;
3994 	struct pwd *newpwd, *oldpwd;
3995 	int error;
3996 
3997 	fdp = td->td_proc->p_fd;
3998 	pdp = td->td_proc->p_pd;
3999 	newpwd = pwd_alloc();
4000 	FILEDESC_SLOCK(fdp);
4001 	PWDDESC_XLOCK(pdp);
4002 	oldpwd = PWDDESC_XLOCKED_LOAD_PWD(pdp);
4003 	if (chroot_allow_open_directories == 0 ||
4004 	    (chroot_allow_open_directories == 1 &&
4005 	    oldpwd->pwd_rdir != rootvnode)) {
4006 		error = chroot_refuse_vdir_fds(fdp);
4007 		FILEDESC_SUNLOCK(fdp);
4008 		if (error != 0) {
4009 			PWDDESC_XUNLOCK(pdp);
4010 			pwd_drop(newpwd);
4011 			return (error);
4012 		}
4013 	} else {
4014 		FILEDESC_SUNLOCK(fdp);
4015 	}
4016 
4017 	vrefact(vp);
4018 	newpwd->pwd_rdir = vp;
4019 	vrefact(vp);
4020 	newpwd->pwd_adir = vp;
4021 	if (oldpwd->pwd_jdir == NULL) {
4022 		vrefact(vp);
4023 		newpwd->pwd_jdir = vp;
4024 	}
4025 	pwd_fill(oldpwd, newpwd);
4026 	pwd_set(pdp, newpwd);
4027 	PWDDESC_XUNLOCK(pdp);
4028 	pwd_drop(oldpwd);
4029 	return (0);
4030 }
4031 
4032 void
pwd_chdir(struct thread * td,struct vnode * vp)4033 pwd_chdir(struct thread *td, struct vnode *vp)
4034 {
4035 	struct pwddesc *pdp;
4036 	struct pwd *newpwd, *oldpwd;
4037 
4038 	VNPASS(vp->v_usecount > 0, vp);
4039 
4040 	newpwd = pwd_alloc();
4041 	pdp = td->td_proc->p_pd;
4042 	PWDDESC_XLOCK(pdp);
4043 	oldpwd = PWDDESC_XLOCKED_LOAD_PWD(pdp);
4044 	newpwd->pwd_cdir = vp;
4045 	pwd_fill(oldpwd, newpwd);
4046 	pwd_set(pdp, newpwd);
4047 	PWDDESC_XUNLOCK(pdp);
4048 	pwd_drop(oldpwd);
4049 }
4050 
4051 /*
4052  * Process is transitioning to/from a non-native ABI.
4053  */
4054 void
pwd_altroot(struct thread * td,struct vnode * altroot_vp)4055 pwd_altroot(struct thread *td, struct vnode *altroot_vp)
4056 {
4057 	struct pwddesc *pdp;
4058 	struct pwd *newpwd, *oldpwd;
4059 
4060 	newpwd = pwd_alloc();
4061 	pdp = td->td_proc->p_pd;
4062 	PWDDESC_XLOCK(pdp);
4063 	oldpwd = PWDDESC_XLOCKED_LOAD_PWD(pdp);
4064 	if (altroot_vp != NULL) {
4065 		/*
4066 		 * Native process to a non-native ABI.
4067 		 */
4068 
4069 		vrefact(altroot_vp);
4070 		newpwd->pwd_adir = altroot_vp;
4071 	} else {
4072 		/*
4073 		 * Non-native process to the native ABI.
4074 		 */
4075 
4076 		vrefact(oldpwd->pwd_rdir);
4077 		newpwd->pwd_adir = oldpwd->pwd_rdir;
4078 	}
4079 	pwd_fill(oldpwd, newpwd);
4080 	pwd_set(pdp, newpwd);
4081 	PWDDESC_XUNLOCK(pdp);
4082 	pwd_drop(oldpwd);
4083 }
4084 
4085 /*
4086  * jail_attach(2) changes both root and working directories.
4087  */
4088 int
pwd_chroot_chdir(struct thread * td,struct vnode * vp)4089 pwd_chroot_chdir(struct thread *td, struct vnode *vp)
4090 {
4091 	struct pwddesc *pdp;
4092 	struct filedesc *fdp;
4093 	struct pwd *newpwd, *oldpwd;
4094 	int error;
4095 
4096 	fdp = td->td_proc->p_fd;
4097 	pdp = td->td_proc->p_pd;
4098 	newpwd = pwd_alloc();
4099 	FILEDESC_SLOCK(fdp);
4100 	PWDDESC_XLOCK(pdp);
4101 	oldpwd = PWDDESC_XLOCKED_LOAD_PWD(pdp);
4102 	error = chroot_refuse_vdir_fds(fdp);
4103 	FILEDESC_SUNLOCK(fdp);
4104 	if (error != 0) {
4105 		PWDDESC_XUNLOCK(pdp);
4106 		pwd_drop(newpwd);
4107 		return (error);
4108 	}
4109 
4110 	vrefact(vp);
4111 	newpwd->pwd_rdir = vp;
4112 	vrefact(vp);
4113 	newpwd->pwd_cdir = vp;
4114 	if (oldpwd->pwd_jdir == NULL) {
4115 		vrefact(vp);
4116 		newpwd->pwd_jdir = vp;
4117 	}
4118 	vrefact(vp);
4119 	newpwd->pwd_adir = vp;
4120 	pwd_fill(oldpwd, newpwd);
4121 	pwd_set(pdp, newpwd);
4122 	PWDDESC_XUNLOCK(pdp);
4123 	pwd_drop(oldpwd);
4124 	return (0);
4125 }
4126 
4127 void
pwd_ensure_dirs(void)4128 pwd_ensure_dirs(void)
4129 {
4130 	struct pwddesc *pdp;
4131 	struct pwd *oldpwd, *newpwd;
4132 
4133 	pdp = curproc->p_pd;
4134 	PWDDESC_XLOCK(pdp);
4135 	oldpwd = PWDDESC_XLOCKED_LOAD_PWD(pdp);
4136 	if (oldpwd->pwd_cdir != NULL && oldpwd->pwd_rdir != NULL &&
4137 	    oldpwd->pwd_adir != NULL) {
4138 		PWDDESC_XUNLOCK(pdp);
4139 		return;
4140 	}
4141 	PWDDESC_XUNLOCK(pdp);
4142 
4143 	newpwd = pwd_alloc();
4144 	PWDDESC_XLOCK(pdp);
4145 	oldpwd = PWDDESC_XLOCKED_LOAD_PWD(pdp);
4146 	pwd_fill(oldpwd, newpwd);
4147 	if (newpwd->pwd_cdir == NULL) {
4148 		vrefact(rootvnode);
4149 		newpwd->pwd_cdir = rootvnode;
4150 	}
4151 	if (newpwd->pwd_rdir == NULL) {
4152 		vrefact(rootvnode);
4153 		newpwd->pwd_rdir = rootvnode;
4154 	}
4155 	if (newpwd->pwd_adir == NULL) {
4156 		vrefact(rootvnode);
4157 		newpwd->pwd_adir = rootvnode;
4158 	}
4159 	pwd_set(pdp, newpwd);
4160 	PWDDESC_XUNLOCK(pdp);
4161 	pwd_drop(oldpwd);
4162 }
4163 
4164 void
pwd_set_rootvnode(void)4165 pwd_set_rootvnode(void)
4166 {
4167 	struct pwddesc *pdp;
4168 	struct pwd *oldpwd, *newpwd;
4169 
4170 	pdp = curproc->p_pd;
4171 
4172 	newpwd = pwd_alloc();
4173 	PWDDESC_XLOCK(pdp);
4174 	oldpwd = PWDDESC_XLOCKED_LOAD_PWD(pdp);
4175 	vrefact(rootvnode);
4176 	newpwd->pwd_cdir = rootvnode;
4177 	vrefact(rootvnode);
4178 	newpwd->pwd_rdir = rootvnode;
4179 	vrefact(rootvnode);
4180 	newpwd->pwd_adir = rootvnode;
4181 	pwd_fill(oldpwd, newpwd);
4182 	pwd_set(pdp, newpwd);
4183 	PWDDESC_XUNLOCK(pdp);
4184 	pwd_drop(oldpwd);
4185 }
4186 
4187 /*
4188  * Scan all active processes and prisons to see if any of them have a current
4189  * or root directory of `olddp'. If so, replace them with the new mount point.
4190  */
4191 void
mountcheckdirs(struct vnode * olddp,struct vnode * newdp)4192 mountcheckdirs(struct vnode *olddp, struct vnode *newdp)
4193 {
4194 	struct pwddesc *pdp;
4195 	struct pwd *newpwd, *oldpwd;
4196 	struct prison *pr;
4197 	struct proc *p;
4198 	int nrele;
4199 
4200 	if (vrefcnt(olddp) == 1)
4201 		return;
4202 	nrele = 0;
4203 	newpwd = pwd_alloc();
4204 	sx_slock(&allproc_lock);
4205 	FOREACH_PROC_IN_SYSTEM(p) {
4206 		PROC_LOCK(p);
4207 		pdp = pdhold(p);
4208 		PROC_UNLOCK(p);
4209 		if (pdp == NULL)
4210 			continue;
4211 		PWDDESC_XLOCK(pdp);
4212 		oldpwd = PWDDESC_XLOCKED_LOAD_PWD(pdp);
4213 		if (oldpwd == NULL ||
4214 		    (oldpwd->pwd_cdir != olddp &&
4215 		    oldpwd->pwd_rdir != olddp &&
4216 		    oldpwd->pwd_jdir != olddp &&
4217 		    oldpwd->pwd_adir != olddp)) {
4218 			PWDDESC_XUNLOCK(pdp);
4219 			pddrop(pdp);
4220 			continue;
4221 		}
4222 		if (oldpwd->pwd_cdir == olddp) {
4223 			vrefact(newdp);
4224 			newpwd->pwd_cdir = newdp;
4225 		}
4226 		if (oldpwd->pwd_rdir == olddp) {
4227 			vrefact(newdp);
4228 			newpwd->pwd_rdir = newdp;
4229 		}
4230 		if (oldpwd->pwd_jdir == olddp) {
4231 			vrefact(newdp);
4232 			newpwd->pwd_jdir = newdp;
4233 		}
4234 		if (oldpwd->pwd_adir == olddp) {
4235 			vrefact(newdp);
4236 			newpwd->pwd_adir = newdp;
4237 		}
4238 		pwd_fill(oldpwd, newpwd);
4239 		pwd_set(pdp, newpwd);
4240 		PWDDESC_XUNLOCK(pdp);
4241 		pwd_drop(oldpwd);
4242 		pddrop(pdp);
4243 		newpwd = pwd_alloc();
4244 	}
4245 	sx_sunlock(&allproc_lock);
4246 	pwd_drop(newpwd);
4247 	if (rootvnode == olddp) {
4248 		vrefact(newdp);
4249 		rootvnode = newdp;
4250 		nrele++;
4251 	}
4252 	mtx_lock(&prison0.pr_mtx);
4253 	if (prison0.pr_root == olddp) {
4254 		vrefact(newdp);
4255 		prison0.pr_root = newdp;
4256 		nrele++;
4257 	}
4258 	mtx_unlock(&prison0.pr_mtx);
4259 	sx_slock(&allprison_lock);
4260 	TAILQ_FOREACH(pr, &allprison, pr_list) {
4261 		mtx_lock(&pr->pr_mtx);
4262 		if (pr->pr_root == olddp) {
4263 			vrefact(newdp);
4264 			pr->pr_root = newdp;
4265 			nrele++;
4266 		}
4267 		mtx_unlock(&pr->pr_mtx);
4268 	}
4269 	sx_sunlock(&allprison_lock);
4270 	while (nrele--)
4271 		vrele(olddp);
4272 }
4273 
4274 int
descrip_check_write_mp(struct filedesc * fdp,struct mount * mp)4275 descrip_check_write_mp(struct filedesc *fdp, struct mount *mp)
4276 {
4277 	struct file *fp;
4278 	struct vnode *vp;
4279 	int error, i;
4280 
4281 	error = 0;
4282 	FILEDESC_SLOCK(fdp);
4283 	FILEDESC_FOREACH_FP(fdp, i, fp) {
4284 		if (fp->f_type != DTYPE_VNODE ||
4285 		    (atomic_load_int(&fp->f_flag) & FWRITE) == 0)
4286 			continue;
4287 		vp = fp->f_vnode;
4288 		if (vp->v_mount == mp) {
4289 			error = EDEADLK;
4290 			break;
4291 		}
4292 	}
4293 	FILEDESC_SUNLOCK(fdp);
4294 	return (error);
4295 }
4296 
4297 struct filedesc_to_leader *
filedesc_to_leader_alloc(struct filedesc_to_leader * old,struct filedesc * fdp,struct proc * leader)4298 filedesc_to_leader_alloc(struct filedesc_to_leader *old, struct filedesc *fdp,
4299     struct proc *leader)
4300 {
4301 	struct filedesc_to_leader *fdtol;
4302 
4303 	fdtol = malloc(sizeof(struct filedesc_to_leader),
4304 	    M_FILEDESC_TO_LEADER, M_WAITOK);
4305 	fdtol->fdl_refcount = 1;
4306 	fdtol->fdl_holdcount = 0;
4307 	fdtol->fdl_wakeup = 0;
4308 	fdtol->fdl_leader = leader;
4309 	if (old != NULL) {
4310 		FILEDESC_XLOCK(fdp);
4311 		fdtol->fdl_next = old->fdl_next;
4312 		fdtol->fdl_prev = old;
4313 		old->fdl_next = fdtol;
4314 		fdtol->fdl_next->fdl_prev = fdtol;
4315 		FILEDESC_XUNLOCK(fdp);
4316 	} else {
4317 		fdtol->fdl_next = fdtol;
4318 		fdtol->fdl_prev = fdtol;
4319 	}
4320 	return (fdtol);
4321 }
4322 
4323 struct filedesc_to_leader *
filedesc_to_leader_share(struct filedesc_to_leader * fdtol,struct filedesc * fdp)4324 filedesc_to_leader_share(struct filedesc_to_leader *fdtol, struct filedesc *fdp)
4325 {
4326 	FILEDESC_XLOCK(fdp);
4327 	fdtol->fdl_refcount++;
4328 	FILEDESC_XUNLOCK(fdp);
4329 	return (fdtol);
4330 }
4331 
4332 static int
filedesc_nfiles(struct filedesc * fdp)4333 filedesc_nfiles(struct filedesc *fdp)
4334 {
4335 	NDSLOTTYPE *map;
4336 	int count, off, minoff;
4337 
4338 	if (fdp == NULL)
4339 		return (0);
4340 	count = 0;
4341 	FILEDESC_SLOCK(fdp);
4342 	map = fdp->fd_map;
4343 	off = NDSLOT(fdp->fd_nfiles - 1);
4344 	for (minoff = NDSLOT(0); off >= minoff; --off)
4345 		count += bitcountl(map[off]);
4346 	FILEDESC_SUNLOCK(fdp);
4347 	return (count);
4348 }
4349 
4350 int
proc_nfiles(struct proc * p)4351 proc_nfiles(struct proc *p)
4352 {
4353 	struct filedesc *fdp;
4354 	int res;
4355 
4356 	PROC_LOCK(p);
4357 	fdp = fdhold(p);
4358 	PROC_UNLOCK(p);
4359 	res = filedesc_nfiles(fdp);
4360 	fddrop(fdp);
4361 	return (res);
4362 }
4363 
4364 static int
sysctl_kern_proc_nfds(SYSCTL_HANDLER_ARGS)4365 sysctl_kern_proc_nfds(SYSCTL_HANDLER_ARGS)
4366 {
4367 	u_int namelen;
4368 	int count;
4369 
4370 	namelen = arg2;
4371 	if (namelen != 1)
4372 		return (EINVAL);
4373 
4374 	if (*(int *)arg1 != 0)
4375 		return (EINVAL);
4376 
4377 	count = filedesc_nfiles(curproc->p_fd);
4378 	return (SYSCTL_OUT(req, &count, sizeof(count)));
4379 }
4380 
4381 static SYSCTL_NODE(_kern_proc, KERN_PROC_NFDS, nfds,
4382     CTLFLAG_RD|CTLFLAG_CAPRD|CTLFLAG_MPSAFE, sysctl_kern_proc_nfds,
4383     "Number of open file descriptors");
4384 
4385 /*
4386  * Get file structures globally.
4387  */
4388 static int
sysctl_kern_file(SYSCTL_HANDLER_ARGS)4389 sysctl_kern_file(SYSCTL_HANDLER_ARGS)
4390 {
4391 	struct xfile xf;
4392 	struct filedesc *fdp;
4393 	struct file *fp;
4394 	struct proc *p;
4395 	int error, n;
4396 
4397 	error = sysctl_wire_old_buffer(req, 0);
4398 	if (error != 0)
4399 		return (error);
4400 	if (req->oldptr == NULL) {
4401 		n = 0;
4402 		sx_slock(&allproc_lock);
4403 		FOREACH_PROC_IN_SYSTEM(p) {
4404 			PROC_LOCK(p);
4405 			if (p->p_state == PRS_NEW) {
4406 				PROC_UNLOCK(p);
4407 				continue;
4408 			}
4409 			fdp = fdhold(p);
4410 			PROC_UNLOCK(p);
4411 			if (fdp == NULL)
4412 				continue;
4413 			/* overestimates sparse tables. */
4414 			n += fdp->fd_nfiles;
4415 			fddrop(fdp);
4416 		}
4417 		sx_sunlock(&allproc_lock);
4418 		return (SYSCTL_OUT(req, 0, n * sizeof(xf)));
4419 	}
4420 	error = 0;
4421 	bzero(&xf, sizeof(xf));
4422 	xf.xf_size = sizeof(xf);
4423 	sx_slock(&allproc_lock);
4424 	FOREACH_PROC_IN_SYSTEM(p) {
4425 		PROC_LOCK(p);
4426 		if (p->p_state == PRS_NEW) {
4427 			PROC_UNLOCK(p);
4428 			continue;
4429 		}
4430 		if (p_cansee(req->td, p) != 0) {
4431 			PROC_UNLOCK(p);
4432 			continue;
4433 		}
4434 		xf.xf_pid = p->p_pid;
4435 		xf.xf_uid = p->p_ucred->cr_uid;
4436 		fdp = fdhold(p);
4437 		PROC_UNLOCK(p);
4438 		if (fdp == NULL)
4439 			continue;
4440 		FILEDESC_SLOCK(fdp);
4441 		if (refcount_load(&fdp->fd_refcnt) == 0)
4442 			goto nextproc;
4443 		FILEDESC_FOREACH_FP(fdp, n, fp) {
4444 			xf.xf_fd = n;
4445 			xf.xf_file = (uintptr_t)fp;
4446 			xf.xf_data = (uintptr_t)fp->f_data;
4447 			xf.xf_vnode = (uintptr_t)fp->f_vnode;
4448 			xf.xf_type = (uintptr_t)fp->f_type;
4449 			xf.xf_count = refcount_load(&fp->f_count);
4450 			xf.xf_msgcount = 0;
4451 			xf.xf_offset = foffset_get(fp);
4452 			xf.xf_flag = fp->f_flag;
4453 			error = SYSCTL_OUT(req, &xf, sizeof(xf));
4454 
4455 			/*
4456 			 * There is no need to re-check the fdtable refcount
4457 			 * here since the filedesc lock is not dropped in the
4458 			 * loop body.
4459 			 */
4460 			if (error != 0)
4461 				break;
4462 		}
4463 nextproc:
4464 		FILEDESC_SUNLOCK(fdp);
4465 		fddrop(fdp);
4466 		if (error)
4467 			break;
4468 	}
4469 	sx_sunlock(&allproc_lock);
4470 	return (error);
4471 }
4472 
4473 SYSCTL_PROC(_kern, KERN_FILE, file, CTLTYPE_OPAQUE|CTLFLAG_RD|CTLFLAG_MPSAFE,
4474     0, 0, sysctl_kern_file, "S,xfile", "Entire file table");
4475 
4476 #ifdef KINFO_FILE_SIZE
4477 CTASSERT(sizeof(struct kinfo_file) == KINFO_FILE_SIZE);
4478 #endif
4479 
4480 static int
xlate_fflags(int fflags)4481 xlate_fflags(int fflags)
4482 {
4483 	static const struct {
4484 		int	fflag;
4485 		int	kf_fflag;
4486 	} fflags_table[] = {
4487 		{ FAPPEND, KF_FLAG_APPEND },
4488 		{ FASYNC, KF_FLAG_ASYNC },
4489 		{ FFSYNC, KF_FLAG_FSYNC },
4490 		{ FHASLOCK, KF_FLAG_HASLOCK },
4491 		{ FNONBLOCK, KF_FLAG_NONBLOCK },
4492 		{ FREAD, KF_FLAG_READ },
4493 		{ FWRITE, KF_FLAG_WRITE },
4494 		{ O_CREAT, KF_FLAG_CREAT },
4495 		{ O_DIRECT, KF_FLAG_DIRECT },
4496 		{ O_EXCL, KF_FLAG_EXCL },
4497 		{ O_EXEC, KF_FLAG_EXEC },
4498 		{ O_EXLOCK, KF_FLAG_EXLOCK },
4499 		{ O_NOFOLLOW, KF_FLAG_NOFOLLOW },
4500 		{ O_SHLOCK, KF_FLAG_SHLOCK },
4501 		{ O_TRUNC, KF_FLAG_TRUNC }
4502 	};
4503 	unsigned int i;
4504 	int kflags;
4505 
4506 	kflags = 0;
4507 	for (i = 0; i < nitems(fflags_table); i++)
4508 		if (fflags & fflags_table[i].fflag)
4509 			kflags |=  fflags_table[i].kf_fflag;
4510 	return (kflags);
4511 }
4512 
4513 /* Trim unused data from kf_path by truncating the structure size. */
4514 void
pack_kinfo(struct kinfo_file * kif)4515 pack_kinfo(struct kinfo_file *kif)
4516 {
4517 
4518 	kif->kf_structsize = offsetof(struct kinfo_file, kf_path) +
4519 	    strlen(kif->kf_path) + 1;
4520 	kif->kf_structsize = roundup(kif->kf_structsize, sizeof(uint64_t));
4521 }
4522 
4523 static void
export_file_to_kinfo(struct file * fp,int fd,cap_rights_t * rightsp,struct kinfo_file * kif,struct filedesc * fdp,int flags)4524 export_file_to_kinfo(struct file *fp, int fd, cap_rights_t *rightsp,
4525     struct kinfo_file *kif, struct filedesc *fdp, int flags)
4526 {
4527 	int error;
4528 
4529 	bzero(kif, sizeof(*kif));
4530 
4531 	/* Set a default type to allow for empty fill_kinfo() methods. */
4532 	kif->kf_type = KF_TYPE_UNKNOWN;
4533 	kif->kf_flags = xlate_fflags(fp->f_flag);
4534 	if (rightsp != NULL)
4535 		kif->kf_cap_rights = *rightsp;
4536 	else
4537 		cap_rights_init_zero(&kif->kf_cap_rights);
4538 	kif->kf_fd = fd;
4539 	kif->kf_ref_count = refcount_load(&fp->f_count);
4540 	kif->kf_offset = foffset_get(fp);
4541 
4542 	/*
4543 	 * This may drop the filedesc lock, so the 'fp' cannot be
4544 	 * accessed after this call.
4545 	 */
4546 	error = fo_fill_kinfo(fp, kif, fdp);
4547 	if (error == 0)
4548 		kif->kf_status |= KF_ATTR_VALID;
4549 	if ((flags & KERN_FILEDESC_PACK_KINFO) != 0)
4550 		pack_kinfo(kif);
4551 	else
4552 		kif->kf_structsize = roundup2(sizeof(*kif), sizeof(uint64_t));
4553 }
4554 
4555 static void
export_vnode_to_kinfo(struct vnode * vp,int fd,int fflags,struct kinfo_file * kif,int flags)4556 export_vnode_to_kinfo(struct vnode *vp, int fd, int fflags,
4557     struct kinfo_file *kif, int flags)
4558 {
4559 	int error;
4560 
4561 	bzero(kif, sizeof(*kif));
4562 
4563 	kif->kf_type = KF_TYPE_VNODE;
4564 	error = vn_fill_kinfo_vnode(vp, kif);
4565 	if (error == 0)
4566 		kif->kf_status |= KF_ATTR_VALID;
4567 	kif->kf_flags = xlate_fflags(fflags);
4568 	cap_rights_init_zero(&kif->kf_cap_rights);
4569 	kif->kf_fd = fd;
4570 	kif->kf_ref_count = -1;
4571 	kif->kf_offset = -1;
4572 	if ((flags & KERN_FILEDESC_PACK_KINFO) != 0)
4573 		pack_kinfo(kif);
4574 	else
4575 		kif->kf_structsize = roundup2(sizeof(*kif), sizeof(uint64_t));
4576 	vrele(vp);
4577 }
4578 
4579 struct export_fd_buf {
4580 	struct filedesc		*fdp;
4581 	struct pwddesc	*pdp;
4582 	struct sbuf 		*sb;
4583 	ssize_t			remainder;
4584 	struct kinfo_file	kif;
4585 	int			flags;
4586 };
4587 
4588 static int
export_kinfo_to_sb(struct export_fd_buf * efbuf)4589 export_kinfo_to_sb(struct export_fd_buf *efbuf)
4590 {
4591 	struct kinfo_file *kif;
4592 
4593 	kif = &efbuf->kif;
4594 	if (efbuf->remainder != -1) {
4595 		if (efbuf->remainder < kif->kf_structsize)
4596 			return (ENOMEM);
4597 		efbuf->remainder -= kif->kf_structsize;
4598 	}
4599 	if (sbuf_bcat(efbuf->sb, kif, kif->kf_structsize) != 0)
4600 		return (sbuf_error(efbuf->sb));
4601 	return (0);
4602 }
4603 
4604 static int
export_file_to_sb(struct file * fp,int fd,cap_rights_t * rightsp,struct export_fd_buf * efbuf)4605 export_file_to_sb(struct file *fp, int fd, cap_rights_t *rightsp,
4606     struct export_fd_buf *efbuf)
4607 {
4608 	int error;
4609 
4610 	if (efbuf->remainder == 0)
4611 		return (ENOMEM);
4612 	export_file_to_kinfo(fp, fd, rightsp, &efbuf->kif, efbuf->fdp,
4613 	    efbuf->flags);
4614 	FILEDESC_SUNLOCK(efbuf->fdp);
4615 	error = export_kinfo_to_sb(efbuf);
4616 	FILEDESC_SLOCK(efbuf->fdp);
4617 	return (error);
4618 }
4619 
4620 static int
export_vnode_to_sb(struct vnode * vp,int fd,int fflags,struct export_fd_buf * efbuf)4621 export_vnode_to_sb(struct vnode *vp, int fd, int fflags,
4622     struct export_fd_buf *efbuf)
4623 {
4624 	int error;
4625 
4626 	if (efbuf->remainder == 0)
4627 		return (ENOMEM);
4628 	if (efbuf->pdp != NULL)
4629 		PWDDESC_XUNLOCK(efbuf->pdp);
4630 	export_vnode_to_kinfo(vp, fd, fflags, &efbuf->kif, efbuf->flags);
4631 	error = export_kinfo_to_sb(efbuf);
4632 	if (efbuf->pdp != NULL)
4633 		PWDDESC_XLOCK(efbuf->pdp);
4634 	return (error);
4635 }
4636 
4637 /*
4638  * Store a process file descriptor information to sbuf.
4639  *
4640  * Takes a locked proc as argument, and returns with the proc unlocked.
4641  */
4642 int
kern_proc_filedesc_out(struct proc * p,struct sbuf * sb,ssize_t maxlen,int flags)4643 kern_proc_filedesc_out(struct proc *p,  struct sbuf *sb, ssize_t maxlen,
4644     int flags)
4645 {
4646 	struct file *fp;
4647 	struct filedesc *fdp;
4648 	struct pwddesc *pdp;
4649 	struct export_fd_buf *efbuf;
4650 	struct vnode *cttyvp, *textvp, *tracevp;
4651 	struct pwd *pwd;
4652 	int error, i;
4653 	cap_rights_t rights;
4654 
4655 	PROC_LOCK_ASSERT(p, MA_OWNED);
4656 
4657 	/* ktrace vnode */
4658 	tracevp = ktr_get_tracevp(p, true);
4659 	/* text vnode */
4660 	textvp = p->p_textvp;
4661 	if (textvp != NULL)
4662 		vrefact(textvp);
4663 	/* Controlling tty. */
4664 	cttyvp = NULL;
4665 	if (p->p_pgrp != NULL && p->p_pgrp->pg_session != NULL) {
4666 		cttyvp = p->p_pgrp->pg_session->s_ttyvp;
4667 		if (cttyvp != NULL)
4668 			vrefact(cttyvp);
4669 	}
4670 	fdp = fdhold(p);
4671 	pdp = pdhold(p);
4672 	PROC_UNLOCK(p);
4673 
4674 	efbuf = malloc(sizeof(*efbuf), M_TEMP, M_WAITOK);
4675 	efbuf->fdp = NULL;
4676 	efbuf->pdp = NULL;
4677 	efbuf->sb = sb;
4678 	efbuf->remainder = maxlen;
4679 	efbuf->flags = flags;
4680 
4681 	error = 0;
4682 	if (tracevp != NULL)
4683 		error = export_vnode_to_sb(tracevp, KF_FD_TYPE_TRACE,
4684 		    FREAD | FWRITE, efbuf);
4685 	if (error == 0 && textvp != NULL)
4686 		error = export_vnode_to_sb(textvp, KF_FD_TYPE_TEXT, FREAD,
4687 		    efbuf);
4688 	if (error == 0 && cttyvp != NULL)
4689 		error = export_vnode_to_sb(cttyvp, KF_FD_TYPE_CTTY,
4690 		    FREAD | FWRITE, efbuf);
4691 	if (error != 0 || pdp == NULL || fdp == NULL)
4692 		goto fail;
4693 	efbuf->fdp = fdp;
4694 	efbuf->pdp = pdp;
4695 	PWDDESC_XLOCK(pdp);
4696 	pwd = pwd_hold_pwddesc(pdp);
4697 	if (pwd != NULL) {
4698 		/* working directory */
4699 		if (pwd->pwd_cdir != NULL) {
4700 			vrefact(pwd->pwd_cdir);
4701 			error = export_vnode_to_sb(pwd->pwd_cdir,
4702 			    KF_FD_TYPE_CWD, FREAD, efbuf);
4703 		}
4704 		/* root directory */
4705 		if (error == 0 && pwd->pwd_rdir != NULL) {
4706 			vrefact(pwd->pwd_rdir);
4707 			error = export_vnode_to_sb(pwd->pwd_rdir,
4708 			    KF_FD_TYPE_ROOT, FREAD, efbuf);
4709 		}
4710 		/* jail directory */
4711 		if (error == 0 && pwd->pwd_jdir != NULL) {
4712 			vrefact(pwd->pwd_jdir);
4713 			error = export_vnode_to_sb(pwd->pwd_jdir,
4714 			    KF_FD_TYPE_JAIL, FREAD, efbuf);
4715 		}
4716 	}
4717 	PWDDESC_XUNLOCK(pdp);
4718 	if (error != 0)
4719 		goto fail;
4720 	if (pwd != NULL)
4721 		pwd_drop(pwd);
4722 	FILEDESC_SLOCK(fdp);
4723 	if (refcount_load(&fdp->fd_refcnt) == 0)
4724 		goto skip;
4725 	FILEDESC_FOREACH_FP(fdp, i, fp) {
4726 #ifdef CAPABILITIES
4727 		rights = *cap_rights(fdp, i);
4728 #else /* !CAPABILITIES */
4729 		rights = cap_no_rights;
4730 #endif
4731 		/*
4732 		 * Create sysctl entry.  It is OK to drop the filedesc
4733 		 * lock inside of export_file_to_sb() as we will
4734 		 * re-validate and re-evaluate its properties when the
4735 		 * loop continues.
4736 		 */
4737 		error = export_file_to_sb(fp, i, &rights, efbuf);
4738 		if (error != 0 || refcount_load(&fdp->fd_refcnt) == 0)
4739 			break;
4740 	}
4741 skip:
4742 	FILEDESC_SUNLOCK(fdp);
4743 fail:
4744 	if (fdp != NULL)
4745 		fddrop(fdp);
4746 	if (pdp != NULL)
4747 		pddrop(pdp);
4748 	free(efbuf, M_TEMP);
4749 	return (error);
4750 }
4751 
4752 #define FILEDESC_SBUF_SIZE	(sizeof(struct kinfo_file) * 5)
4753 
4754 /*
4755  * Get per-process file descriptors for use by procstat(1), et al.
4756  */
4757 static int
sysctl_kern_proc_filedesc(SYSCTL_HANDLER_ARGS)4758 sysctl_kern_proc_filedesc(SYSCTL_HANDLER_ARGS)
4759 {
4760 	struct sbuf sb;
4761 	struct proc *p;
4762 	ssize_t maxlen;
4763 	u_int namelen;
4764 	int error, error2, *name;
4765 
4766 	namelen = arg2;
4767 	if (namelen != 1)
4768 		return (EINVAL);
4769 
4770 	name = (int *)arg1;
4771 
4772 	sbuf_new_for_sysctl(&sb, NULL, FILEDESC_SBUF_SIZE, req);
4773 	sbuf_clear_flags(&sb, SBUF_INCLUDENUL);
4774 	error = pget((pid_t)name[0], PGET_CANDEBUG | PGET_NOTWEXIT, &p);
4775 	if (error != 0) {
4776 		sbuf_delete(&sb);
4777 		return (error);
4778 	}
4779 	maxlen = req->oldptr != NULL ? req->oldlen : -1;
4780 	error = kern_proc_filedesc_out(p, &sb, maxlen,
4781 	    KERN_FILEDESC_PACK_KINFO);
4782 	error2 = sbuf_finish(&sb);
4783 	sbuf_delete(&sb);
4784 	return (error != 0 ? error : error2);
4785 }
4786 
4787 #ifdef COMPAT_FREEBSD7
4788 #ifdef KINFO_OFILE_SIZE
4789 CTASSERT(sizeof(struct kinfo_ofile) == KINFO_OFILE_SIZE);
4790 #endif
4791 
4792 static void
kinfo_to_okinfo(struct kinfo_file * kif,struct kinfo_ofile * okif)4793 kinfo_to_okinfo(struct kinfo_file *kif, struct kinfo_ofile *okif)
4794 {
4795 
4796 	okif->kf_structsize = sizeof(*okif);
4797 	okif->kf_type = kif->kf_type;
4798 	okif->kf_fd = kif->kf_fd;
4799 	okif->kf_ref_count = kif->kf_ref_count;
4800 	okif->kf_flags = kif->kf_flags & (KF_FLAG_READ | KF_FLAG_WRITE |
4801 	    KF_FLAG_APPEND | KF_FLAG_ASYNC | KF_FLAG_FSYNC | KF_FLAG_NONBLOCK |
4802 	    KF_FLAG_DIRECT | KF_FLAG_HASLOCK);
4803 	okif->kf_offset = kif->kf_offset;
4804 	if (kif->kf_type == KF_TYPE_VNODE)
4805 		okif->kf_vnode_type = kif->kf_un.kf_file.kf_file_type;
4806 	else
4807 		okif->kf_vnode_type = KF_VTYPE_VNON;
4808 	strlcpy(okif->kf_path, kif->kf_path, sizeof(okif->kf_path));
4809 	if (kif->kf_type == KF_TYPE_SOCKET) {
4810 		okif->kf_sock_domain = kif->kf_un.kf_sock.kf_sock_domain0;
4811 		okif->kf_sock_type = kif->kf_un.kf_sock.kf_sock_type0;
4812 		okif->kf_sock_protocol = kif->kf_un.kf_sock.kf_sock_protocol0;
4813 		okif->kf_sa_local = kif->kf_un.kf_sock.kf_sa_local;
4814 		okif->kf_sa_peer = kif->kf_un.kf_sock.kf_sa_peer;
4815 	} else {
4816 		okif->kf_sa_local.ss_family = AF_UNSPEC;
4817 		okif->kf_sa_peer.ss_family = AF_UNSPEC;
4818 	}
4819 }
4820 
4821 static int
export_vnode_for_osysctl(struct vnode * vp,int type,struct kinfo_file * kif,struct kinfo_ofile * okif,struct pwddesc * pdp,struct sysctl_req * req)4822 export_vnode_for_osysctl(struct vnode *vp, int type, struct kinfo_file *kif,
4823     struct kinfo_ofile *okif, struct pwddesc *pdp, struct sysctl_req *req)
4824 {
4825 	int error;
4826 
4827 	vrefact(vp);
4828 	PWDDESC_XUNLOCK(pdp);
4829 	export_vnode_to_kinfo(vp, type, 0, kif, KERN_FILEDESC_PACK_KINFO);
4830 	kinfo_to_okinfo(kif, okif);
4831 	error = SYSCTL_OUT(req, okif, sizeof(*okif));
4832 	PWDDESC_XLOCK(pdp);
4833 	return (error);
4834 }
4835 
4836 /*
4837  * Get per-process file descriptors for use by procstat(1), et al.
4838  */
4839 static int
sysctl_kern_proc_ofiledesc(SYSCTL_HANDLER_ARGS)4840 sysctl_kern_proc_ofiledesc(SYSCTL_HANDLER_ARGS)
4841 {
4842 	struct kinfo_ofile *okif;
4843 	struct kinfo_file *kif;
4844 	struct filedesc *fdp;
4845 	struct pwddesc *pdp;
4846 	struct pwd *pwd;
4847 	u_int namelen;
4848 	int error, i, *name;
4849 	struct file *fp;
4850 	struct proc *p;
4851 
4852 	namelen = arg2;
4853 	if (namelen != 1)
4854 		return (EINVAL);
4855 
4856 	name = (int *)arg1;
4857 	error = pget((pid_t)name[0], PGET_CANDEBUG | PGET_NOTWEXIT, &p);
4858 	if (error != 0)
4859 		return (error);
4860 	fdp = fdhold(p);
4861 	if (fdp != NULL)
4862 		pdp = pdhold(p);
4863 	PROC_UNLOCK(p);
4864 	if (fdp == NULL || pdp == NULL) {
4865 		if (fdp != NULL)
4866 			fddrop(fdp);
4867 		return (ENOENT);
4868 	}
4869 	kif = malloc(sizeof(*kif), M_TEMP, M_WAITOK);
4870 	okif = malloc(sizeof(*okif), M_TEMP, M_WAITOK);
4871 	PWDDESC_XLOCK(pdp);
4872 	pwd = pwd_hold_pwddesc(pdp);
4873 	if (pwd != NULL) {
4874 		if (pwd->pwd_cdir != NULL)
4875 			export_vnode_for_osysctl(pwd->pwd_cdir, KF_FD_TYPE_CWD, kif,
4876 			    okif, pdp, req);
4877 		if (pwd->pwd_rdir != NULL)
4878 			export_vnode_for_osysctl(pwd->pwd_rdir, KF_FD_TYPE_ROOT, kif,
4879 			    okif, pdp, req);
4880 		if (pwd->pwd_jdir != NULL)
4881 			export_vnode_for_osysctl(pwd->pwd_jdir, KF_FD_TYPE_JAIL, kif,
4882 			    okif, pdp, req);
4883 	}
4884 	PWDDESC_XUNLOCK(pdp);
4885 	if (pwd != NULL)
4886 		pwd_drop(pwd);
4887 	FILEDESC_SLOCK(fdp);
4888 	if (refcount_load(&fdp->fd_refcnt) == 0)
4889 		goto skip;
4890 	FILEDESC_FOREACH_FP(fdp, i, fp) {
4891 		export_file_to_kinfo(fp, i, NULL, kif, fdp,
4892 		    KERN_FILEDESC_PACK_KINFO);
4893 		FILEDESC_SUNLOCK(fdp);
4894 		kinfo_to_okinfo(kif, okif);
4895 		error = SYSCTL_OUT(req, okif, sizeof(*okif));
4896 		FILEDESC_SLOCK(fdp);
4897 		if (error != 0 || refcount_load(&fdp->fd_refcnt) == 0)
4898 			break;
4899 	}
4900 skip:
4901 	FILEDESC_SUNLOCK(fdp);
4902 	fddrop(fdp);
4903 	pddrop(pdp);
4904 	free(kif, M_TEMP);
4905 	free(okif, M_TEMP);
4906 	return (0);
4907 }
4908 
4909 static SYSCTL_NODE(_kern_proc, KERN_PROC_OFILEDESC, ofiledesc,
4910     CTLFLAG_RD|CTLFLAG_MPSAFE, sysctl_kern_proc_ofiledesc,
4911     "Process ofiledesc entries");
4912 #endif	/* COMPAT_FREEBSD7 */
4913 
4914 int
vntype_to_kinfo(int vtype)4915 vntype_to_kinfo(int vtype)
4916 {
4917 	struct {
4918 		int	vtype;
4919 		int	kf_vtype;
4920 	} vtypes_table[] = {
4921 		{ VBAD, KF_VTYPE_VBAD },
4922 		{ VBLK, KF_VTYPE_VBLK },
4923 		{ VCHR, KF_VTYPE_VCHR },
4924 		{ VDIR, KF_VTYPE_VDIR },
4925 		{ VFIFO, KF_VTYPE_VFIFO },
4926 		{ VLNK, KF_VTYPE_VLNK },
4927 		{ VNON, KF_VTYPE_VNON },
4928 		{ VREG, KF_VTYPE_VREG },
4929 		{ VSOCK, KF_VTYPE_VSOCK }
4930 	};
4931 	unsigned int i;
4932 
4933 	/*
4934 	 * Perform vtype translation.
4935 	 */
4936 	for (i = 0; i < nitems(vtypes_table); i++)
4937 		if (vtypes_table[i].vtype == vtype)
4938 			return (vtypes_table[i].kf_vtype);
4939 
4940 	return (KF_VTYPE_UNKNOWN);
4941 }
4942 
4943 static SYSCTL_NODE(_kern_proc, KERN_PROC_FILEDESC, filedesc,
4944     CTLFLAG_RD|CTLFLAG_MPSAFE, sysctl_kern_proc_filedesc,
4945     "Process filedesc entries");
4946 
4947 /*
4948  * Store a process current working directory information to sbuf.
4949  *
4950  * Takes a locked proc as argument, and returns with the proc unlocked.
4951  */
4952 int
kern_proc_cwd_out(struct proc * p,struct sbuf * sb,ssize_t maxlen)4953 kern_proc_cwd_out(struct proc *p,  struct sbuf *sb, ssize_t maxlen)
4954 {
4955 	struct pwddesc *pdp;
4956 	struct pwd *pwd;
4957 	struct export_fd_buf *efbuf;
4958 	struct vnode *cdir;
4959 	int error;
4960 
4961 	PROC_LOCK_ASSERT(p, MA_OWNED);
4962 
4963 	pdp = pdhold(p);
4964 	PROC_UNLOCK(p);
4965 	if (pdp == NULL)
4966 		return (EINVAL);
4967 
4968 	efbuf = malloc(sizeof(*efbuf), M_TEMP, M_WAITOK);
4969 	efbuf->fdp = NULL;
4970 	efbuf->pdp = pdp;
4971 	efbuf->sb = sb;
4972 	efbuf->remainder = maxlen;
4973 	efbuf->flags = 0;
4974 
4975 	PWDDESC_XLOCK(pdp);
4976 	pwd = PWDDESC_XLOCKED_LOAD_PWD(pdp);
4977 	cdir = pwd->pwd_cdir;
4978 	if (cdir == NULL) {
4979 		error = EINVAL;
4980 	} else {
4981 		vrefact(cdir);
4982 		error = export_vnode_to_sb(cdir, KF_FD_TYPE_CWD, FREAD, efbuf);
4983 	}
4984 	PWDDESC_XUNLOCK(pdp);
4985 	pddrop(pdp);
4986 	free(efbuf, M_TEMP);
4987 	return (error);
4988 }
4989 
4990 /*
4991  * Get per-process current working directory.
4992  */
4993 static int
sysctl_kern_proc_cwd(SYSCTL_HANDLER_ARGS)4994 sysctl_kern_proc_cwd(SYSCTL_HANDLER_ARGS)
4995 {
4996 	struct sbuf sb;
4997 	struct proc *p;
4998 	ssize_t maxlen;
4999 	u_int namelen;
5000 	int error, error2, *name;
5001 
5002 	namelen = arg2;
5003 	if (namelen != 1)
5004 		return (EINVAL);
5005 
5006 	name = (int *)arg1;
5007 
5008 	sbuf_new_for_sysctl(&sb, NULL, sizeof(struct kinfo_file), req);
5009 	sbuf_clear_flags(&sb, SBUF_INCLUDENUL);
5010 	error = pget((pid_t)name[0], PGET_CANDEBUG | PGET_NOTWEXIT, &p);
5011 	if (error != 0) {
5012 		sbuf_delete(&sb);
5013 		return (error);
5014 	}
5015 	maxlen = req->oldptr != NULL ? req->oldlen : -1;
5016 	error = kern_proc_cwd_out(p, &sb, maxlen);
5017 	error2 = sbuf_finish(&sb);
5018 	sbuf_delete(&sb);
5019 	return (error != 0 ? error : error2);
5020 }
5021 
5022 static SYSCTL_NODE(_kern_proc, KERN_PROC_CWD, cwd, CTLFLAG_RD|CTLFLAG_MPSAFE,
5023     sysctl_kern_proc_cwd, "Process current working directory");
5024 
5025 #ifdef DDB
5026 /*
5027  * For the purposes of debugging, generate a human-readable string for the
5028  * file type.
5029  */
5030 static const char *
file_type_to_name(short type)5031 file_type_to_name(short type)
5032 {
5033 
5034 	switch (type) {
5035 	case 0:
5036 		return ("zero");
5037 	case DTYPE_VNODE:
5038 		return ("vnode");
5039 	case DTYPE_SOCKET:
5040 		return ("socket");
5041 	case DTYPE_PIPE:
5042 		return ("pipe");
5043 	case DTYPE_FIFO:
5044 		return ("fifo");
5045 	case DTYPE_KQUEUE:
5046 		return ("kqueue");
5047 	case DTYPE_CRYPTO:
5048 		return ("crypto");
5049 	case DTYPE_MQUEUE:
5050 		return ("mqueue");
5051 	case DTYPE_SHM:
5052 		return ("shm");
5053 	case DTYPE_SEM:
5054 		return ("ksem");
5055 	case DTYPE_PTS:
5056 		return ("pts");
5057 	case DTYPE_DEV:
5058 		return ("dev");
5059 	case DTYPE_PROCDESC:
5060 		return ("proc");
5061 	case DTYPE_EVENTFD:
5062 		return ("eventfd");
5063 	case DTYPE_TIMERFD:
5064 		return ("timerfd");
5065 	default:
5066 		return ("unkn");
5067 	}
5068 }
5069 
5070 /*
5071  * For the purposes of debugging, identify a process (if any, perhaps one of
5072  * many) that references the passed file in its file descriptor array. Return
5073  * NULL if none.
5074  */
5075 static struct proc *
file_to_first_proc(struct file * fp)5076 file_to_first_proc(struct file *fp)
5077 {
5078 	struct filedesc *fdp;
5079 	struct proc *p;
5080 	int n;
5081 
5082 	FOREACH_PROC_IN_SYSTEM(p) {
5083 		if (p->p_state == PRS_NEW)
5084 			continue;
5085 		fdp = p->p_fd;
5086 		if (fdp == NULL)
5087 			continue;
5088 		for (n = 0; n < fdp->fd_nfiles; n++) {
5089 			if (fp == fdp->fd_ofiles[n].fde_file)
5090 				return (p);
5091 		}
5092 	}
5093 	return (NULL);
5094 }
5095 
5096 static void
db_print_file(struct file * fp,int header)5097 db_print_file(struct file *fp, int header)
5098 {
5099 #define XPTRWIDTH ((int)howmany(sizeof(void *) * NBBY, 4))
5100 	struct proc *p;
5101 
5102 	if (header)
5103 		db_printf("%*s %6s %*s %8s %4s %5s %6s %*s %5s %s\n",
5104 		    XPTRWIDTH, "File", "Type", XPTRWIDTH, "Data", "Flag",
5105 		    "GCFl", "Count", "MCount", XPTRWIDTH, "Vnode", "FPID",
5106 		    "FCmd");
5107 	p = file_to_first_proc(fp);
5108 	db_printf("%*p %6s %*p %08x %04x %5d %6d %*p %5d %s\n", XPTRWIDTH,
5109 	    fp, file_type_to_name(fp->f_type), XPTRWIDTH, fp->f_data,
5110 	    fp->f_flag, 0, refcount_load(&fp->f_count), 0, XPTRWIDTH, fp->f_vnode,
5111 	    p != NULL ? p->p_pid : -1, p != NULL ? p->p_comm : "-");
5112 
5113 #undef XPTRWIDTH
5114 }
5115 
DB_SHOW_COMMAND(file,db_show_file)5116 DB_SHOW_COMMAND(file, db_show_file)
5117 {
5118 	struct file *fp;
5119 
5120 	if (!have_addr) {
5121 		db_printf("usage: show file <addr>\n");
5122 		return;
5123 	}
5124 	fp = (struct file *)addr;
5125 	db_print_file(fp, 1);
5126 }
5127 
DB_SHOW_COMMAND_FLAGS(files,db_show_files,DB_CMD_MEMSAFE)5128 DB_SHOW_COMMAND_FLAGS(files, db_show_files, DB_CMD_MEMSAFE)
5129 {
5130 	struct filedesc *fdp;
5131 	struct file *fp;
5132 	struct proc *p;
5133 	int header;
5134 	int n;
5135 
5136 	header = 1;
5137 	FOREACH_PROC_IN_SYSTEM(p) {
5138 		if (p->p_state == PRS_NEW)
5139 			continue;
5140 		if ((fdp = p->p_fd) == NULL)
5141 			continue;
5142 		for (n = 0; n < fdp->fd_nfiles; ++n) {
5143 			if ((fp = fdp->fd_ofiles[n].fde_file) == NULL)
5144 				continue;
5145 			db_print_file(fp, header);
5146 			header = 0;
5147 		}
5148 	}
5149 }
5150 #endif
5151 
5152 SYSCTL_INT(_kern, KERN_MAXFILESPERPROC, maxfilesperproc,
5153     CTLFLAG_RWTUN | CTLFLAG_NOFETCH,
5154     &maxfilesperproc, 0, "Maximum files allowed open per process");
5155 
5156 SYSCTL_INT(_kern, KERN_MAXFILES, maxfiles, CTLFLAG_RWTUN | CTLFLAG_NOFETCH,
5157     &maxfiles, 0, "Maximum number of files");
5158 
5159 SYSCTL_INT(_kern, OID_AUTO, openfiles, CTLFLAG_RD,
5160     &openfiles, 0, "System-wide number of open files");
5161 
5162 /* ARGSUSED*/
5163 static void
filelistinit(void * dummy)5164 filelistinit(void *dummy)
5165 {
5166 
5167 	file_zone = uma_zcreate("Files", sizeof(struct file), NULL, NULL,
5168 	    NULL, NULL, UMA_ALIGN_PTR, UMA_ZONE_NOFREE);
5169 	filedesc0_zone = uma_zcreate("filedesc0", sizeof(struct filedesc0),
5170 	    NULL, NULL, NULL, NULL, UMA_ALIGN_PTR, 0);
5171 	pwd_zone = uma_zcreate("PWD", sizeof(struct pwd), NULL, NULL,
5172 	    NULL, NULL, UMA_ALIGN_PTR, UMA_ZONE_SMR);
5173 	/*
5174 	 * XXXMJG this is a temporary hack due to boot ordering issues against
5175 	 * the vnode zone.
5176 	 */
5177 	vfs_smr = uma_zone_get_smr(pwd_zone);
5178 	mtx_init(&sigio_lock, "sigio lock", NULL, MTX_DEF);
5179 }
5180 SYSINIT(select, SI_SUB_LOCK, SI_ORDER_FIRST, filelistinit, NULL);
5181 
5182 /*-------------------------------------------------------------------*/
5183 
5184 static int
badfo_readwrite(struct file * fp,struct uio * uio,struct ucred * active_cred,int flags,struct thread * td)5185 badfo_readwrite(struct file *fp, struct uio *uio, struct ucred *active_cred,
5186     int flags, struct thread *td)
5187 {
5188 
5189 	return (EBADF);
5190 }
5191 
5192 static int
badfo_truncate(struct file * fp,off_t length,struct ucred * active_cred,struct thread * td)5193 badfo_truncate(struct file *fp, off_t length, struct ucred *active_cred,
5194     struct thread *td)
5195 {
5196 
5197 	return (EINVAL);
5198 }
5199 
5200 static int
badfo_ioctl(struct file * fp,u_long com,void * data,struct ucred * active_cred,struct thread * td)5201 badfo_ioctl(struct file *fp, u_long com, void *data, struct ucred *active_cred,
5202     struct thread *td)
5203 {
5204 
5205 	return (EBADF);
5206 }
5207 
5208 static int
badfo_poll(struct file * fp,int events,struct ucred * active_cred,struct thread * td)5209 badfo_poll(struct file *fp, int events, struct ucred *active_cred,
5210     struct thread *td)
5211 {
5212 
5213 	return (0);
5214 }
5215 
5216 static int
badfo_kqfilter(struct file * fp,struct knote * kn)5217 badfo_kqfilter(struct file *fp, struct knote *kn)
5218 {
5219 
5220 	return (EBADF);
5221 }
5222 
5223 static int
badfo_stat(struct file * fp,struct stat * sb,struct ucred * active_cred)5224 badfo_stat(struct file *fp, struct stat *sb, struct ucred *active_cred)
5225 {
5226 
5227 	return (EBADF);
5228 }
5229 
5230 static int
badfo_close(struct file * fp,struct thread * td)5231 badfo_close(struct file *fp, struct thread *td)
5232 {
5233 
5234 	return (0);
5235 }
5236 
5237 static int
badfo_chmod(struct file * fp,mode_t mode,struct ucred * active_cred,struct thread * td)5238 badfo_chmod(struct file *fp, mode_t mode, struct ucred *active_cred,
5239     struct thread *td)
5240 {
5241 
5242 	return (EBADF);
5243 }
5244 
5245 static int
badfo_chown(struct file * fp,uid_t uid,gid_t gid,struct ucred * active_cred,struct thread * td)5246 badfo_chown(struct file *fp, uid_t uid, gid_t gid, struct ucred *active_cred,
5247     struct thread *td)
5248 {
5249 
5250 	return (EBADF);
5251 }
5252 
5253 static int
badfo_sendfile(struct file * fp,int sockfd,struct uio * hdr_uio,struct uio * trl_uio,off_t offset,size_t nbytes,off_t * sent,int flags,struct thread * td)5254 badfo_sendfile(struct file *fp, int sockfd, struct uio *hdr_uio,
5255     struct uio *trl_uio, off_t offset, size_t nbytes, off_t *sent, int flags,
5256     struct thread *td)
5257 {
5258 
5259 	return (EBADF);
5260 }
5261 
5262 static int
badfo_fill_kinfo(struct file * fp,struct kinfo_file * kif,struct filedesc * fdp)5263 badfo_fill_kinfo(struct file *fp, struct kinfo_file *kif, struct filedesc *fdp)
5264 {
5265 
5266 	return (0);
5267 }
5268 
5269 const struct fileops badfileops = {
5270 	.fo_read = badfo_readwrite,
5271 	.fo_write = badfo_readwrite,
5272 	.fo_truncate = badfo_truncate,
5273 	.fo_ioctl = badfo_ioctl,
5274 	.fo_poll = badfo_poll,
5275 	.fo_kqfilter = badfo_kqfilter,
5276 	.fo_stat = badfo_stat,
5277 	.fo_close = badfo_close,
5278 	.fo_chmod = badfo_chmod,
5279 	.fo_chown = badfo_chown,
5280 	.fo_sendfile = badfo_sendfile,
5281 	.fo_fill_kinfo = badfo_fill_kinfo,
5282 };
5283 
5284 static int
path_poll(struct file * fp,int events,struct ucred * active_cred,struct thread * td)5285 path_poll(struct file *fp, int events, struct ucred *active_cred,
5286     struct thread *td)
5287 {
5288 	return (POLLNVAL);
5289 }
5290 
5291 static int
path_close(struct file * fp,struct thread * td)5292 path_close(struct file *fp, struct thread *td)
5293 {
5294 	MPASS(fp->f_type == DTYPE_VNODE);
5295 	fp->f_ops = &badfileops;
5296 	vrele(fp->f_vnode);
5297 	return (0);
5298 }
5299 
5300 const struct fileops path_fileops = {
5301 	.fo_read = badfo_readwrite,
5302 	.fo_write = badfo_readwrite,
5303 	.fo_truncate = badfo_truncate,
5304 	.fo_ioctl = badfo_ioctl,
5305 	.fo_poll = path_poll,
5306 	.fo_kqfilter = vn_kqfilter_opath,
5307 	.fo_stat = vn_statfile,
5308 	.fo_close = path_close,
5309 	.fo_chmod = badfo_chmod,
5310 	.fo_chown = badfo_chown,
5311 	.fo_sendfile = badfo_sendfile,
5312 	.fo_fill_kinfo = vn_fill_kinfo,
5313 	.fo_cmp = vn_cmp,
5314 	.fo_flags = DFLAG_PASSABLE,
5315 };
5316 
5317 int
invfo_rdwr(struct file * fp,struct uio * uio,struct ucred * active_cred,int flags,struct thread * td)5318 invfo_rdwr(struct file *fp, struct uio *uio, struct ucred *active_cred,
5319     int flags, struct thread *td)
5320 {
5321 
5322 	return (EOPNOTSUPP);
5323 }
5324 
5325 int
invfo_truncate(struct file * fp,off_t length,struct ucred * active_cred,struct thread * td)5326 invfo_truncate(struct file *fp, off_t length, struct ucred *active_cred,
5327     struct thread *td)
5328 {
5329 
5330 	return (EINVAL);
5331 }
5332 
5333 int
invfo_ioctl(struct file * fp,u_long com,void * data,struct ucred * active_cred,struct thread * td)5334 invfo_ioctl(struct file *fp, u_long com, void *data,
5335     struct ucred *active_cred, struct thread *td)
5336 {
5337 
5338 	return (ENOTTY);
5339 }
5340 
5341 int
invfo_poll(struct file * fp,int events,struct ucred * active_cred,struct thread * td)5342 invfo_poll(struct file *fp, int events, struct ucred *active_cred,
5343     struct thread *td)
5344 {
5345 
5346 	return (poll_no_poll(events));
5347 }
5348 
5349 int
invfo_kqfilter(struct file * fp,struct knote * kn)5350 invfo_kqfilter(struct file *fp, struct knote *kn)
5351 {
5352 
5353 	return (EINVAL);
5354 }
5355 
5356 int
invfo_chmod(struct file * fp,mode_t mode,struct ucred * active_cred,struct thread * td)5357 invfo_chmod(struct file *fp, mode_t mode, struct ucred *active_cred,
5358     struct thread *td)
5359 {
5360 
5361 	return (EINVAL);
5362 }
5363 
5364 int
invfo_chown(struct file * fp,uid_t uid,gid_t gid,struct ucred * active_cred,struct thread * td)5365 invfo_chown(struct file *fp, uid_t uid, gid_t gid, struct ucred *active_cred,
5366     struct thread *td)
5367 {
5368 
5369 	return (EINVAL);
5370 }
5371 
5372 int
invfo_sendfile(struct file * fp,int sockfd,struct uio * hdr_uio,struct uio * trl_uio,off_t offset,size_t nbytes,off_t * sent,int flags,struct thread * td)5373 invfo_sendfile(struct file *fp, int sockfd, struct uio *hdr_uio,
5374     struct uio *trl_uio, off_t offset, size_t nbytes, off_t *sent, int flags,
5375     struct thread *td)
5376 {
5377 
5378 	return (EINVAL);
5379 }
5380 
5381 /*-------------------------------------------------------------------*/
5382 
5383 /*
5384  * File Descriptor pseudo-device driver (/dev/fd/).
5385  *
5386  * Opening minor device N dup()s the file (if any) connected to file
5387  * descriptor N belonging to the calling process.  Note that this driver
5388  * consists of only the ``open()'' routine, because all subsequent
5389  * references to this file will be direct to the other driver.
5390  *
5391  * XXX: we could give this one a cloning event handler if necessary.
5392  */
5393 
5394 /* ARGSUSED */
5395 static int
fdopen(struct cdev * dev,int mode,int type,struct thread * td)5396 fdopen(struct cdev *dev, int mode, int type, struct thread *td)
5397 {
5398 
5399 	/*
5400 	 * XXX Kludge: set curthread->td_dupfd to contain the value of the
5401 	 * the file descriptor being sought for duplication. The error
5402 	 * return ensures that the vnode for this device will be released
5403 	 * by vn_open. Open will detect this special error and take the
5404 	 * actions in dupfdopen below. Other callers of vn_open or VOP_OPEN
5405 	 * will simply report the error.
5406 	 */
5407 	td->td_dupfd = dev2unit(dev);
5408 	return (ENODEV);
5409 }
5410 
5411 static struct cdevsw fildesc_cdevsw = {
5412 	.d_version =	D_VERSION,
5413 	.d_open =	fdopen,
5414 	.d_name =	"FD",
5415 };
5416 
5417 static void
fildesc_drvinit(void * unused)5418 fildesc_drvinit(void *unused)
5419 {
5420 	struct cdev *dev;
5421 
5422 	dev = make_dev_credf(MAKEDEV_ETERNAL, &fildesc_cdevsw, 0, NULL,
5423 	    UID_ROOT, GID_WHEEL, 0666, "fd/0");
5424 	make_dev_alias(dev, "stdin");
5425 	dev = make_dev_credf(MAKEDEV_ETERNAL, &fildesc_cdevsw, 1, NULL,
5426 	    UID_ROOT, GID_WHEEL, 0666, "fd/1");
5427 	make_dev_alias(dev, "stdout");
5428 	dev = make_dev_credf(MAKEDEV_ETERNAL, &fildesc_cdevsw, 2, NULL,
5429 	    UID_ROOT, GID_WHEEL, 0666, "fd/2");
5430 	make_dev_alias(dev, "stderr");
5431 }
5432 
5433 SYSINIT(fildescdev, SI_SUB_DRIVERS, SI_ORDER_MIDDLE, fildesc_drvinit, NULL);
5434