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