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