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