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