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