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