1 /*- 2 * Copyright (c) 1982, 1986, 1989, 1991, 1993 3 * The Regents of the University of California. All rights reserved. 4 * (c) UNIX System Laboratories, Inc. 5 * All or some portions of this file are derived from material licensed 6 * to the University of California by American Telephone and Telegraph 7 * Co. or Unix System Laboratories, Inc. and are reproduced herein with 8 * the permission of UNIX System Laboratories, Inc. 9 * 10 * Redistribution and use in source and binary forms, with or without 11 * modification, are permitted provided that the following conditions 12 * are met: 13 * 1. Redistributions of source code must retain the above copyright 14 * notice, this list of conditions and the following disclaimer. 15 * 2. Redistributions in binary form must reproduce the above copyright 16 * notice, this list of conditions and the following disclaimer in the 17 * documentation and/or other materials provided with the distribution. 18 * 4. Neither the name of the University nor the names of its contributors 19 * may be used to endorse or promote products derived from this software 20 * without specific prior written permission. 21 * 22 * THIS SOFTWARE IS PROVIDED BY THE REGENTS AND CONTRIBUTORS ``AS IS'' AND 23 * ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE 24 * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE 25 * ARE DISCLAIMED. IN NO EVENT SHALL THE REGENTS OR CONTRIBUTORS BE LIABLE 26 * FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL 27 * DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS 28 * OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) 29 * HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT 30 * LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY 31 * OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF 32 * SUCH DAMAGE. 33 * 34 * @(#)kern_descrip.c 8.6 (Berkeley) 4/19/94 35 */ 36 37 #include <sys/cdefs.h> 38 __FBSDID("$FreeBSD$"); 39 40 #include "opt_capsicum.h" 41 #include "opt_compat.h" 42 #include "opt_ddb.h" 43 #include "opt_ktrace.h" 44 45 #include <sys/param.h> 46 #include <sys/systm.h> 47 48 #include <sys/capsicum.h> 49 #include <sys/conf.h> 50 #include <sys/fcntl.h> 51 #include <sys/file.h> 52 #include <sys/filedesc.h> 53 #include <sys/filio.h> 54 #include <sys/jail.h> 55 #include <sys/kernel.h> 56 #include <sys/limits.h> 57 #include <sys/lock.h> 58 #include <sys/malloc.h> 59 #include <sys/mount.h> 60 #include <sys/mutex.h> 61 #include <sys/namei.h> 62 #include <sys/selinfo.h> 63 #include <sys/priv.h> 64 #include <sys/proc.h> 65 #include <sys/protosw.h> 66 #include <sys/racct.h> 67 #include <sys/resourcevar.h> 68 #include <sys/sbuf.h> 69 #include <sys/signalvar.h> 70 #include <sys/socketvar.h> 71 #include <sys/kdb.h> 72 #include <sys/stat.h> 73 #include <sys/sx.h> 74 #include <sys/syscallsubr.h> 75 #include <sys/sysctl.h> 76 #include <sys/sysproto.h> 77 #include <sys/unistd.h> 78 #include <sys/user.h> 79 #include <sys/vnode.h> 80 #ifdef KTRACE 81 #include <sys/ktrace.h> 82 #endif 83 84 #include <net/vnet.h> 85 86 #include <security/audit/audit.h> 87 88 #include <vm/uma.h> 89 #include <vm/vm.h> 90 91 #include <ddb/ddb.h> 92 93 static MALLOC_DEFINE(M_FILEDESC, "filedesc", "Open file descriptor table"); 94 static MALLOC_DEFINE(M_FILEDESC_TO_LEADER, "filedesc_to_leader", 95 "file desc to leader structures"); 96 static MALLOC_DEFINE(M_SIGIO, "sigio", "sigio structures"); 97 MALLOC_DEFINE(M_FILECAPS, "filecaps", "descriptor capabilities"); 98 99 MALLOC_DECLARE(M_FADVISE); 100 101 static uma_zone_t file_zone; 102 static uma_zone_t filedesc0_zone; 103 104 static int closefp(struct filedesc *fdp, int fd, struct file *fp, 105 struct thread *td, int holdleaders); 106 static int fd_first_free(struct filedesc *fdp, int low, int size); 107 static int fd_last_used(struct filedesc *fdp, int size); 108 static void fdgrowtable(struct filedesc *fdp, int nfd); 109 static void fdgrowtable_exp(struct filedesc *fdp, int nfd); 110 static void fdunused(struct filedesc *fdp, int fd); 111 static void fdused(struct filedesc *fdp, int fd); 112 static int getmaxfd(struct thread *td); 113 114 /* 115 * Each process has: 116 * 117 * - An array of open file descriptors (fd_ofiles) 118 * - An array of file flags (fd_ofileflags) 119 * - A bitmap recording which descriptors are in use (fd_map) 120 * 121 * A process starts out with NDFILE descriptors. The value of NDFILE has 122 * been selected based the historical limit of 20 open files, and an 123 * assumption that the majority of processes, especially short-lived 124 * processes like shells, will never need more. 125 * 126 * If this initial allocation is exhausted, a larger descriptor table and 127 * map are allocated dynamically, and the pointers in the process's struct 128 * filedesc are updated to point to those. This is repeated every time 129 * the process runs out of file descriptors (provided it hasn't hit its 130 * resource limit). 131 * 132 * Since threads may hold references to individual descriptor table 133 * entries, the tables are never freed. Instead, they are placed on a 134 * linked list and freed only when the struct filedesc is released. 135 */ 136 #define NDFILE 20 137 #define NDSLOTSIZE sizeof(NDSLOTTYPE) 138 #define NDENTRIES (NDSLOTSIZE * __CHAR_BIT) 139 #define NDSLOT(x) ((x) / NDENTRIES) 140 #define NDBIT(x) ((NDSLOTTYPE)1 << ((x) % NDENTRIES)) 141 #define NDSLOTS(x) (((x) + NDENTRIES - 1) / NDENTRIES) 142 143 /* 144 * SLIST entry used to keep track of ofiles which must be reclaimed when 145 * the process exits. 146 */ 147 struct freetable { 148 struct fdescenttbl *ft_table; 149 SLIST_ENTRY(freetable) ft_next; 150 }; 151 152 /* 153 * Initial allocation: a filedesc structure + the head of SLIST used to 154 * keep track of old ofiles + enough space for NDFILE descriptors. 155 */ 156 157 struct fdescenttbl0 { 158 int fdt_nfiles; 159 struct filedescent fdt_ofiles[NDFILE]; 160 }; 161 162 struct filedesc0 { 163 struct filedesc fd_fd; 164 SLIST_HEAD(, freetable) fd_free; 165 struct fdescenttbl0 fd_dfiles; 166 NDSLOTTYPE fd_dmap[NDSLOTS(NDFILE)]; 167 }; 168 169 /* 170 * Descriptor management. 171 */ 172 volatile int openfiles; /* actual number of open files */ 173 struct mtx sigio_lock; /* mtx to protect pointers to sigio */ 174 void (*mq_fdclose)(struct thread *td, int fd, struct file *fp); 175 176 /* 177 * If low >= size, just return low. Otherwise find the first zero bit in the 178 * given bitmap, starting at low and not exceeding size - 1. Return size if 179 * not found. 180 */ 181 static int 182 fd_first_free(struct filedesc *fdp, int low, int size) 183 { 184 NDSLOTTYPE *map = fdp->fd_map; 185 NDSLOTTYPE mask; 186 int off, maxoff; 187 188 if (low >= size) 189 return (low); 190 191 off = NDSLOT(low); 192 if (low % NDENTRIES) { 193 mask = ~(~(NDSLOTTYPE)0 >> (NDENTRIES - (low % NDENTRIES))); 194 if ((mask &= ~map[off]) != 0UL) 195 return (off * NDENTRIES + ffsl(mask) - 1); 196 ++off; 197 } 198 for (maxoff = NDSLOTS(size); off < maxoff; ++off) 199 if (map[off] != ~0UL) 200 return (off * NDENTRIES + ffsl(~map[off]) - 1); 201 return (size); 202 } 203 204 /* 205 * Find the highest non-zero bit in the given bitmap, starting at 0 and 206 * not exceeding size - 1. Return -1 if not found. 207 */ 208 static int 209 fd_last_used(struct filedesc *fdp, int size) 210 { 211 NDSLOTTYPE *map = fdp->fd_map; 212 NDSLOTTYPE mask; 213 int off, minoff; 214 215 off = NDSLOT(size); 216 if (size % NDENTRIES) { 217 mask = ~(~(NDSLOTTYPE)0 << (size % NDENTRIES)); 218 if ((mask &= map[off]) != 0) 219 return (off * NDENTRIES + flsl(mask) - 1); 220 --off; 221 } 222 for (minoff = NDSLOT(0); off >= minoff; --off) 223 if (map[off] != 0) 224 return (off * NDENTRIES + flsl(map[off]) - 1); 225 return (-1); 226 } 227 228 static int 229 fdisused(struct filedesc *fdp, int fd) 230 { 231 232 KASSERT(fd >= 0 && fd < fdp->fd_nfiles, 233 ("file descriptor %d out of range (0, %d)", fd, fdp->fd_nfiles)); 234 235 return ((fdp->fd_map[NDSLOT(fd)] & NDBIT(fd)) != 0); 236 } 237 238 /* 239 * Mark a file descriptor as used. 240 */ 241 static void 242 fdused_init(struct filedesc *fdp, int fd) 243 { 244 245 KASSERT(!fdisused(fdp, fd), ("fd=%d is already used", fd)); 246 247 fdp->fd_map[NDSLOT(fd)] |= NDBIT(fd); 248 } 249 250 static void 251 fdused(struct filedesc *fdp, int fd) 252 { 253 254 FILEDESC_XLOCK_ASSERT(fdp); 255 256 fdused_init(fdp, fd); 257 if (fd > fdp->fd_lastfile) 258 fdp->fd_lastfile = fd; 259 if (fd == fdp->fd_freefile) 260 fdp->fd_freefile = fd_first_free(fdp, fd, fdp->fd_nfiles); 261 } 262 263 /* 264 * Mark a file descriptor as unused. 265 */ 266 static void 267 fdunused(struct filedesc *fdp, int fd) 268 { 269 270 FILEDESC_XLOCK_ASSERT(fdp); 271 272 KASSERT(fdisused(fdp, fd), ("fd=%d is already unused", fd)); 273 KASSERT(fdp->fd_ofiles[fd].fde_file == NULL, 274 ("fd=%d is still in use", fd)); 275 276 fdp->fd_map[NDSLOT(fd)] &= ~NDBIT(fd); 277 if (fd < fdp->fd_freefile) 278 fdp->fd_freefile = fd; 279 if (fd == fdp->fd_lastfile) 280 fdp->fd_lastfile = fd_last_used(fdp, fd); 281 } 282 283 /* 284 * Free a file descriptor. 285 * 286 * Avoid some work if fdp is about to be destroyed. 287 */ 288 static inline void 289 fdefree_last(struct filedescent *fde) 290 { 291 292 filecaps_free(&fde->fde_caps); 293 } 294 295 static inline void 296 fdfree(struct filedesc *fdp, int fd) 297 { 298 struct filedescent *fde; 299 300 fde = &fdp->fd_ofiles[fd]; 301 #ifdef CAPABILITIES 302 seq_write_begin(&fde->fde_seq); 303 #endif 304 fdefree_last(fde); 305 fde->fde_file = NULL; 306 fdunused(fdp, fd); 307 #ifdef CAPABILITIES 308 seq_write_end(&fde->fde_seq); 309 #endif 310 } 311 312 void 313 pwd_ensure_dirs(void) 314 { 315 struct filedesc *fdp; 316 317 fdp = curproc->p_fd; 318 FILEDESC_XLOCK(fdp); 319 if (fdp->fd_cdir == NULL) { 320 fdp->fd_cdir = rootvnode; 321 VREF(rootvnode); 322 } 323 if (fdp->fd_rdir == NULL) { 324 fdp->fd_rdir = rootvnode; 325 VREF(rootvnode); 326 } 327 FILEDESC_XUNLOCK(fdp); 328 } 329 330 /* 331 * System calls on descriptors. 332 */ 333 #ifndef _SYS_SYSPROTO_H_ 334 struct getdtablesize_args { 335 int dummy; 336 }; 337 #endif 338 /* ARGSUSED */ 339 int 340 sys_getdtablesize(struct thread *td, struct getdtablesize_args *uap) 341 { 342 #ifdef RACCT 343 uint64_t lim; 344 #endif 345 346 td->td_retval[0] = 347 min((int)lim_cur(td, RLIMIT_NOFILE), maxfilesperproc); 348 #ifdef RACCT 349 PROC_LOCK(td->td_proc); 350 lim = racct_get_limit(td->td_proc, RACCT_NOFILE); 351 PROC_UNLOCK(td->td_proc); 352 if (lim < td->td_retval[0]) 353 td->td_retval[0] = lim; 354 #endif 355 return (0); 356 } 357 358 /* 359 * Duplicate a file descriptor to a particular value. 360 * 361 * Note: keep in mind that a potential race condition exists when closing 362 * descriptors from a shared descriptor table (via rfork). 363 */ 364 #ifndef _SYS_SYSPROTO_H_ 365 struct dup2_args { 366 u_int from; 367 u_int to; 368 }; 369 #endif 370 /* ARGSUSED */ 371 int 372 sys_dup2(struct thread *td, struct dup2_args *uap) 373 { 374 375 return (kern_dup(td, FDDUP_FIXED, 0, (int)uap->from, (int)uap->to)); 376 } 377 378 /* 379 * Duplicate a file descriptor. 380 */ 381 #ifndef _SYS_SYSPROTO_H_ 382 struct dup_args { 383 u_int fd; 384 }; 385 #endif 386 /* ARGSUSED */ 387 int 388 sys_dup(struct thread *td, struct dup_args *uap) 389 { 390 391 return (kern_dup(td, FDDUP_NORMAL, 0, (int)uap->fd, 0)); 392 } 393 394 /* 395 * The file control system call. 396 */ 397 #ifndef _SYS_SYSPROTO_H_ 398 struct fcntl_args { 399 int fd; 400 int cmd; 401 long arg; 402 }; 403 #endif 404 /* ARGSUSED */ 405 int 406 sys_fcntl(struct thread *td, struct fcntl_args *uap) 407 { 408 409 return (kern_fcntl_freebsd(td, uap->fd, uap->cmd, uap->arg)); 410 } 411 412 int 413 kern_fcntl_freebsd(struct thread *td, int fd, int cmd, long arg) 414 { 415 struct flock fl; 416 struct __oflock ofl; 417 intptr_t arg1; 418 int error, newcmd; 419 420 error = 0; 421 newcmd = cmd; 422 switch (cmd) { 423 case F_OGETLK: 424 case F_OSETLK: 425 case F_OSETLKW: 426 /* 427 * Convert old flock structure to new. 428 */ 429 error = copyin((void *)(intptr_t)arg, &ofl, sizeof(ofl)); 430 fl.l_start = ofl.l_start; 431 fl.l_len = ofl.l_len; 432 fl.l_pid = ofl.l_pid; 433 fl.l_type = ofl.l_type; 434 fl.l_whence = ofl.l_whence; 435 fl.l_sysid = 0; 436 437 switch (cmd) { 438 case F_OGETLK: 439 newcmd = F_GETLK; 440 break; 441 case F_OSETLK: 442 newcmd = F_SETLK; 443 break; 444 case F_OSETLKW: 445 newcmd = F_SETLKW; 446 break; 447 } 448 arg1 = (intptr_t)&fl; 449 break; 450 case F_GETLK: 451 case F_SETLK: 452 case F_SETLKW: 453 case F_SETLK_REMOTE: 454 error = copyin((void *)(intptr_t)arg, &fl, sizeof(fl)); 455 arg1 = (intptr_t)&fl; 456 break; 457 default: 458 arg1 = arg; 459 break; 460 } 461 if (error) 462 return (error); 463 error = kern_fcntl(td, fd, newcmd, arg1); 464 if (error) 465 return (error); 466 if (cmd == F_OGETLK) { 467 ofl.l_start = fl.l_start; 468 ofl.l_len = fl.l_len; 469 ofl.l_pid = fl.l_pid; 470 ofl.l_type = fl.l_type; 471 ofl.l_whence = fl.l_whence; 472 error = copyout(&ofl, (void *)(intptr_t)arg, sizeof(ofl)); 473 } else if (cmd == F_GETLK) { 474 error = copyout(&fl, (void *)(intptr_t)arg, sizeof(fl)); 475 } 476 return (error); 477 } 478 479 int 480 kern_fcntl(struct thread *td, int fd, int cmd, intptr_t arg) 481 { 482 struct filedesc *fdp; 483 struct flock *flp; 484 struct file *fp, *fp2; 485 struct filedescent *fde; 486 struct proc *p; 487 struct vnode *vp; 488 cap_rights_t rights; 489 int error, flg, tmp; 490 uint64_t bsize; 491 off_t foffset; 492 493 error = 0; 494 flg = F_POSIX; 495 p = td->td_proc; 496 fdp = p->p_fd; 497 498 switch (cmd) { 499 case F_DUPFD: 500 tmp = arg; 501 error = kern_dup(td, FDDUP_FCNTL, 0, fd, tmp); 502 break; 503 504 case F_DUPFD_CLOEXEC: 505 tmp = arg; 506 error = kern_dup(td, FDDUP_FCNTL, FDDUP_FLAG_CLOEXEC, fd, tmp); 507 break; 508 509 case F_DUP2FD: 510 tmp = arg; 511 error = kern_dup(td, FDDUP_FIXED, 0, fd, tmp); 512 break; 513 514 case F_DUP2FD_CLOEXEC: 515 tmp = arg; 516 error = kern_dup(td, FDDUP_FIXED, FDDUP_FLAG_CLOEXEC, fd, tmp); 517 break; 518 519 case F_GETFD: 520 FILEDESC_SLOCK(fdp); 521 if (fget_locked(fdp, fd) == NULL) { 522 FILEDESC_SUNLOCK(fdp); 523 error = EBADF; 524 break; 525 } 526 fde = &fdp->fd_ofiles[fd]; 527 td->td_retval[0] = 528 (fde->fde_flags & UF_EXCLOSE) ? FD_CLOEXEC : 0; 529 FILEDESC_SUNLOCK(fdp); 530 break; 531 532 case F_SETFD: 533 FILEDESC_XLOCK(fdp); 534 if (fget_locked(fdp, fd) == NULL) { 535 FILEDESC_XUNLOCK(fdp); 536 error = EBADF; 537 break; 538 } 539 fde = &fdp->fd_ofiles[fd]; 540 fde->fde_flags = (fde->fde_flags & ~UF_EXCLOSE) | 541 (arg & FD_CLOEXEC ? UF_EXCLOSE : 0); 542 FILEDESC_XUNLOCK(fdp); 543 break; 544 545 case F_GETFL: 546 error = fget_fcntl(td, fd, 547 cap_rights_init(&rights, CAP_FCNTL), F_GETFL, &fp); 548 if (error != 0) 549 break; 550 td->td_retval[0] = OFLAGS(fp->f_flag); 551 fdrop(fp, td); 552 break; 553 554 case F_SETFL: 555 error = fget_fcntl(td, fd, 556 cap_rights_init(&rights, CAP_FCNTL), F_SETFL, &fp); 557 if (error != 0) 558 break; 559 do { 560 tmp = flg = fp->f_flag; 561 tmp &= ~FCNTLFLAGS; 562 tmp |= FFLAGS(arg & ~O_ACCMODE) & FCNTLFLAGS; 563 } while(atomic_cmpset_int(&fp->f_flag, flg, tmp) == 0); 564 tmp = fp->f_flag & FNONBLOCK; 565 error = fo_ioctl(fp, FIONBIO, &tmp, td->td_ucred, td); 566 if (error != 0) { 567 fdrop(fp, td); 568 break; 569 } 570 tmp = fp->f_flag & FASYNC; 571 error = fo_ioctl(fp, FIOASYNC, &tmp, td->td_ucred, td); 572 if (error == 0) { 573 fdrop(fp, td); 574 break; 575 } 576 atomic_clear_int(&fp->f_flag, FNONBLOCK); 577 tmp = 0; 578 (void)fo_ioctl(fp, FIONBIO, &tmp, td->td_ucred, td); 579 fdrop(fp, td); 580 break; 581 582 case F_GETOWN: 583 error = fget_fcntl(td, fd, 584 cap_rights_init(&rights, CAP_FCNTL), F_GETOWN, &fp); 585 if (error != 0) 586 break; 587 error = fo_ioctl(fp, FIOGETOWN, &tmp, td->td_ucred, td); 588 if (error == 0) 589 td->td_retval[0] = tmp; 590 fdrop(fp, td); 591 break; 592 593 case F_SETOWN: 594 error = fget_fcntl(td, fd, 595 cap_rights_init(&rights, CAP_FCNTL), F_SETOWN, &fp); 596 if (error != 0) 597 break; 598 tmp = arg; 599 error = fo_ioctl(fp, FIOSETOWN, &tmp, td->td_ucred, td); 600 fdrop(fp, td); 601 break; 602 603 case F_SETLK_REMOTE: 604 error = priv_check(td, PRIV_NFS_LOCKD); 605 if (error) 606 return (error); 607 flg = F_REMOTE; 608 goto do_setlk; 609 610 case F_SETLKW: 611 flg |= F_WAIT; 612 /* FALLTHROUGH F_SETLK */ 613 614 case F_SETLK: 615 do_setlk: 616 cap_rights_init(&rights, CAP_FLOCK); 617 error = fget_unlocked(fdp, fd, &rights, &fp, NULL); 618 if (error != 0) 619 break; 620 if (fp->f_type != DTYPE_VNODE) { 621 error = EBADF; 622 fdrop(fp, td); 623 break; 624 } 625 626 flp = (struct flock *)arg; 627 if (flp->l_whence == SEEK_CUR) { 628 foffset = foffset_get(fp); 629 if (foffset < 0 || 630 (flp->l_start > 0 && 631 foffset > OFF_MAX - flp->l_start)) { 632 error = EOVERFLOW; 633 fdrop(fp, td); 634 break; 635 } 636 flp->l_start += foffset; 637 } 638 639 vp = fp->f_vnode; 640 switch (flp->l_type) { 641 case F_RDLCK: 642 if ((fp->f_flag & FREAD) == 0) { 643 error = EBADF; 644 break; 645 } 646 PROC_LOCK(p->p_leader); 647 p->p_leader->p_flag |= P_ADVLOCK; 648 PROC_UNLOCK(p->p_leader); 649 error = VOP_ADVLOCK(vp, (caddr_t)p->p_leader, F_SETLK, 650 flp, flg); 651 break; 652 case F_WRLCK: 653 if ((fp->f_flag & FWRITE) == 0) { 654 error = EBADF; 655 break; 656 } 657 PROC_LOCK(p->p_leader); 658 p->p_leader->p_flag |= P_ADVLOCK; 659 PROC_UNLOCK(p->p_leader); 660 error = VOP_ADVLOCK(vp, (caddr_t)p->p_leader, F_SETLK, 661 flp, flg); 662 break; 663 case F_UNLCK: 664 error = VOP_ADVLOCK(vp, (caddr_t)p->p_leader, F_UNLCK, 665 flp, flg); 666 break; 667 case F_UNLCKSYS: 668 /* 669 * Temporary api for testing remote lock 670 * infrastructure. 671 */ 672 if (flg != F_REMOTE) { 673 error = EINVAL; 674 break; 675 } 676 error = VOP_ADVLOCK(vp, (caddr_t)p->p_leader, 677 F_UNLCKSYS, flp, flg); 678 break; 679 default: 680 error = EINVAL; 681 break; 682 } 683 if (error != 0 || flp->l_type == F_UNLCK || 684 flp->l_type == F_UNLCKSYS) { 685 fdrop(fp, td); 686 break; 687 } 688 689 /* 690 * Check for a race with close. 691 * 692 * The vnode is now advisory locked (or unlocked, but this case 693 * is not really important) as the caller requested. 694 * We had to drop the filedesc lock, so we need to recheck if 695 * the descriptor is still valid, because if it was closed 696 * in the meantime we need to remove advisory lock from the 697 * vnode - close on any descriptor leading to an advisory 698 * locked vnode, removes that lock. 699 * We will return 0 on purpose in that case, as the result of 700 * successful advisory lock might have been externally visible 701 * already. This is fine - effectively we pretend to the caller 702 * that the closing thread was a bit slower and that the 703 * advisory lock succeeded before the close. 704 */ 705 error = fget_unlocked(fdp, fd, &rights, &fp2, NULL); 706 if (error != 0) { 707 fdrop(fp, td); 708 break; 709 } 710 if (fp != fp2) { 711 flp->l_whence = SEEK_SET; 712 flp->l_start = 0; 713 flp->l_len = 0; 714 flp->l_type = F_UNLCK; 715 (void) VOP_ADVLOCK(vp, (caddr_t)p->p_leader, 716 F_UNLCK, flp, F_POSIX); 717 } 718 fdrop(fp, td); 719 fdrop(fp2, td); 720 break; 721 722 case F_GETLK: 723 error = fget_unlocked(fdp, fd, 724 cap_rights_init(&rights, CAP_FLOCK), &fp, NULL); 725 if (error != 0) 726 break; 727 if (fp->f_type != DTYPE_VNODE) { 728 error = EBADF; 729 fdrop(fp, td); 730 break; 731 } 732 flp = (struct flock *)arg; 733 if (flp->l_type != F_RDLCK && flp->l_type != F_WRLCK && 734 flp->l_type != F_UNLCK) { 735 error = EINVAL; 736 fdrop(fp, td); 737 break; 738 } 739 if (flp->l_whence == SEEK_CUR) { 740 foffset = foffset_get(fp); 741 if ((flp->l_start > 0 && 742 foffset > OFF_MAX - flp->l_start) || 743 (flp->l_start < 0 && 744 foffset < OFF_MIN - flp->l_start)) { 745 error = EOVERFLOW; 746 fdrop(fp, td); 747 break; 748 } 749 flp->l_start += foffset; 750 } 751 vp = fp->f_vnode; 752 error = VOP_ADVLOCK(vp, (caddr_t)p->p_leader, F_GETLK, flp, 753 F_POSIX); 754 fdrop(fp, td); 755 break; 756 757 case F_RDAHEAD: 758 arg = arg ? 128 * 1024: 0; 759 /* FALLTHROUGH */ 760 case F_READAHEAD: 761 error = fget_unlocked(fdp, fd, 762 cap_rights_init(&rights), &fp, NULL); 763 if (error != 0) 764 break; 765 if (fp->f_type != DTYPE_VNODE) { 766 fdrop(fp, td); 767 error = EBADF; 768 break; 769 } 770 vp = fp->f_vnode; 771 /* 772 * Exclusive lock synchronizes against f_seqcount reads and 773 * writes in sequential_heuristic(). 774 */ 775 error = vn_lock(vp, LK_EXCLUSIVE); 776 if (error != 0) { 777 fdrop(fp, td); 778 break; 779 } 780 if (arg >= 0) { 781 bsize = fp->f_vnode->v_mount->mnt_stat.f_iosize; 782 fp->f_seqcount = (arg + bsize - 1) / bsize; 783 atomic_set_int(&fp->f_flag, FRDAHEAD); 784 } else { 785 atomic_clear_int(&fp->f_flag, FRDAHEAD); 786 } 787 VOP_UNLOCK(vp, 0); 788 fdrop(fp, td); 789 break; 790 791 default: 792 error = EINVAL; 793 break; 794 } 795 return (error); 796 } 797 798 static int 799 getmaxfd(struct thread *td) 800 { 801 802 return (min((int)lim_cur(td, RLIMIT_NOFILE), maxfilesperproc)); 803 } 804 805 /* 806 * Common code for dup, dup2, fcntl(F_DUPFD) and fcntl(F_DUP2FD). 807 */ 808 int 809 kern_dup(struct thread *td, u_int mode, int flags, int old, int new) 810 { 811 struct filedesc *fdp; 812 struct filedescent *oldfde, *newfde; 813 struct proc *p; 814 struct file *delfp; 815 int error, maxfd; 816 817 p = td->td_proc; 818 fdp = p->p_fd; 819 820 MPASS((flags & ~(FDDUP_FLAG_CLOEXEC)) == 0); 821 MPASS(mode < FDDUP_LASTMODE); 822 823 /* 824 * Verify we have a valid descriptor to dup from and possibly to 825 * dup to. Unlike dup() and dup2(), fcntl()'s F_DUPFD should 826 * return EINVAL when the new descriptor is out of bounds. 827 */ 828 if (old < 0) 829 return (EBADF); 830 if (new < 0) 831 return (mode == FDDUP_FCNTL ? EINVAL : EBADF); 832 maxfd = getmaxfd(td); 833 if (new >= maxfd) 834 return (mode == FDDUP_FCNTL ? EINVAL : EBADF); 835 836 FILEDESC_XLOCK(fdp); 837 if (fget_locked(fdp, old) == NULL) { 838 FILEDESC_XUNLOCK(fdp); 839 return (EBADF); 840 } 841 if ((mode == FDDUP_FIXED || mode == FDDUP_MUSTREPLACE) && old == new) { 842 td->td_retval[0] = new; 843 if (flags & FDDUP_FLAG_CLOEXEC) 844 fdp->fd_ofiles[new].fde_flags |= UF_EXCLOSE; 845 FILEDESC_XUNLOCK(fdp); 846 return (0); 847 } 848 849 /* 850 * If the caller specified a file descriptor, make sure the file 851 * table is large enough to hold it, and grab it. Otherwise, just 852 * allocate a new descriptor the usual way. 853 */ 854 switch (mode) { 855 case FDDUP_NORMAL: 856 case FDDUP_FCNTL: 857 if ((error = fdalloc(td, new, &new)) != 0) { 858 FILEDESC_XUNLOCK(fdp); 859 return (error); 860 } 861 break; 862 case FDDUP_MUSTREPLACE: 863 /* Target file descriptor must exist. */ 864 if (fget_locked(fdp, new) == NULL) { 865 FILEDESC_XUNLOCK(fdp); 866 return (EBADF); 867 } 868 break; 869 case FDDUP_FIXED: 870 if (new >= fdp->fd_nfiles) { 871 /* 872 * The resource limits are here instead of e.g. 873 * fdalloc(), because the file descriptor table may be 874 * shared between processes, so we can't really use 875 * racct_add()/racct_sub(). Instead of counting the 876 * number of actually allocated descriptors, just put 877 * the limit on the size of the file descriptor table. 878 */ 879 #ifdef RACCT 880 if (racct_enable) { 881 PROC_LOCK(p); 882 error = racct_set(p, RACCT_NOFILE, new + 1); 883 PROC_UNLOCK(p); 884 if (error != 0) { 885 FILEDESC_XUNLOCK(fdp); 886 return (EMFILE); 887 } 888 } 889 #endif 890 fdgrowtable_exp(fdp, new + 1); 891 } 892 if (!fdisused(fdp, new)) 893 fdused(fdp, new); 894 break; 895 default: 896 KASSERT(0, ("%s unsupported mode %d", __func__, mode)); 897 } 898 899 KASSERT(old != new, ("new fd is same as old")); 900 901 oldfde = &fdp->fd_ofiles[old]; 902 fhold(oldfde->fde_file); 903 newfde = &fdp->fd_ofiles[new]; 904 delfp = newfde->fde_file; 905 906 /* 907 * Duplicate the source descriptor. 908 */ 909 #ifdef CAPABILITIES 910 seq_write_begin(&newfde->fde_seq); 911 #endif 912 filecaps_free(&newfde->fde_caps); 913 memcpy(newfde, oldfde, fde_change_size); 914 filecaps_copy(&oldfde->fde_caps, &newfde->fde_caps); 915 if ((flags & FDDUP_FLAG_CLOEXEC) != 0) 916 newfde->fde_flags = oldfde->fde_flags | UF_EXCLOSE; 917 else 918 newfde->fde_flags = oldfde->fde_flags & ~UF_EXCLOSE; 919 #ifdef CAPABILITIES 920 seq_write_end(&newfde->fde_seq); 921 #endif 922 td->td_retval[0] = new; 923 924 if (delfp != NULL) { 925 (void) closefp(fdp, new, delfp, td, 1); 926 /* closefp() drops the FILEDESC lock for us. */ 927 } else { 928 FILEDESC_XUNLOCK(fdp); 929 } 930 931 return (0); 932 } 933 934 /* 935 * If sigio is on the list associated with a process or process group, 936 * disable signalling from the device, remove sigio from the list and 937 * free sigio. 938 */ 939 void 940 funsetown(struct sigio **sigiop) 941 { 942 struct sigio *sigio; 943 944 SIGIO_LOCK(); 945 sigio = *sigiop; 946 if (sigio == NULL) { 947 SIGIO_UNLOCK(); 948 return; 949 } 950 *(sigio->sio_myref) = NULL; 951 if ((sigio)->sio_pgid < 0) { 952 struct pgrp *pg = (sigio)->sio_pgrp; 953 PGRP_LOCK(pg); 954 SLIST_REMOVE(&sigio->sio_pgrp->pg_sigiolst, sigio, 955 sigio, sio_pgsigio); 956 PGRP_UNLOCK(pg); 957 } else { 958 struct proc *p = (sigio)->sio_proc; 959 PROC_LOCK(p); 960 SLIST_REMOVE(&sigio->sio_proc->p_sigiolst, sigio, 961 sigio, sio_pgsigio); 962 PROC_UNLOCK(p); 963 } 964 SIGIO_UNLOCK(); 965 crfree(sigio->sio_ucred); 966 free(sigio, M_SIGIO); 967 } 968 969 /* 970 * Free a list of sigio structures. 971 * We only need to lock the SIGIO_LOCK because we have made ourselves 972 * inaccessible to callers of fsetown and therefore do not need to lock 973 * the proc or pgrp struct for the list manipulation. 974 */ 975 void 976 funsetownlst(struct sigiolst *sigiolst) 977 { 978 struct proc *p; 979 struct pgrp *pg; 980 struct sigio *sigio; 981 982 sigio = SLIST_FIRST(sigiolst); 983 if (sigio == NULL) 984 return; 985 p = NULL; 986 pg = NULL; 987 988 /* 989 * Every entry of the list should belong 990 * to a single proc or pgrp. 991 */ 992 if (sigio->sio_pgid < 0) { 993 pg = sigio->sio_pgrp; 994 PGRP_LOCK_ASSERT(pg, MA_NOTOWNED); 995 } else /* if (sigio->sio_pgid > 0) */ { 996 p = sigio->sio_proc; 997 PROC_LOCK_ASSERT(p, MA_NOTOWNED); 998 } 999 1000 SIGIO_LOCK(); 1001 while ((sigio = SLIST_FIRST(sigiolst)) != NULL) { 1002 *(sigio->sio_myref) = NULL; 1003 if (pg != NULL) { 1004 KASSERT(sigio->sio_pgid < 0, 1005 ("Proc sigio in pgrp sigio list")); 1006 KASSERT(sigio->sio_pgrp == pg, 1007 ("Bogus pgrp in sigio list")); 1008 PGRP_LOCK(pg); 1009 SLIST_REMOVE(&pg->pg_sigiolst, sigio, sigio, 1010 sio_pgsigio); 1011 PGRP_UNLOCK(pg); 1012 } else /* if (p != NULL) */ { 1013 KASSERT(sigio->sio_pgid > 0, 1014 ("Pgrp sigio in proc sigio list")); 1015 KASSERT(sigio->sio_proc == p, 1016 ("Bogus proc in sigio list")); 1017 PROC_LOCK(p); 1018 SLIST_REMOVE(&p->p_sigiolst, sigio, sigio, 1019 sio_pgsigio); 1020 PROC_UNLOCK(p); 1021 } 1022 SIGIO_UNLOCK(); 1023 crfree(sigio->sio_ucred); 1024 free(sigio, M_SIGIO); 1025 SIGIO_LOCK(); 1026 } 1027 SIGIO_UNLOCK(); 1028 } 1029 1030 /* 1031 * This is common code for FIOSETOWN ioctl called by fcntl(fd, F_SETOWN, arg). 1032 * 1033 * After permission checking, add a sigio structure to the sigio list for 1034 * the process or process group. 1035 */ 1036 int 1037 fsetown(pid_t pgid, struct sigio **sigiop) 1038 { 1039 struct proc *proc; 1040 struct pgrp *pgrp; 1041 struct sigio *sigio; 1042 int ret; 1043 1044 if (pgid == 0) { 1045 funsetown(sigiop); 1046 return (0); 1047 } 1048 1049 ret = 0; 1050 1051 /* Allocate and fill in the new sigio out of locks. */ 1052 sigio = malloc(sizeof(struct sigio), M_SIGIO, M_WAITOK); 1053 sigio->sio_pgid = pgid; 1054 sigio->sio_ucred = crhold(curthread->td_ucred); 1055 sigio->sio_myref = sigiop; 1056 1057 sx_slock(&proctree_lock); 1058 if (pgid > 0) { 1059 proc = pfind(pgid); 1060 if (proc == NULL) { 1061 ret = ESRCH; 1062 goto fail; 1063 } 1064 1065 /* 1066 * Policy - Don't allow a process to FSETOWN a process 1067 * in another session. 1068 * 1069 * Remove this test to allow maximum flexibility or 1070 * restrict FSETOWN to the current process or process 1071 * group for maximum safety. 1072 */ 1073 PROC_UNLOCK(proc); 1074 if (proc->p_session != curthread->td_proc->p_session) { 1075 ret = EPERM; 1076 goto fail; 1077 } 1078 1079 pgrp = NULL; 1080 } else /* if (pgid < 0) */ { 1081 pgrp = pgfind(-pgid); 1082 if (pgrp == NULL) { 1083 ret = ESRCH; 1084 goto fail; 1085 } 1086 PGRP_UNLOCK(pgrp); 1087 1088 /* 1089 * Policy - Don't allow a process to FSETOWN a process 1090 * in another session. 1091 * 1092 * Remove this test to allow maximum flexibility or 1093 * restrict FSETOWN to the current process or process 1094 * group for maximum safety. 1095 */ 1096 if (pgrp->pg_session != curthread->td_proc->p_session) { 1097 ret = EPERM; 1098 goto fail; 1099 } 1100 1101 proc = NULL; 1102 } 1103 funsetown(sigiop); 1104 if (pgid > 0) { 1105 PROC_LOCK(proc); 1106 /* 1107 * Since funsetownlst() is called without the proctree 1108 * locked, we need to check for P_WEXIT. 1109 * XXX: is ESRCH correct? 1110 */ 1111 if ((proc->p_flag & P_WEXIT) != 0) { 1112 PROC_UNLOCK(proc); 1113 ret = ESRCH; 1114 goto fail; 1115 } 1116 SLIST_INSERT_HEAD(&proc->p_sigiolst, sigio, sio_pgsigio); 1117 sigio->sio_proc = proc; 1118 PROC_UNLOCK(proc); 1119 } else { 1120 PGRP_LOCK(pgrp); 1121 SLIST_INSERT_HEAD(&pgrp->pg_sigiolst, sigio, sio_pgsigio); 1122 sigio->sio_pgrp = pgrp; 1123 PGRP_UNLOCK(pgrp); 1124 } 1125 sx_sunlock(&proctree_lock); 1126 SIGIO_LOCK(); 1127 *sigiop = sigio; 1128 SIGIO_UNLOCK(); 1129 return (0); 1130 1131 fail: 1132 sx_sunlock(&proctree_lock); 1133 crfree(sigio->sio_ucred); 1134 free(sigio, M_SIGIO); 1135 return (ret); 1136 } 1137 1138 /* 1139 * This is common code for FIOGETOWN ioctl called by fcntl(fd, F_GETOWN, arg). 1140 */ 1141 pid_t 1142 fgetown(sigiop) 1143 struct sigio **sigiop; 1144 { 1145 pid_t pgid; 1146 1147 SIGIO_LOCK(); 1148 pgid = (*sigiop != NULL) ? (*sigiop)->sio_pgid : 0; 1149 SIGIO_UNLOCK(); 1150 return (pgid); 1151 } 1152 1153 /* 1154 * Function drops the filedesc lock on return. 1155 */ 1156 static int 1157 closefp(struct filedesc *fdp, int fd, struct file *fp, struct thread *td, 1158 int holdleaders) 1159 { 1160 int error; 1161 1162 FILEDESC_XLOCK_ASSERT(fdp); 1163 1164 if (holdleaders) { 1165 if (td->td_proc->p_fdtol != NULL) { 1166 /* 1167 * Ask fdfree() to sleep to ensure that all relevant 1168 * process leaders can be traversed in closef(). 1169 */ 1170 fdp->fd_holdleaderscount++; 1171 } else { 1172 holdleaders = 0; 1173 } 1174 } 1175 1176 /* 1177 * We now hold the fp reference that used to be owned by the 1178 * descriptor array. We have to unlock the FILEDESC *AFTER* 1179 * knote_fdclose to prevent a race of the fd getting opened, a knote 1180 * added, and deleteing a knote for the new fd. 1181 */ 1182 knote_fdclose(td, fd); 1183 1184 /* 1185 * We need to notify mqueue if the object is of type mqueue. 1186 */ 1187 if (fp->f_type == DTYPE_MQUEUE) 1188 mq_fdclose(td, fd, fp); 1189 FILEDESC_XUNLOCK(fdp); 1190 1191 error = closef(fp, td); 1192 if (holdleaders) { 1193 FILEDESC_XLOCK(fdp); 1194 fdp->fd_holdleaderscount--; 1195 if (fdp->fd_holdleaderscount == 0 && 1196 fdp->fd_holdleaderswakeup != 0) { 1197 fdp->fd_holdleaderswakeup = 0; 1198 wakeup(&fdp->fd_holdleaderscount); 1199 } 1200 FILEDESC_XUNLOCK(fdp); 1201 } 1202 return (error); 1203 } 1204 1205 /* 1206 * Close a file descriptor. 1207 */ 1208 #ifndef _SYS_SYSPROTO_H_ 1209 struct close_args { 1210 int fd; 1211 }; 1212 #endif 1213 /* ARGSUSED */ 1214 int 1215 sys_close(struct thread *td, struct close_args *uap) 1216 { 1217 1218 return (kern_close(td, uap->fd)); 1219 } 1220 1221 int 1222 kern_close(struct thread *td, int fd) 1223 { 1224 struct filedesc *fdp; 1225 struct file *fp; 1226 1227 fdp = td->td_proc->p_fd; 1228 1229 AUDIT_SYSCLOSE(td, fd); 1230 1231 FILEDESC_XLOCK(fdp); 1232 if ((fp = fget_locked(fdp, fd)) == NULL) { 1233 FILEDESC_XUNLOCK(fdp); 1234 return (EBADF); 1235 } 1236 fdfree(fdp, fd); 1237 1238 /* closefp() drops the FILEDESC lock for us. */ 1239 return (closefp(fdp, fd, fp, td, 1)); 1240 } 1241 1242 /* 1243 * Close open file descriptors. 1244 */ 1245 #ifndef _SYS_SYSPROTO_H_ 1246 struct closefrom_args { 1247 int lowfd; 1248 }; 1249 #endif 1250 /* ARGSUSED */ 1251 int 1252 sys_closefrom(struct thread *td, struct closefrom_args *uap) 1253 { 1254 struct filedesc *fdp; 1255 int fd; 1256 1257 fdp = td->td_proc->p_fd; 1258 AUDIT_ARG_FD(uap->lowfd); 1259 1260 /* 1261 * Treat negative starting file descriptor values identical to 1262 * closefrom(0) which closes all files. 1263 */ 1264 if (uap->lowfd < 0) 1265 uap->lowfd = 0; 1266 FILEDESC_SLOCK(fdp); 1267 for (fd = uap->lowfd; fd <= fdp->fd_lastfile; fd++) { 1268 if (fdp->fd_ofiles[fd].fde_file != NULL) { 1269 FILEDESC_SUNLOCK(fdp); 1270 (void)kern_close(td, fd); 1271 FILEDESC_SLOCK(fdp); 1272 } 1273 } 1274 FILEDESC_SUNLOCK(fdp); 1275 return (0); 1276 } 1277 1278 #if defined(COMPAT_43) 1279 /* 1280 * Return status information about a file descriptor. 1281 */ 1282 #ifndef _SYS_SYSPROTO_H_ 1283 struct ofstat_args { 1284 int fd; 1285 struct ostat *sb; 1286 }; 1287 #endif 1288 /* ARGSUSED */ 1289 int 1290 ofstat(struct thread *td, struct ofstat_args *uap) 1291 { 1292 struct ostat oub; 1293 struct stat ub; 1294 int error; 1295 1296 error = kern_fstat(td, uap->fd, &ub); 1297 if (error == 0) { 1298 cvtstat(&ub, &oub); 1299 error = copyout(&oub, uap->sb, sizeof(oub)); 1300 } 1301 return (error); 1302 } 1303 #endif /* COMPAT_43 */ 1304 1305 /* 1306 * Return status information about a file descriptor. 1307 */ 1308 #ifndef _SYS_SYSPROTO_H_ 1309 struct fstat_args { 1310 int fd; 1311 struct stat *sb; 1312 }; 1313 #endif 1314 /* ARGSUSED */ 1315 int 1316 sys_fstat(struct thread *td, struct fstat_args *uap) 1317 { 1318 struct stat ub; 1319 int error; 1320 1321 error = kern_fstat(td, uap->fd, &ub); 1322 if (error == 0) 1323 error = copyout(&ub, uap->sb, sizeof(ub)); 1324 return (error); 1325 } 1326 1327 int 1328 kern_fstat(struct thread *td, int fd, struct stat *sbp) 1329 { 1330 struct file *fp; 1331 cap_rights_t rights; 1332 int error; 1333 1334 AUDIT_ARG_FD(fd); 1335 1336 error = fget(td, fd, cap_rights_init(&rights, CAP_FSTAT), &fp); 1337 if (error != 0) 1338 return (error); 1339 1340 AUDIT_ARG_FILE(td->td_proc, fp); 1341 1342 error = fo_stat(fp, sbp, td->td_ucred, td); 1343 fdrop(fp, td); 1344 #ifdef KTRACE 1345 if (error == 0 && KTRPOINT(td, KTR_STRUCT)) 1346 ktrstat(sbp); 1347 #endif 1348 return (error); 1349 } 1350 1351 /* 1352 * Return status information about a file descriptor. 1353 */ 1354 #ifndef _SYS_SYSPROTO_H_ 1355 struct nfstat_args { 1356 int fd; 1357 struct nstat *sb; 1358 }; 1359 #endif 1360 /* ARGSUSED */ 1361 int 1362 sys_nfstat(struct thread *td, struct nfstat_args *uap) 1363 { 1364 struct nstat nub; 1365 struct stat ub; 1366 int error; 1367 1368 error = kern_fstat(td, uap->fd, &ub); 1369 if (error == 0) { 1370 cvtnstat(&ub, &nub); 1371 error = copyout(&nub, uap->sb, sizeof(nub)); 1372 } 1373 return (error); 1374 } 1375 1376 /* 1377 * Return pathconf information about a file descriptor. 1378 */ 1379 #ifndef _SYS_SYSPROTO_H_ 1380 struct fpathconf_args { 1381 int fd; 1382 int name; 1383 }; 1384 #endif 1385 /* ARGSUSED */ 1386 int 1387 sys_fpathconf(struct thread *td, struct fpathconf_args *uap) 1388 { 1389 struct file *fp; 1390 struct vnode *vp; 1391 cap_rights_t rights; 1392 int error; 1393 1394 error = fget(td, uap->fd, cap_rights_init(&rights, CAP_FPATHCONF), &fp); 1395 if (error != 0) 1396 return (error); 1397 1398 /* If asynchronous I/O is available, it works for all descriptors. */ 1399 if (uap->name == _PC_ASYNC_IO) { 1400 td->td_retval[0] = async_io_version; 1401 goto out; 1402 } 1403 vp = fp->f_vnode; 1404 if (vp != NULL) { 1405 vn_lock(vp, LK_SHARED | LK_RETRY); 1406 error = VOP_PATHCONF(vp, uap->name, td->td_retval); 1407 VOP_UNLOCK(vp, 0); 1408 } else if (fp->f_type == DTYPE_PIPE || fp->f_type == DTYPE_SOCKET) { 1409 if (uap->name != _PC_PIPE_BUF) { 1410 error = EINVAL; 1411 } else { 1412 td->td_retval[0] = PIPE_BUF; 1413 error = 0; 1414 } 1415 } else { 1416 error = EOPNOTSUPP; 1417 } 1418 out: 1419 fdrop(fp, td); 1420 return (error); 1421 } 1422 1423 /* 1424 * Initialize filecaps structure. 1425 */ 1426 void 1427 filecaps_init(struct filecaps *fcaps) 1428 { 1429 1430 bzero(fcaps, sizeof(*fcaps)); 1431 fcaps->fc_nioctls = -1; 1432 } 1433 1434 /* 1435 * Copy filecaps structure allocating memory for ioctls array if needed. 1436 */ 1437 void 1438 filecaps_copy(const struct filecaps *src, struct filecaps *dst) 1439 { 1440 size_t size; 1441 1442 *dst = *src; 1443 if (src->fc_ioctls != NULL) { 1444 KASSERT(src->fc_nioctls > 0, 1445 ("fc_ioctls != NULL, but fc_nioctls=%hd", src->fc_nioctls)); 1446 1447 size = sizeof(src->fc_ioctls[0]) * src->fc_nioctls; 1448 dst->fc_ioctls = malloc(size, M_FILECAPS, M_WAITOK); 1449 bcopy(src->fc_ioctls, dst->fc_ioctls, size); 1450 } 1451 } 1452 1453 /* 1454 * Move filecaps structure to the new place and clear the old place. 1455 */ 1456 void 1457 filecaps_move(struct filecaps *src, struct filecaps *dst) 1458 { 1459 1460 *dst = *src; 1461 bzero(src, sizeof(*src)); 1462 } 1463 1464 /* 1465 * Fill the given filecaps structure with full rights. 1466 */ 1467 static void 1468 filecaps_fill(struct filecaps *fcaps) 1469 { 1470 1471 CAP_ALL(&fcaps->fc_rights); 1472 fcaps->fc_ioctls = NULL; 1473 fcaps->fc_nioctls = -1; 1474 fcaps->fc_fcntls = CAP_FCNTL_ALL; 1475 } 1476 1477 /* 1478 * Free memory allocated within filecaps structure. 1479 */ 1480 void 1481 filecaps_free(struct filecaps *fcaps) 1482 { 1483 1484 free(fcaps->fc_ioctls, M_FILECAPS); 1485 bzero(fcaps, sizeof(*fcaps)); 1486 } 1487 1488 /* 1489 * Validate the given filecaps structure. 1490 */ 1491 static void 1492 filecaps_validate(const struct filecaps *fcaps, const char *func) 1493 { 1494 1495 KASSERT(cap_rights_is_valid(&fcaps->fc_rights), 1496 ("%s: invalid rights", func)); 1497 KASSERT((fcaps->fc_fcntls & ~CAP_FCNTL_ALL) == 0, 1498 ("%s: invalid fcntls", func)); 1499 KASSERT(fcaps->fc_fcntls == 0 || 1500 cap_rights_is_set(&fcaps->fc_rights, CAP_FCNTL), 1501 ("%s: fcntls without CAP_FCNTL", func)); 1502 KASSERT(fcaps->fc_ioctls != NULL ? fcaps->fc_nioctls > 0 : 1503 (fcaps->fc_nioctls == -1 || fcaps->fc_nioctls == 0), 1504 ("%s: invalid ioctls", func)); 1505 KASSERT(fcaps->fc_nioctls == 0 || 1506 cap_rights_is_set(&fcaps->fc_rights, CAP_IOCTL), 1507 ("%s: ioctls without CAP_IOCTL", func)); 1508 } 1509 1510 static void 1511 fdgrowtable_exp(struct filedesc *fdp, int nfd) 1512 { 1513 int nfd1; 1514 1515 FILEDESC_XLOCK_ASSERT(fdp); 1516 1517 nfd1 = fdp->fd_nfiles * 2; 1518 if (nfd1 < nfd) 1519 nfd1 = nfd; 1520 fdgrowtable(fdp, nfd1); 1521 } 1522 1523 /* 1524 * Grow the file table to accomodate (at least) nfd descriptors. 1525 */ 1526 static void 1527 fdgrowtable(struct filedesc *fdp, int nfd) 1528 { 1529 struct filedesc0 *fdp0; 1530 struct freetable *ft; 1531 struct fdescenttbl *ntable; 1532 struct fdescenttbl *otable; 1533 int nnfiles, onfiles; 1534 NDSLOTTYPE *nmap, *omap; 1535 1536 /* 1537 * If lastfile is -1 this struct filedesc was just allocated and we are 1538 * growing it to accomodate for the one we are going to copy from. There 1539 * is no need to have a lock on this one as it's not visible to anyone. 1540 */ 1541 if (fdp->fd_lastfile != -1) 1542 FILEDESC_XLOCK_ASSERT(fdp); 1543 1544 KASSERT(fdp->fd_nfiles > 0, ("zero-length file table")); 1545 1546 /* save old values */ 1547 onfiles = fdp->fd_nfiles; 1548 otable = fdp->fd_files; 1549 omap = fdp->fd_map; 1550 1551 /* compute the size of the new table */ 1552 nnfiles = NDSLOTS(nfd) * NDENTRIES; /* round up */ 1553 if (nnfiles <= onfiles) 1554 /* the table is already large enough */ 1555 return; 1556 1557 /* 1558 * Allocate a new table. We need enough space for the number of 1559 * entries, file entries themselves and the struct freetable we will use 1560 * when we decommission the table and place it on the freelist. 1561 * We place the struct freetable in the middle so we don't have 1562 * to worry about padding. 1563 */ 1564 ntable = malloc(offsetof(struct fdescenttbl, fdt_ofiles) + 1565 nnfiles * sizeof(ntable->fdt_ofiles[0]) + 1566 sizeof(struct freetable), 1567 M_FILEDESC, M_ZERO | M_WAITOK); 1568 /* copy the old data */ 1569 ntable->fdt_nfiles = nnfiles; 1570 memcpy(ntable->fdt_ofiles, otable->fdt_ofiles, 1571 onfiles * sizeof(ntable->fdt_ofiles[0])); 1572 1573 /* 1574 * Allocate a new map only if the old is not large enough. It will 1575 * grow at a slower rate than the table as it can map more 1576 * entries than the table can hold. 1577 */ 1578 if (NDSLOTS(nnfiles) > NDSLOTS(onfiles)) { 1579 nmap = malloc(NDSLOTS(nnfiles) * NDSLOTSIZE, M_FILEDESC, 1580 M_ZERO | M_WAITOK); 1581 /* copy over the old data and update the pointer */ 1582 memcpy(nmap, omap, NDSLOTS(onfiles) * sizeof(*omap)); 1583 fdp->fd_map = nmap; 1584 } 1585 1586 /* 1587 * Make sure that ntable is correctly initialized before we replace 1588 * fd_files poiner. Otherwise fget_unlocked() may see inconsistent 1589 * data. 1590 */ 1591 atomic_store_rel_ptr((volatile void *)&fdp->fd_files, (uintptr_t)ntable); 1592 1593 /* 1594 * Do not free the old file table, as some threads may still 1595 * reference entries within it. Instead, place it on a freelist 1596 * which will be processed when the struct filedesc is released. 1597 * 1598 * Note that if onfiles == NDFILE, we're dealing with the original 1599 * static allocation contained within (struct filedesc0 *)fdp, 1600 * which must not be freed. 1601 */ 1602 if (onfiles > NDFILE) { 1603 ft = (struct freetable *)&otable->fdt_ofiles[onfiles]; 1604 fdp0 = (struct filedesc0 *)fdp; 1605 ft->ft_table = otable; 1606 SLIST_INSERT_HEAD(&fdp0->fd_free, ft, ft_next); 1607 } 1608 /* 1609 * The map does not have the same possibility of threads still 1610 * holding references to it. So always free it as long as it 1611 * does not reference the original static allocation. 1612 */ 1613 if (NDSLOTS(onfiles) > NDSLOTS(NDFILE)) 1614 free(omap, M_FILEDESC); 1615 } 1616 1617 /* 1618 * Allocate a file descriptor for the process. 1619 */ 1620 int 1621 fdalloc(struct thread *td, int minfd, int *result) 1622 { 1623 struct proc *p = td->td_proc; 1624 struct filedesc *fdp = p->p_fd; 1625 int fd, maxfd, allocfd; 1626 #ifdef RACCT 1627 int error; 1628 #endif 1629 1630 FILEDESC_XLOCK_ASSERT(fdp); 1631 1632 if (fdp->fd_freefile > minfd) 1633 minfd = fdp->fd_freefile; 1634 1635 maxfd = getmaxfd(td); 1636 1637 /* 1638 * Search the bitmap for a free descriptor starting at minfd. 1639 * If none is found, grow the file table. 1640 */ 1641 fd = fd_first_free(fdp, minfd, fdp->fd_nfiles); 1642 if (fd >= maxfd) 1643 return (EMFILE); 1644 if (fd >= fdp->fd_nfiles) { 1645 allocfd = min(fd * 2, maxfd); 1646 #ifdef RACCT 1647 if (racct_enable) { 1648 PROC_LOCK(p); 1649 error = racct_set(p, RACCT_NOFILE, allocfd); 1650 PROC_UNLOCK(p); 1651 if (error != 0) 1652 return (EMFILE); 1653 } 1654 #endif 1655 /* 1656 * fd is already equal to first free descriptor >= minfd, so 1657 * we only need to grow the table and we are done. 1658 */ 1659 fdgrowtable_exp(fdp, allocfd); 1660 } 1661 1662 /* 1663 * Perform some sanity checks, then mark the file descriptor as 1664 * used and return it to the caller. 1665 */ 1666 KASSERT(fd >= 0 && fd < min(maxfd, fdp->fd_nfiles), 1667 ("invalid descriptor %d", fd)); 1668 KASSERT(!fdisused(fdp, fd), 1669 ("fd_first_free() returned non-free descriptor")); 1670 KASSERT(fdp->fd_ofiles[fd].fde_file == NULL, 1671 ("file descriptor isn't free")); 1672 fdused(fdp, fd); 1673 *result = fd; 1674 return (0); 1675 } 1676 1677 /* 1678 * Allocate n file descriptors for the process. 1679 */ 1680 int 1681 fdallocn(struct thread *td, int minfd, int *fds, int n) 1682 { 1683 struct proc *p = td->td_proc; 1684 struct filedesc *fdp = p->p_fd; 1685 int i; 1686 1687 FILEDESC_XLOCK_ASSERT(fdp); 1688 1689 for (i = 0; i < n; i++) 1690 if (fdalloc(td, 0, &fds[i]) != 0) 1691 break; 1692 1693 if (i < n) { 1694 for (i--; i >= 0; i--) 1695 fdunused(fdp, fds[i]); 1696 return (EMFILE); 1697 } 1698 1699 return (0); 1700 } 1701 1702 /* 1703 * Create a new open file structure and allocate a file decriptor for the 1704 * process that refers to it. We add one reference to the file for the 1705 * descriptor table and one reference for resultfp. This is to prevent us 1706 * being preempted and the entry in the descriptor table closed after we 1707 * release the FILEDESC lock. 1708 */ 1709 int 1710 falloc(struct thread *td, struct file **resultfp, int *resultfd, int flags) 1711 { 1712 struct file *fp; 1713 int error, fd; 1714 1715 error = falloc_noinstall(td, &fp); 1716 if (error) 1717 return (error); /* no reference held on error */ 1718 1719 error = finstall(td, fp, &fd, flags, NULL); 1720 if (error) { 1721 fdrop(fp, td); /* one reference (fp only) */ 1722 return (error); 1723 } 1724 1725 if (resultfp != NULL) 1726 *resultfp = fp; /* copy out result */ 1727 else 1728 fdrop(fp, td); /* release local reference */ 1729 1730 if (resultfd != NULL) 1731 *resultfd = fd; 1732 1733 return (0); 1734 } 1735 1736 /* 1737 * Create a new open file structure without allocating a file descriptor. 1738 */ 1739 int 1740 falloc_noinstall(struct thread *td, struct file **resultfp) 1741 { 1742 struct file *fp; 1743 int maxuserfiles = maxfiles - (maxfiles / 20); 1744 static struct timeval lastfail; 1745 static int curfail; 1746 1747 KASSERT(resultfp != NULL, ("%s: resultfp == NULL", __func__)); 1748 1749 if ((openfiles >= maxuserfiles && 1750 priv_check(td, PRIV_MAXFILES) != 0) || 1751 openfiles >= maxfiles) { 1752 if (ppsratecheck(&lastfail, &curfail, 1)) { 1753 printf("kern.maxfiles limit exceeded by uid %i, " 1754 "please see tuning(7).\n", td->td_ucred->cr_ruid); 1755 } 1756 return (ENFILE); 1757 } 1758 atomic_add_int(&openfiles, 1); 1759 fp = uma_zalloc(file_zone, M_WAITOK | M_ZERO); 1760 refcount_init(&fp->f_count, 1); 1761 fp->f_cred = crhold(td->td_ucred); 1762 fp->f_ops = &badfileops; 1763 *resultfp = fp; 1764 return (0); 1765 } 1766 1767 /* 1768 * Install a file in a file descriptor table. 1769 */ 1770 void 1771 _finstall(struct filedesc *fdp, struct file *fp, int fd, int flags, 1772 struct filecaps *fcaps) 1773 { 1774 struct filedescent *fde; 1775 1776 MPASS(fp != NULL); 1777 if (fcaps != NULL) 1778 filecaps_validate(fcaps, __func__); 1779 FILEDESC_XLOCK_ASSERT(fdp); 1780 1781 fde = &fdp->fd_ofiles[fd]; 1782 #ifdef CAPABILITIES 1783 seq_write_begin(&fde->fde_seq); 1784 #endif 1785 fde->fde_file = fp; 1786 fde->fde_flags = (flags & O_CLOEXEC) != 0 ? UF_EXCLOSE : 0; 1787 if (fcaps != NULL) 1788 filecaps_move(fcaps, &fde->fde_caps); 1789 else 1790 filecaps_fill(&fde->fde_caps); 1791 #ifdef CAPABILITIES 1792 seq_write_end(&fde->fde_seq); 1793 #endif 1794 } 1795 1796 int 1797 finstall(struct thread *td, struct file *fp, int *fd, int flags, 1798 struct filecaps *fcaps) 1799 { 1800 struct filedesc *fdp = td->td_proc->p_fd; 1801 int error; 1802 1803 MPASS(fd != NULL); 1804 1805 FILEDESC_XLOCK(fdp); 1806 if ((error = fdalloc(td, 0, fd))) { 1807 FILEDESC_XUNLOCK(fdp); 1808 return (error); 1809 } 1810 fhold(fp); 1811 _finstall(fdp, fp, *fd, flags, fcaps); 1812 FILEDESC_XUNLOCK(fdp); 1813 return (0); 1814 } 1815 1816 /* 1817 * Build a new filedesc structure from another. 1818 * Copy the current, root, and jail root vnode references. 1819 * 1820 * If fdp is not NULL, return with it shared locked. 1821 */ 1822 struct filedesc * 1823 fdinit(struct filedesc *fdp, bool prepfiles) 1824 { 1825 struct filedesc0 *newfdp0; 1826 struct filedesc *newfdp; 1827 1828 newfdp0 = uma_zalloc(filedesc0_zone, M_WAITOK | M_ZERO); 1829 newfdp = &newfdp0->fd_fd; 1830 1831 /* Create the file descriptor table. */ 1832 FILEDESC_LOCK_INIT(newfdp); 1833 refcount_init(&newfdp->fd_refcnt, 1); 1834 refcount_init(&newfdp->fd_holdcnt, 1); 1835 newfdp->fd_cmask = CMASK; 1836 newfdp->fd_map = newfdp0->fd_dmap; 1837 newfdp->fd_lastfile = -1; 1838 newfdp->fd_files = (struct fdescenttbl *)&newfdp0->fd_dfiles; 1839 newfdp->fd_files->fdt_nfiles = NDFILE; 1840 1841 if (fdp == NULL) 1842 return (newfdp); 1843 1844 if (prepfiles && fdp->fd_lastfile >= newfdp->fd_nfiles) 1845 fdgrowtable(newfdp, fdp->fd_lastfile + 1); 1846 1847 FILEDESC_SLOCK(fdp); 1848 newfdp->fd_cdir = fdp->fd_cdir; 1849 if (newfdp->fd_cdir) 1850 VREF(newfdp->fd_cdir); 1851 newfdp->fd_rdir = fdp->fd_rdir; 1852 if (newfdp->fd_rdir) 1853 VREF(newfdp->fd_rdir); 1854 newfdp->fd_jdir = fdp->fd_jdir; 1855 if (newfdp->fd_jdir) 1856 VREF(newfdp->fd_jdir); 1857 1858 if (!prepfiles) { 1859 FILEDESC_SUNLOCK(fdp); 1860 } else { 1861 while (fdp->fd_lastfile >= newfdp->fd_nfiles) { 1862 FILEDESC_SUNLOCK(fdp); 1863 fdgrowtable(newfdp, fdp->fd_lastfile + 1); 1864 FILEDESC_SLOCK(fdp); 1865 } 1866 } 1867 1868 return (newfdp); 1869 } 1870 1871 static struct filedesc * 1872 fdhold(struct proc *p) 1873 { 1874 struct filedesc *fdp; 1875 1876 PROC_LOCK_ASSERT(p, MA_OWNED); 1877 fdp = p->p_fd; 1878 if (fdp != NULL) 1879 refcount_acquire(&fdp->fd_holdcnt); 1880 return (fdp); 1881 } 1882 1883 static void 1884 fddrop(struct filedesc *fdp) 1885 { 1886 1887 if (fdp->fd_holdcnt > 1) { 1888 if (refcount_release(&fdp->fd_holdcnt) == 0) 1889 return; 1890 } 1891 1892 FILEDESC_LOCK_DESTROY(fdp); 1893 uma_zfree(filedesc0_zone, fdp); 1894 } 1895 1896 /* 1897 * Share a filedesc structure. 1898 */ 1899 struct filedesc * 1900 fdshare(struct filedesc *fdp) 1901 { 1902 1903 refcount_acquire(&fdp->fd_refcnt); 1904 return (fdp); 1905 } 1906 1907 /* 1908 * Unshare a filedesc structure, if necessary by making a copy 1909 */ 1910 void 1911 fdunshare(struct thread *td) 1912 { 1913 struct filedesc *tmp; 1914 struct proc *p = td->td_proc; 1915 1916 if (p->p_fd->fd_refcnt == 1) 1917 return; 1918 1919 tmp = fdcopy(p->p_fd); 1920 fdescfree(td); 1921 p->p_fd = tmp; 1922 } 1923 1924 void 1925 fdinstall_remapped(struct thread *td, struct filedesc *fdp) 1926 { 1927 1928 fdescfree(td); 1929 td->td_proc->p_fd = fdp; 1930 } 1931 1932 /* 1933 * Copy a filedesc structure. A NULL pointer in returns a NULL reference, 1934 * this is to ease callers, not catch errors. 1935 */ 1936 struct filedesc * 1937 fdcopy(struct filedesc *fdp) 1938 { 1939 struct filedesc *newfdp; 1940 struct filedescent *nfde, *ofde; 1941 int i; 1942 1943 MPASS(fdp != NULL); 1944 1945 newfdp = fdinit(fdp, true); 1946 /* copy all passable descriptors (i.e. not kqueue) */ 1947 newfdp->fd_freefile = -1; 1948 for (i = 0; i <= fdp->fd_lastfile; ++i) { 1949 ofde = &fdp->fd_ofiles[i]; 1950 if (ofde->fde_file == NULL || 1951 (ofde->fde_file->f_ops->fo_flags & DFLAG_PASSABLE) == 0) { 1952 if (newfdp->fd_freefile == -1) 1953 newfdp->fd_freefile = i; 1954 continue; 1955 } 1956 nfde = &newfdp->fd_ofiles[i]; 1957 *nfde = *ofde; 1958 filecaps_copy(&ofde->fde_caps, &nfde->fde_caps); 1959 fhold(nfde->fde_file); 1960 fdused_init(newfdp, i); 1961 newfdp->fd_lastfile = i; 1962 } 1963 if (newfdp->fd_freefile == -1) 1964 newfdp->fd_freefile = i; 1965 newfdp->fd_cmask = fdp->fd_cmask; 1966 FILEDESC_SUNLOCK(fdp); 1967 return (newfdp); 1968 } 1969 1970 /* 1971 * Copies a filedesc structure, while remapping all file descriptors 1972 * stored inside using a translation table. 1973 * 1974 * File descriptors are copied over to the new file descriptor table, 1975 * regardless of whether the close-on-exec flag is set. 1976 */ 1977 int 1978 fdcopy_remapped(struct filedesc *fdp, const int *fds, size_t nfds, 1979 struct filedesc **ret) 1980 { 1981 struct filedesc *newfdp; 1982 struct filedescent *nfde, *ofde; 1983 int error, i; 1984 1985 MPASS(fdp != NULL); 1986 1987 newfdp = fdinit(fdp, true); 1988 if (nfds > fdp->fd_lastfile + 1) { 1989 /* New table cannot be larger than the old one. */ 1990 error = E2BIG; 1991 goto bad; 1992 } 1993 /* Copy all passable descriptors (i.e. not kqueue). */ 1994 newfdp->fd_freefile = nfds; 1995 for (i = 0; i < nfds; ++i) { 1996 if (fds[i] < 0 || fds[i] > fdp->fd_lastfile) { 1997 /* File descriptor out of bounds. */ 1998 error = EBADF; 1999 goto bad; 2000 } 2001 ofde = &fdp->fd_ofiles[fds[i]]; 2002 if (ofde->fde_file == NULL) { 2003 /* Unused file descriptor. */ 2004 error = EBADF; 2005 goto bad; 2006 } 2007 if ((ofde->fde_file->f_ops->fo_flags & DFLAG_PASSABLE) == 0) { 2008 /* File descriptor cannot be passed. */ 2009 error = EINVAL; 2010 goto bad; 2011 } 2012 nfde = &newfdp->fd_ofiles[i]; 2013 *nfde = *ofde; 2014 filecaps_copy(&ofde->fde_caps, &nfde->fde_caps); 2015 fhold(nfde->fde_file); 2016 fdused_init(newfdp, i); 2017 newfdp->fd_lastfile = i; 2018 } 2019 newfdp->fd_cmask = fdp->fd_cmask; 2020 FILEDESC_SUNLOCK(fdp); 2021 *ret = newfdp; 2022 return (0); 2023 bad: 2024 FILEDESC_SUNLOCK(fdp); 2025 fdescfree_remapped(newfdp); 2026 return (error); 2027 } 2028 2029 /* 2030 * Clear POSIX style locks. This is only used when fdp looses a reference (i.e. 2031 * one of processes using it exits) and the table used to be shared. 2032 */ 2033 static void 2034 fdclearlocks(struct thread *td) 2035 { 2036 struct filedesc *fdp; 2037 struct filedesc_to_leader *fdtol; 2038 struct flock lf; 2039 struct file *fp; 2040 struct proc *p; 2041 struct vnode *vp; 2042 int i; 2043 2044 p = td->td_proc; 2045 fdp = p->p_fd; 2046 fdtol = p->p_fdtol; 2047 MPASS(fdtol != NULL); 2048 2049 FILEDESC_XLOCK(fdp); 2050 KASSERT(fdtol->fdl_refcount > 0, 2051 ("filedesc_to_refcount botch: fdl_refcount=%d", 2052 fdtol->fdl_refcount)); 2053 if (fdtol->fdl_refcount == 1 && 2054 (p->p_leader->p_flag & P_ADVLOCK) != 0) { 2055 for (i = 0; i <= fdp->fd_lastfile; i++) { 2056 fp = fdp->fd_ofiles[i].fde_file; 2057 if (fp == NULL || fp->f_type != DTYPE_VNODE) 2058 continue; 2059 fhold(fp); 2060 FILEDESC_XUNLOCK(fdp); 2061 lf.l_whence = SEEK_SET; 2062 lf.l_start = 0; 2063 lf.l_len = 0; 2064 lf.l_type = F_UNLCK; 2065 vp = fp->f_vnode; 2066 (void) VOP_ADVLOCK(vp, 2067 (caddr_t)p->p_leader, F_UNLCK, 2068 &lf, F_POSIX); 2069 FILEDESC_XLOCK(fdp); 2070 fdrop(fp, td); 2071 } 2072 } 2073 retry: 2074 if (fdtol->fdl_refcount == 1) { 2075 if (fdp->fd_holdleaderscount > 0 && 2076 (p->p_leader->p_flag & P_ADVLOCK) != 0) { 2077 /* 2078 * close() or kern_dup() has cleared a reference 2079 * in a shared file descriptor table. 2080 */ 2081 fdp->fd_holdleaderswakeup = 1; 2082 sx_sleep(&fdp->fd_holdleaderscount, 2083 FILEDESC_LOCK(fdp), PLOCK, "fdlhold", 0); 2084 goto retry; 2085 } 2086 if (fdtol->fdl_holdcount > 0) { 2087 /* 2088 * Ensure that fdtol->fdl_leader remains 2089 * valid in closef(). 2090 */ 2091 fdtol->fdl_wakeup = 1; 2092 sx_sleep(fdtol, FILEDESC_LOCK(fdp), PLOCK, 2093 "fdlhold", 0); 2094 goto retry; 2095 } 2096 } 2097 fdtol->fdl_refcount--; 2098 if (fdtol->fdl_refcount == 0 && 2099 fdtol->fdl_holdcount == 0) { 2100 fdtol->fdl_next->fdl_prev = fdtol->fdl_prev; 2101 fdtol->fdl_prev->fdl_next = fdtol->fdl_next; 2102 } else 2103 fdtol = NULL; 2104 p->p_fdtol = NULL; 2105 FILEDESC_XUNLOCK(fdp); 2106 if (fdtol != NULL) 2107 free(fdtol, M_FILEDESC_TO_LEADER); 2108 } 2109 2110 /* 2111 * Release a filedesc structure. 2112 */ 2113 static void 2114 fdescfree_fds(struct thread *td, struct filedesc *fdp, bool needclose) 2115 { 2116 struct filedesc0 *fdp0; 2117 struct freetable *ft, *tft; 2118 struct filedescent *fde; 2119 struct file *fp; 2120 int i; 2121 2122 for (i = 0; i <= fdp->fd_lastfile; i++) { 2123 fde = &fdp->fd_ofiles[i]; 2124 fp = fde->fde_file; 2125 if (fp != NULL) { 2126 fdefree_last(fde); 2127 if (needclose) 2128 (void) closef(fp, td); 2129 else 2130 fdrop(fp, td); 2131 } 2132 } 2133 2134 if (NDSLOTS(fdp->fd_nfiles) > NDSLOTS(NDFILE)) 2135 free(fdp->fd_map, M_FILEDESC); 2136 if (fdp->fd_nfiles > NDFILE) 2137 free(fdp->fd_files, M_FILEDESC); 2138 2139 fdp0 = (struct filedesc0 *)fdp; 2140 SLIST_FOREACH_SAFE(ft, &fdp0->fd_free, ft_next, tft) 2141 free(ft->ft_table, M_FILEDESC); 2142 2143 fddrop(fdp); 2144 } 2145 2146 void 2147 fdescfree(struct thread *td) 2148 { 2149 struct proc *p; 2150 struct filedesc *fdp; 2151 struct vnode *cdir, *jdir, *rdir; 2152 2153 p = td->td_proc; 2154 fdp = p->p_fd; 2155 MPASS(fdp != NULL); 2156 2157 #ifdef RACCT 2158 if (racct_enable) { 2159 PROC_LOCK(p); 2160 racct_set(p, RACCT_NOFILE, 0); 2161 PROC_UNLOCK(p); 2162 } 2163 #endif 2164 2165 if (p->p_fdtol != NULL) 2166 fdclearlocks(td); 2167 2168 PROC_LOCK(p); 2169 p->p_fd = NULL; 2170 PROC_UNLOCK(p); 2171 2172 if (refcount_release(&fdp->fd_refcnt) == 0) 2173 return; 2174 2175 FILEDESC_XLOCK(fdp); 2176 cdir = fdp->fd_cdir; 2177 fdp->fd_cdir = NULL; 2178 rdir = fdp->fd_rdir; 2179 fdp->fd_rdir = NULL; 2180 jdir = fdp->fd_jdir; 2181 fdp->fd_jdir = NULL; 2182 FILEDESC_XUNLOCK(fdp); 2183 2184 if (cdir != NULL) 2185 vrele(cdir); 2186 if (rdir != NULL) 2187 vrele(rdir); 2188 if (jdir != NULL) 2189 vrele(jdir); 2190 2191 fdescfree_fds(td, fdp, 1); 2192 } 2193 2194 void 2195 fdescfree_remapped(struct filedesc *fdp) 2196 { 2197 2198 if (fdp->fd_cdir != NULL) 2199 vrele(fdp->fd_cdir); 2200 if (fdp->fd_rdir != NULL) 2201 vrele(fdp->fd_rdir); 2202 if (fdp->fd_jdir != NULL) 2203 vrele(fdp->fd_jdir); 2204 2205 fdescfree_fds(curthread, fdp, 0); 2206 } 2207 2208 /* 2209 * For setugid programs, we don't want to people to use that setugidness 2210 * to generate error messages which write to a file which otherwise would 2211 * otherwise be off-limits to the process. We check for filesystems where 2212 * the vnode can change out from under us after execve (like [lin]procfs). 2213 * 2214 * Since fdsetugidsafety calls this only for fd 0, 1 and 2, this check is 2215 * sufficient. We also don't check for setugidness since we know we are. 2216 */ 2217 static bool 2218 is_unsafe(struct file *fp) 2219 { 2220 struct vnode *vp; 2221 2222 if (fp->f_type != DTYPE_VNODE) 2223 return (false); 2224 2225 vp = fp->f_vnode; 2226 return ((vp->v_vflag & VV_PROCDEP) != 0); 2227 } 2228 2229 /* 2230 * Make this setguid thing safe, if at all possible. 2231 */ 2232 void 2233 fdsetugidsafety(struct thread *td) 2234 { 2235 struct filedesc *fdp; 2236 struct file *fp; 2237 int i; 2238 2239 fdp = td->td_proc->p_fd; 2240 KASSERT(fdp->fd_refcnt == 1, ("the fdtable should not be shared")); 2241 MPASS(fdp->fd_nfiles >= 3); 2242 for (i = 0; i <= 2; i++) { 2243 fp = fdp->fd_ofiles[i].fde_file; 2244 if (fp != NULL && is_unsafe(fp)) { 2245 FILEDESC_XLOCK(fdp); 2246 knote_fdclose(td, i); 2247 /* 2248 * NULL-out descriptor prior to close to avoid 2249 * a race while close blocks. 2250 */ 2251 fdfree(fdp, i); 2252 FILEDESC_XUNLOCK(fdp); 2253 (void) closef(fp, td); 2254 } 2255 } 2256 } 2257 2258 /* 2259 * If a specific file object occupies a specific file descriptor, close the 2260 * file descriptor entry and drop a reference on the file object. This is a 2261 * convenience function to handle a subsequent error in a function that calls 2262 * falloc() that handles the race that another thread might have closed the 2263 * file descriptor out from under the thread creating the file object. 2264 */ 2265 void 2266 fdclose(struct thread *td, struct file *fp, int idx) 2267 { 2268 struct filedesc *fdp = td->td_proc->p_fd; 2269 2270 FILEDESC_XLOCK(fdp); 2271 if (fdp->fd_ofiles[idx].fde_file == fp) { 2272 fdfree(fdp, idx); 2273 FILEDESC_XUNLOCK(fdp); 2274 fdrop(fp, td); 2275 } else 2276 FILEDESC_XUNLOCK(fdp); 2277 } 2278 2279 /* 2280 * Close any files on exec? 2281 */ 2282 void 2283 fdcloseexec(struct thread *td) 2284 { 2285 struct filedesc *fdp; 2286 struct filedescent *fde; 2287 struct file *fp; 2288 int i; 2289 2290 fdp = td->td_proc->p_fd; 2291 KASSERT(fdp->fd_refcnt == 1, ("the fdtable should not be shared")); 2292 for (i = 0; i <= fdp->fd_lastfile; i++) { 2293 fde = &fdp->fd_ofiles[i]; 2294 fp = fde->fde_file; 2295 if (fp != NULL && (fp->f_type == DTYPE_MQUEUE || 2296 (fde->fde_flags & UF_EXCLOSE))) { 2297 FILEDESC_XLOCK(fdp); 2298 fdfree(fdp, i); 2299 (void) closefp(fdp, i, fp, td, 0); 2300 /* closefp() drops the FILEDESC lock. */ 2301 } 2302 } 2303 } 2304 2305 /* 2306 * It is unsafe for set[ug]id processes to be started with file 2307 * descriptors 0..2 closed, as these descriptors are given implicit 2308 * significance in the Standard C library. fdcheckstd() will create a 2309 * descriptor referencing /dev/null for each of stdin, stdout, and 2310 * stderr that is not already open. 2311 */ 2312 int 2313 fdcheckstd(struct thread *td) 2314 { 2315 struct filedesc *fdp; 2316 register_t save; 2317 int i, error, devnull; 2318 2319 fdp = td->td_proc->p_fd; 2320 KASSERT(fdp->fd_refcnt == 1, ("the fdtable should not be shared")); 2321 MPASS(fdp->fd_nfiles >= 3); 2322 devnull = -1; 2323 for (i = 0; i <= 2; i++) { 2324 if (fdp->fd_ofiles[i].fde_file != NULL) 2325 continue; 2326 2327 save = td->td_retval[0]; 2328 if (devnull != -1) { 2329 error = kern_dup(td, FDDUP_FIXED, 0, devnull, i); 2330 } else { 2331 error = kern_openat(td, AT_FDCWD, "/dev/null", 2332 UIO_SYSSPACE, O_RDWR, 0); 2333 if (error == 0) { 2334 devnull = td->td_retval[0]; 2335 KASSERT(devnull == i, ("we didn't get our fd")); 2336 } 2337 } 2338 td->td_retval[0] = save; 2339 if (error != 0) 2340 return (error); 2341 } 2342 return (0); 2343 } 2344 2345 /* 2346 * Internal form of close. Decrement reference count on file structure. 2347 * Note: td may be NULL when closing a file that was being passed in a 2348 * message. 2349 * 2350 * XXXRW: Giant is not required for the caller, but often will be held; this 2351 * makes it moderately likely the Giant will be recursed in the VFS case. 2352 */ 2353 int 2354 closef(struct file *fp, struct thread *td) 2355 { 2356 struct vnode *vp; 2357 struct flock lf; 2358 struct filedesc_to_leader *fdtol; 2359 struct filedesc *fdp; 2360 2361 /* 2362 * POSIX record locking dictates that any close releases ALL 2363 * locks owned by this process. This is handled by setting 2364 * a flag in the unlock to free ONLY locks obeying POSIX 2365 * semantics, and not to free BSD-style file locks. 2366 * If the descriptor was in a message, POSIX-style locks 2367 * aren't passed with the descriptor, and the thread pointer 2368 * will be NULL. Callers should be careful only to pass a 2369 * NULL thread pointer when there really is no owning 2370 * context that might have locks, or the locks will be 2371 * leaked. 2372 */ 2373 if (fp->f_type == DTYPE_VNODE && td != NULL) { 2374 vp = fp->f_vnode; 2375 if ((td->td_proc->p_leader->p_flag & P_ADVLOCK) != 0) { 2376 lf.l_whence = SEEK_SET; 2377 lf.l_start = 0; 2378 lf.l_len = 0; 2379 lf.l_type = F_UNLCK; 2380 (void) VOP_ADVLOCK(vp, (caddr_t)td->td_proc->p_leader, 2381 F_UNLCK, &lf, F_POSIX); 2382 } 2383 fdtol = td->td_proc->p_fdtol; 2384 if (fdtol != NULL) { 2385 /* 2386 * Handle special case where file descriptor table is 2387 * shared between multiple process leaders. 2388 */ 2389 fdp = td->td_proc->p_fd; 2390 FILEDESC_XLOCK(fdp); 2391 for (fdtol = fdtol->fdl_next; 2392 fdtol != td->td_proc->p_fdtol; 2393 fdtol = fdtol->fdl_next) { 2394 if ((fdtol->fdl_leader->p_flag & 2395 P_ADVLOCK) == 0) 2396 continue; 2397 fdtol->fdl_holdcount++; 2398 FILEDESC_XUNLOCK(fdp); 2399 lf.l_whence = SEEK_SET; 2400 lf.l_start = 0; 2401 lf.l_len = 0; 2402 lf.l_type = F_UNLCK; 2403 vp = fp->f_vnode; 2404 (void) VOP_ADVLOCK(vp, 2405 (caddr_t)fdtol->fdl_leader, F_UNLCK, &lf, 2406 F_POSIX); 2407 FILEDESC_XLOCK(fdp); 2408 fdtol->fdl_holdcount--; 2409 if (fdtol->fdl_holdcount == 0 && 2410 fdtol->fdl_wakeup != 0) { 2411 fdtol->fdl_wakeup = 0; 2412 wakeup(fdtol); 2413 } 2414 } 2415 FILEDESC_XUNLOCK(fdp); 2416 } 2417 } 2418 return (fdrop(fp, td)); 2419 } 2420 2421 /* 2422 * Initialize the file pointer with the specified properties. 2423 * 2424 * The ops are set with release semantics to be certain that the flags, type, 2425 * and data are visible when ops is. This is to prevent ops methods from being 2426 * called with bad data. 2427 */ 2428 void 2429 finit(struct file *fp, u_int flag, short type, void *data, struct fileops *ops) 2430 { 2431 fp->f_data = data; 2432 fp->f_flag = flag; 2433 fp->f_type = type; 2434 atomic_store_rel_ptr((volatile uintptr_t *)&fp->f_ops, (uintptr_t)ops); 2435 } 2436 2437 int 2438 fget_unlocked(struct filedesc *fdp, int fd, cap_rights_t *needrightsp, 2439 struct file **fpp, seq_t *seqp) 2440 { 2441 #ifdef CAPABILITIES 2442 struct filedescent *fde; 2443 #endif 2444 struct fdescenttbl *fdt; 2445 struct file *fp; 2446 u_int count; 2447 #ifdef CAPABILITIES 2448 seq_t seq; 2449 cap_rights_t haverights; 2450 int error; 2451 #endif 2452 2453 fdt = fdp->fd_files; 2454 if ((u_int)fd >= fdt->fdt_nfiles) 2455 return (EBADF); 2456 /* 2457 * Fetch the descriptor locklessly. We avoid fdrop() races by 2458 * never raising a refcount above 0. To accomplish this we have 2459 * to use a cmpset loop rather than an atomic_add. The descriptor 2460 * must be re-verified once we acquire a reference to be certain 2461 * that the identity is still correct and we did not lose a race 2462 * due to preemption. 2463 */ 2464 for (;;) { 2465 #ifdef CAPABILITIES 2466 seq = seq_read(fd_seq(fdt, fd)); 2467 fde = &fdt->fdt_ofiles[fd]; 2468 haverights = *cap_rights_fde(fde); 2469 fp = fde->fde_file; 2470 if (!seq_consistent(fd_seq(fdt, fd), seq)) { 2471 cpu_spinwait(); 2472 continue; 2473 } 2474 #else 2475 fp = fdt->fdt_ofiles[fd].fde_file; 2476 #endif 2477 if (fp == NULL) 2478 return (EBADF); 2479 #ifdef CAPABILITIES 2480 error = cap_check(&haverights, needrightsp); 2481 if (error != 0) 2482 return (error); 2483 #endif 2484 retry: 2485 count = fp->f_count; 2486 if (count == 0) { 2487 /* 2488 * Force a reload. Other thread could reallocate the 2489 * table before this fd was closed, so it possible that 2490 * there is a stale fp pointer in cached version. 2491 */ 2492 fdt = *(struct fdescenttbl * volatile *)&(fdp->fd_files); 2493 continue; 2494 } 2495 /* 2496 * Use an acquire barrier to force re-reading of fdt so it is 2497 * refreshed for verification. 2498 */ 2499 if (atomic_cmpset_acq_int(&fp->f_count, count, count + 1) == 0) 2500 goto retry; 2501 fdt = fdp->fd_files; 2502 #ifdef CAPABILITIES 2503 if (seq_consistent_nomb(fd_seq(fdt, fd), seq)) 2504 #else 2505 if (fp == fdt->fdt_ofiles[fd].fde_file) 2506 #endif 2507 break; 2508 fdrop(fp, curthread); 2509 } 2510 *fpp = fp; 2511 if (seqp != NULL) { 2512 #ifdef CAPABILITIES 2513 *seqp = seq; 2514 #endif 2515 } 2516 return (0); 2517 } 2518 2519 /* 2520 * Extract the file pointer associated with the specified descriptor for the 2521 * current user process. 2522 * 2523 * If the descriptor doesn't exist or doesn't match 'flags', EBADF is 2524 * returned. 2525 * 2526 * File's rights will be checked against the capability rights mask. 2527 * 2528 * If an error occured the non-zero error is returned and *fpp is set to 2529 * NULL. Otherwise *fpp is held and set and zero is returned. Caller is 2530 * responsible for fdrop(). 2531 */ 2532 static __inline int 2533 _fget(struct thread *td, int fd, struct file **fpp, int flags, 2534 cap_rights_t *needrightsp, seq_t *seqp) 2535 { 2536 struct filedesc *fdp; 2537 struct file *fp; 2538 int error; 2539 2540 *fpp = NULL; 2541 fdp = td->td_proc->p_fd; 2542 error = fget_unlocked(fdp, fd, needrightsp, &fp, seqp); 2543 if (error != 0) 2544 return (error); 2545 if (fp->f_ops == &badfileops) { 2546 fdrop(fp, td); 2547 return (EBADF); 2548 } 2549 2550 /* 2551 * FREAD and FWRITE failure return EBADF as per POSIX. 2552 */ 2553 error = 0; 2554 switch (flags) { 2555 case FREAD: 2556 case FWRITE: 2557 if ((fp->f_flag & flags) == 0) 2558 error = EBADF; 2559 break; 2560 case FEXEC: 2561 if ((fp->f_flag & (FREAD | FEXEC)) == 0 || 2562 ((fp->f_flag & FWRITE) != 0)) 2563 error = EBADF; 2564 break; 2565 case 0: 2566 break; 2567 default: 2568 KASSERT(0, ("wrong flags")); 2569 } 2570 2571 if (error != 0) { 2572 fdrop(fp, td); 2573 return (error); 2574 } 2575 2576 *fpp = fp; 2577 return (0); 2578 } 2579 2580 int 2581 fget(struct thread *td, int fd, cap_rights_t *rightsp, struct file **fpp) 2582 { 2583 2584 return (_fget(td, fd, fpp, 0, rightsp, NULL)); 2585 } 2586 2587 int 2588 fget_mmap(struct thread *td, int fd, cap_rights_t *rightsp, u_char *maxprotp, 2589 struct file **fpp) 2590 { 2591 int error; 2592 #ifndef CAPABILITIES 2593 error = _fget(td, fd, fpp, 0, rightsp, NULL); 2594 if (maxprotp != NULL) 2595 *maxprotp = VM_PROT_ALL; 2596 #else 2597 struct filedesc *fdp = td->td_proc->p_fd; 2598 seq_t seq; 2599 2600 MPASS(cap_rights_is_set(rightsp, CAP_MMAP)); 2601 for (;;) { 2602 error = _fget(td, fd, fpp, 0, rightsp, &seq); 2603 if (error != 0) 2604 return (error); 2605 /* 2606 * If requested, convert capability rights to access flags. 2607 */ 2608 if (maxprotp != NULL) 2609 *maxprotp = cap_rights_to_vmprot(cap_rights(fdp, fd)); 2610 if (!fd_modified(fdp, fd, seq)) 2611 break; 2612 fdrop(*fpp, td); 2613 } 2614 #endif 2615 return (error); 2616 } 2617 2618 int 2619 fget_read(struct thread *td, int fd, cap_rights_t *rightsp, struct file **fpp) 2620 { 2621 2622 return (_fget(td, fd, fpp, FREAD, rightsp, NULL)); 2623 } 2624 2625 int 2626 fget_write(struct thread *td, int fd, cap_rights_t *rightsp, struct file **fpp) 2627 { 2628 2629 return (_fget(td, fd, fpp, FWRITE, rightsp, NULL)); 2630 } 2631 2632 int 2633 fget_fcntl(struct thread *td, int fd, cap_rights_t *rightsp, int needfcntl, 2634 struct file **fpp) 2635 { 2636 struct filedesc *fdp = td->td_proc->p_fd; 2637 #ifndef CAPABILITIES 2638 return (fget_unlocked(fdp, fd, rightsp, fpp, NULL)); 2639 #else 2640 int error; 2641 seq_t seq; 2642 2643 MPASS(cap_rights_is_set(rightsp, CAP_FCNTL)); 2644 for (;;) { 2645 error = fget_unlocked(fdp, fd, rightsp, fpp, &seq); 2646 if (error != 0) 2647 return (error); 2648 error = cap_fcntl_check(fdp, fd, needfcntl); 2649 if (!fd_modified(fdp, fd, seq)) 2650 break; 2651 fdrop(*fpp, td); 2652 } 2653 if (error != 0) { 2654 fdrop(*fpp, td); 2655 *fpp = NULL; 2656 } 2657 return (error); 2658 #endif 2659 } 2660 2661 /* 2662 * Like fget() but loads the underlying vnode, or returns an error if the 2663 * descriptor does not represent a vnode. Note that pipes use vnodes but 2664 * never have VM objects. The returned vnode will be vref()'d. 2665 * 2666 * XXX: what about the unused flags ? 2667 */ 2668 static __inline int 2669 _fgetvp(struct thread *td, int fd, int flags, cap_rights_t *needrightsp, 2670 struct vnode **vpp) 2671 { 2672 struct file *fp; 2673 int error; 2674 2675 *vpp = NULL; 2676 error = _fget(td, fd, &fp, flags, needrightsp, NULL); 2677 if (error != 0) 2678 return (error); 2679 if (fp->f_vnode == NULL) { 2680 error = EINVAL; 2681 } else { 2682 *vpp = fp->f_vnode; 2683 vref(*vpp); 2684 } 2685 fdrop(fp, td); 2686 2687 return (error); 2688 } 2689 2690 int 2691 fgetvp(struct thread *td, int fd, cap_rights_t *rightsp, struct vnode **vpp) 2692 { 2693 2694 return (_fgetvp(td, fd, 0, rightsp, vpp)); 2695 } 2696 2697 int 2698 fgetvp_rights(struct thread *td, int fd, cap_rights_t *needrightsp, 2699 struct filecaps *havecaps, struct vnode **vpp) 2700 { 2701 struct filedesc *fdp; 2702 struct file *fp; 2703 #ifdef CAPABILITIES 2704 int error; 2705 #endif 2706 2707 fdp = td->td_proc->p_fd; 2708 fp = fget_locked(fdp, fd); 2709 if (fp == NULL || fp->f_ops == &badfileops) 2710 return (EBADF); 2711 2712 #ifdef CAPABILITIES 2713 if (needrightsp != NULL) { 2714 error = cap_check(cap_rights(fdp, fd), needrightsp); 2715 if (error != 0) 2716 return (error); 2717 } 2718 #endif 2719 2720 if (fp->f_vnode == NULL) 2721 return (EINVAL); 2722 2723 *vpp = fp->f_vnode; 2724 vref(*vpp); 2725 filecaps_copy(&fdp->fd_ofiles[fd].fde_caps, havecaps); 2726 2727 return (0); 2728 } 2729 2730 int 2731 fgetvp_read(struct thread *td, int fd, cap_rights_t *rightsp, struct vnode **vpp) 2732 { 2733 2734 return (_fgetvp(td, fd, FREAD, rightsp, vpp)); 2735 } 2736 2737 int 2738 fgetvp_exec(struct thread *td, int fd, cap_rights_t *rightsp, struct vnode **vpp) 2739 { 2740 2741 return (_fgetvp(td, fd, FEXEC, rightsp, vpp)); 2742 } 2743 2744 #ifdef notyet 2745 int 2746 fgetvp_write(struct thread *td, int fd, cap_rights_t *rightsp, 2747 struct vnode **vpp) 2748 { 2749 2750 return (_fgetvp(td, fd, FWRITE, rightsp, vpp)); 2751 } 2752 #endif 2753 2754 /* 2755 * Like fget() but loads the underlying socket, or returns an error if the 2756 * descriptor does not represent a socket. 2757 * 2758 * We bump the ref count on the returned socket. XXX Also obtain the SX lock 2759 * in the future. 2760 * 2761 * Note: fgetsock() and fputsock() are deprecated, as consumers should rely 2762 * on their file descriptor reference to prevent the socket from being free'd 2763 * during use. 2764 */ 2765 int 2766 fgetsock(struct thread *td, int fd, cap_rights_t *rightsp, struct socket **spp, 2767 u_int *fflagp) 2768 { 2769 struct file *fp; 2770 int error; 2771 2772 *spp = NULL; 2773 if (fflagp != NULL) 2774 *fflagp = 0; 2775 if ((error = _fget(td, fd, &fp, 0, rightsp, NULL)) != 0) 2776 return (error); 2777 if (fp->f_type != DTYPE_SOCKET) { 2778 error = ENOTSOCK; 2779 } else { 2780 *spp = fp->f_data; 2781 if (fflagp) 2782 *fflagp = fp->f_flag; 2783 SOCK_LOCK(*spp); 2784 soref(*spp); 2785 SOCK_UNLOCK(*spp); 2786 } 2787 fdrop(fp, td); 2788 2789 return (error); 2790 } 2791 2792 /* 2793 * Drop the reference count on the socket and XXX release the SX lock in the 2794 * future. The last reference closes the socket. 2795 * 2796 * Note: fputsock() is deprecated, see comment for fgetsock(). 2797 */ 2798 void 2799 fputsock(struct socket *so) 2800 { 2801 2802 ACCEPT_LOCK(); 2803 SOCK_LOCK(so); 2804 CURVNET_SET(so->so_vnet); 2805 sorele(so); 2806 CURVNET_RESTORE(); 2807 } 2808 2809 /* 2810 * Handle the last reference to a file being closed. 2811 */ 2812 int 2813 _fdrop(struct file *fp, struct thread *td) 2814 { 2815 int error; 2816 2817 if (fp->f_count != 0) 2818 panic("fdrop: count %d", fp->f_count); 2819 error = fo_close(fp, td); 2820 atomic_subtract_int(&openfiles, 1); 2821 crfree(fp->f_cred); 2822 free(fp->f_advice, M_FADVISE); 2823 uma_zfree(file_zone, fp); 2824 2825 return (error); 2826 } 2827 2828 /* 2829 * Apply an advisory lock on a file descriptor. 2830 * 2831 * Just attempt to get a record lock of the requested type on the entire file 2832 * (l_whence = SEEK_SET, l_start = 0, l_len = 0). 2833 */ 2834 #ifndef _SYS_SYSPROTO_H_ 2835 struct flock_args { 2836 int fd; 2837 int how; 2838 }; 2839 #endif 2840 /* ARGSUSED */ 2841 int 2842 sys_flock(struct thread *td, struct flock_args *uap) 2843 { 2844 struct file *fp; 2845 struct vnode *vp; 2846 struct flock lf; 2847 cap_rights_t rights; 2848 int error; 2849 2850 error = fget(td, uap->fd, cap_rights_init(&rights, CAP_FLOCK), &fp); 2851 if (error != 0) 2852 return (error); 2853 if (fp->f_type != DTYPE_VNODE) { 2854 fdrop(fp, td); 2855 return (EOPNOTSUPP); 2856 } 2857 2858 vp = fp->f_vnode; 2859 lf.l_whence = SEEK_SET; 2860 lf.l_start = 0; 2861 lf.l_len = 0; 2862 if (uap->how & LOCK_UN) { 2863 lf.l_type = F_UNLCK; 2864 atomic_clear_int(&fp->f_flag, FHASLOCK); 2865 error = VOP_ADVLOCK(vp, (caddr_t)fp, F_UNLCK, &lf, F_FLOCK); 2866 goto done2; 2867 } 2868 if (uap->how & LOCK_EX) 2869 lf.l_type = F_WRLCK; 2870 else if (uap->how & LOCK_SH) 2871 lf.l_type = F_RDLCK; 2872 else { 2873 error = EBADF; 2874 goto done2; 2875 } 2876 atomic_set_int(&fp->f_flag, FHASLOCK); 2877 error = VOP_ADVLOCK(vp, (caddr_t)fp, F_SETLK, &lf, 2878 (uap->how & LOCK_NB) ? F_FLOCK : F_FLOCK | F_WAIT); 2879 done2: 2880 fdrop(fp, td); 2881 return (error); 2882 } 2883 /* 2884 * Duplicate the specified descriptor to a free descriptor. 2885 */ 2886 int 2887 dupfdopen(struct thread *td, struct filedesc *fdp, int dfd, int mode, 2888 int openerror, int *indxp) 2889 { 2890 struct filedescent *newfde, *oldfde; 2891 struct file *fp; 2892 int error, indx; 2893 2894 KASSERT(openerror == ENODEV || openerror == ENXIO, 2895 ("unexpected error %d in %s", openerror, __func__)); 2896 2897 /* 2898 * If the to-be-dup'd fd number is greater than the allowed number 2899 * of file descriptors, or the fd to be dup'd has already been 2900 * closed, then reject. 2901 */ 2902 FILEDESC_XLOCK(fdp); 2903 if ((fp = fget_locked(fdp, dfd)) == NULL) { 2904 FILEDESC_XUNLOCK(fdp); 2905 return (EBADF); 2906 } 2907 2908 error = fdalloc(td, 0, &indx); 2909 if (error != 0) { 2910 FILEDESC_XUNLOCK(fdp); 2911 return (error); 2912 } 2913 2914 /* 2915 * There are two cases of interest here. 2916 * 2917 * For ENODEV simply dup (dfd) to file descriptor (indx) and return. 2918 * 2919 * For ENXIO steal away the file structure from (dfd) and store it in 2920 * (indx). (dfd) is effectively closed by this operation. 2921 */ 2922 switch (openerror) { 2923 case ENODEV: 2924 /* 2925 * Check that the mode the file is being opened for is a 2926 * subset of the mode of the existing descriptor. 2927 */ 2928 if (((mode & (FREAD|FWRITE)) | fp->f_flag) != fp->f_flag) { 2929 fdunused(fdp, indx); 2930 FILEDESC_XUNLOCK(fdp); 2931 return (EACCES); 2932 } 2933 fhold(fp); 2934 newfde = &fdp->fd_ofiles[indx]; 2935 oldfde = &fdp->fd_ofiles[dfd]; 2936 #ifdef CAPABILITIES 2937 seq_write_begin(&newfde->fde_seq); 2938 #endif 2939 memcpy(newfde, oldfde, fde_change_size); 2940 filecaps_copy(&oldfde->fde_caps, &newfde->fde_caps); 2941 #ifdef CAPABILITIES 2942 seq_write_end(&newfde->fde_seq); 2943 #endif 2944 break; 2945 case ENXIO: 2946 /* 2947 * Steal away the file pointer from dfd and stuff it into indx. 2948 */ 2949 newfde = &fdp->fd_ofiles[indx]; 2950 oldfde = &fdp->fd_ofiles[dfd]; 2951 #ifdef CAPABILITIES 2952 seq_write_begin(&newfde->fde_seq); 2953 #endif 2954 memcpy(newfde, oldfde, fde_change_size); 2955 oldfde->fde_file = NULL; 2956 fdunused(fdp, dfd); 2957 #ifdef CAPABILITIES 2958 seq_write_end(&newfde->fde_seq); 2959 #endif 2960 break; 2961 } 2962 FILEDESC_XUNLOCK(fdp); 2963 *indxp = indx; 2964 return (0); 2965 } 2966 2967 /* 2968 * This sysctl determines if we will allow a process to chroot(2) if it 2969 * has a directory open: 2970 * 0: disallowed for all processes. 2971 * 1: allowed for processes that were not already chroot(2)'ed. 2972 * 2: allowed for all processes. 2973 */ 2974 2975 static int chroot_allow_open_directories = 1; 2976 2977 SYSCTL_INT(_kern, OID_AUTO, chroot_allow_open_directories, CTLFLAG_RW, 2978 &chroot_allow_open_directories, 0, 2979 "Allow a process to chroot(2) if it has a directory open"); 2980 2981 /* 2982 * Helper function for raised chroot(2) security function: Refuse if 2983 * any filedescriptors are open directories. 2984 */ 2985 static int 2986 chroot_refuse_vdir_fds(struct filedesc *fdp) 2987 { 2988 struct vnode *vp; 2989 struct file *fp; 2990 int fd; 2991 2992 FILEDESC_LOCK_ASSERT(fdp); 2993 2994 for (fd = 0; fd <= fdp->fd_lastfile; fd++) { 2995 fp = fget_locked(fdp, fd); 2996 if (fp == NULL) 2997 continue; 2998 if (fp->f_type == DTYPE_VNODE) { 2999 vp = fp->f_vnode; 3000 if (vp->v_type == VDIR) 3001 return (EPERM); 3002 } 3003 } 3004 return (0); 3005 } 3006 3007 /* 3008 * Common routine for kern_chroot() and jail_attach(). The caller is 3009 * responsible for invoking priv_check() and mac_vnode_check_chroot() to 3010 * authorize this operation. 3011 */ 3012 int 3013 pwd_chroot(struct thread *td, struct vnode *vp) 3014 { 3015 struct filedesc *fdp; 3016 struct vnode *oldvp; 3017 int error; 3018 3019 fdp = td->td_proc->p_fd; 3020 FILEDESC_XLOCK(fdp); 3021 if (chroot_allow_open_directories == 0 || 3022 (chroot_allow_open_directories == 1 && fdp->fd_rdir != rootvnode)) { 3023 error = chroot_refuse_vdir_fds(fdp); 3024 if (error != 0) { 3025 FILEDESC_XUNLOCK(fdp); 3026 return (error); 3027 } 3028 } 3029 oldvp = fdp->fd_rdir; 3030 VREF(vp); 3031 fdp->fd_rdir = vp; 3032 if (fdp->fd_jdir == NULL) { 3033 VREF(vp); 3034 fdp->fd_jdir = vp; 3035 } 3036 FILEDESC_XUNLOCK(fdp); 3037 vrele(oldvp); 3038 return (0); 3039 } 3040 3041 void 3042 pwd_chdir(struct thread *td, struct vnode *vp) 3043 { 3044 struct filedesc *fdp; 3045 struct vnode *oldvp; 3046 3047 fdp = td->td_proc->p_fd; 3048 FILEDESC_XLOCK(fdp); 3049 VNASSERT(vp->v_usecount > 0, vp, 3050 ("chdir to a vnode with zero usecount")); 3051 oldvp = fdp->fd_cdir; 3052 fdp->fd_cdir = vp; 3053 FILEDESC_XUNLOCK(fdp); 3054 vrele(oldvp); 3055 } 3056 3057 /* 3058 * Scan all active processes and prisons to see if any of them have a current 3059 * or root directory of `olddp'. If so, replace them with the new mount point. 3060 */ 3061 void 3062 mountcheckdirs(struct vnode *olddp, struct vnode *newdp) 3063 { 3064 struct filedesc *fdp; 3065 struct prison *pr; 3066 struct proc *p; 3067 int nrele; 3068 3069 if (vrefcnt(olddp) == 1) 3070 return; 3071 nrele = 0; 3072 sx_slock(&allproc_lock); 3073 FOREACH_PROC_IN_SYSTEM(p) { 3074 PROC_LOCK(p); 3075 fdp = fdhold(p); 3076 PROC_UNLOCK(p); 3077 if (fdp == NULL) 3078 continue; 3079 FILEDESC_XLOCK(fdp); 3080 if (fdp->fd_cdir == olddp) { 3081 vref(newdp); 3082 fdp->fd_cdir = newdp; 3083 nrele++; 3084 } 3085 if (fdp->fd_rdir == olddp) { 3086 vref(newdp); 3087 fdp->fd_rdir = newdp; 3088 nrele++; 3089 } 3090 if (fdp->fd_jdir == olddp) { 3091 vref(newdp); 3092 fdp->fd_jdir = newdp; 3093 nrele++; 3094 } 3095 FILEDESC_XUNLOCK(fdp); 3096 fddrop(fdp); 3097 } 3098 sx_sunlock(&allproc_lock); 3099 if (rootvnode == olddp) { 3100 vref(newdp); 3101 rootvnode = newdp; 3102 nrele++; 3103 } 3104 mtx_lock(&prison0.pr_mtx); 3105 if (prison0.pr_root == olddp) { 3106 vref(newdp); 3107 prison0.pr_root = newdp; 3108 nrele++; 3109 } 3110 mtx_unlock(&prison0.pr_mtx); 3111 sx_slock(&allprison_lock); 3112 TAILQ_FOREACH(pr, &allprison, pr_list) { 3113 mtx_lock(&pr->pr_mtx); 3114 if (pr->pr_root == olddp) { 3115 vref(newdp); 3116 pr->pr_root = newdp; 3117 nrele++; 3118 } 3119 mtx_unlock(&pr->pr_mtx); 3120 } 3121 sx_sunlock(&allprison_lock); 3122 while (nrele--) 3123 vrele(olddp); 3124 } 3125 3126 struct filedesc_to_leader * 3127 filedesc_to_leader_alloc(struct filedesc_to_leader *old, struct filedesc *fdp, struct proc *leader) 3128 { 3129 struct filedesc_to_leader *fdtol; 3130 3131 fdtol = malloc(sizeof(struct filedesc_to_leader), 3132 M_FILEDESC_TO_LEADER, M_WAITOK); 3133 fdtol->fdl_refcount = 1; 3134 fdtol->fdl_holdcount = 0; 3135 fdtol->fdl_wakeup = 0; 3136 fdtol->fdl_leader = leader; 3137 if (old != NULL) { 3138 FILEDESC_XLOCK(fdp); 3139 fdtol->fdl_next = old->fdl_next; 3140 fdtol->fdl_prev = old; 3141 old->fdl_next = fdtol; 3142 fdtol->fdl_next->fdl_prev = fdtol; 3143 FILEDESC_XUNLOCK(fdp); 3144 } else { 3145 fdtol->fdl_next = fdtol; 3146 fdtol->fdl_prev = fdtol; 3147 } 3148 return (fdtol); 3149 } 3150 3151 /* 3152 * Get file structures globally. 3153 */ 3154 static int 3155 sysctl_kern_file(SYSCTL_HANDLER_ARGS) 3156 { 3157 struct xfile xf; 3158 struct filedesc *fdp; 3159 struct file *fp; 3160 struct proc *p; 3161 int error, n; 3162 3163 error = sysctl_wire_old_buffer(req, 0); 3164 if (error != 0) 3165 return (error); 3166 if (req->oldptr == NULL) { 3167 n = 0; 3168 sx_slock(&allproc_lock); 3169 FOREACH_PROC_IN_SYSTEM(p) { 3170 PROC_LOCK(p); 3171 if (p->p_state == PRS_NEW) { 3172 PROC_UNLOCK(p); 3173 continue; 3174 } 3175 fdp = fdhold(p); 3176 PROC_UNLOCK(p); 3177 if (fdp == NULL) 3178 continue; 3179 /* overestimates sparse tables. */ 3180 if (fdp->fd_lastfile > 0) 3181 n += fdp->fd_lastfile; 3182 fddrop(fdp); 3183 } 3184 sx_sunlock(&allproc_lock); 3185 return (SYSCTL_OUT(req, 0, n * sizeof(xf))); 3186 } 3187 error = 0; 3188 bzero(&xf, sizeof(xf)); 3189 xf.xf_size = sizeof(xf); 3190 sx_slock(&allproc_lock); 3191 FOREACH_PROC_IN_SYSTEM(p) { 3192 PROC_LOCK(p); 3193 if (p->p_state == PRS_NEW) { 3194 PROC_UNLOCK(p); 3195 continue; 3196 } 3197 if (p_cansee(req->td, p) != 0) { 3198 PROC_UNLOCK(p); 3199 continue; 3200 } 3201 xf.xf_pid = p->p_pid; 3202 xf.xf_uid = p->p_ucred->cr_uid; 3203 fdp = fdhold(p); 3204 PROC_UNLOCK(p); 3205 if (fdp == NULL) 3206 continue; 3207 FILEDESC_SLOCK(fdp); 3208 for (n = 0; fdp->fd_refcnt > 0 && n <= fdp->fd_lastfile; ++n) { 3209 if ((fp = fdp->fd_ofiles[n].fde_file) == NULL) 3210 continue; 3211 xf.xf_fd = n; 3212 xf.xf_file = fp; 3213 xf.xf_data = fp->f_data; 3214 xf.xf_vnode = fp->f_vnode; 3215 xf.xf_type = fp->f_type; 3216 xf.xf_count = fp->f_count; 3217 xf.xf_msgcount = 0; 3218 xf.xf_offset = foffset_get(fp); 3219 xf.xf_flag = fp->f_flag; 3220 error = SYSCTL_OUT(req, &xf, sizeof(xf)); 3221 if (error) 3222 break; 3223 } 3224 FILEDESC_SUNLOCK(fdp); 3225 fddrop(fdp); 3226 if (error) 3227 break; 3228 } 3229 sx_sunlock(&allproc_lock); 3230 return (error); 3231 } 3232 3233 SYSCTL_PROC(_kern, KERN_FILE, file, CTLTYPE_OPAQUE|CTLFLAG_RD|CTLFLAG_MPSAFE, 3234 0, 0, sysctl_kern_file, "S,xfile", "Entire file table"); 3235 3236 #ifdef KINFO_FILE_SIZE 3237 CTASSERT(sizeof(struct kinfo_file) == KINFO_FILE_SIZE); 3238 #endif 3239 3240 static int 3241 xlate_fflags(int fflags) 3242 { 3243 static const struct { 3244 int fflag; 3245 int kf_fflag; 3246 } fflags_table[] = { 3247 { FAPPEND, KF_FLAG_APPEND }, 3248 { FASYNC, KF_FLAG_ASYNC }, 3249 { FFSYNC, KF_FLAG_FSYNC }, 3250 { FHASLOCK, KF_FLAG_HASLOCK }, 3251 { FNONBLOCK, KF_FLAG_NONBLOCK }, 3252 { FREAD, KF_FLAG_READ }, 3253 { FWRITE, KF_FLAG_WRITE }, 3254 { O_CREAT, KF_FLAG_CREAT }, 3255 { O_DIRECT, KF_FLAG_DIRECT }, 3256 { O_EXCL, KF_FLAG_EXCL }, 3257 { O_EXEC, KF_FLAG_EXEC }, 3258 { O_EXLOCK, KF_FLAG_EXLOCK }, 3259 { O_NOFOLLOW, KF_FLAG_NOFOLLOW }, 3260 { O_SHLOCK, KF_FLAG_SHLOCK }, 3261 { O_TRUNC, KF_FLAG_TRUNC } 3262 }; 3263 unsigned int i; 3264 int kflags; 3265 3266 kflags = 0; 3267 for (i = 0; i < nitems(fflags_table); i++) 3268 if (fflags & fflags_table[i].fflag) 3269 kflags |= fflags_table[i].kf_fflag; 3270 return (kflags); 3271 } 3272 3273 /* Trim unused data from kf_path by truncating the structure size. */ 3274 static void 3275 pack_kinfo(struct kinfo_file *kif) 3276 { 3277 3278 kif->kf_structsize = offsetof(struct kinfo_file, kf_path) + 3279 strlen(kif->kf_path) + 1; 3280 kif->kf_structsize = roundup(kif->kf_structsize, sizeof(uint64_t)); 3281 } 3282 3283 static void 3284 export_file_to_kinfo(struct file *fp, int fd, cap_rights_t *rightsp, 3285 struct kinfo_file *kif, struct filedesc *fdp) 3286 { 3287 int error; 3288 3289 bzero(kif, sizeof(*kif)); 3290 3291 /* Set a default type to allow for empty fill_kinfo() methods. */ 3292 kif->kf_type = KF_TYPE_UNKNOWN; 3293 kif->kf_flags = xlate_fflags(fp->f_flag); 3294 if (rightsp != NULL) 3295 kif->kf_cap_rights = *rightsp; 3296 else 3297 cap_rights_init(&kif->kf_cap_rights); 3298 kif->kf_fd = fd; 3299 kif->kf_ref_count = fp->f_count; 3300 kif->kf_offset = foffset_get(fp); 3301 3302 /* 3303 * This may drop the filedesc lock, so the 'fp' cannot be 3304 * accessed after this call. 3305 */ 3306 error = fo_fill_kinfo(fp, kif, fdp); 3307 if (error == 0) 3308 kif->kf_status |= KF_ATTR_VALID; 3309 pack_kinfo(kif); 3310 } 3311 3312 static void 3313 export_vnode_to_kinfo(struct vnode *vp, int fd, int fflags, 3314 struct kinfo_file *kif) 3315 { 3316 int error; 3317 3318 bzero(kif, sizeof(*kif)); 3319 3320 kif->kf_type = KF_TYPE_VNODE; 3321 error = vn_fill_kinfo_vnode(vp, kif); 3322 if (error == 0) 3323 kif->kf_status |= KF_ATTR_VALID; 3324 kif->kf_flags = xlate_fflags(fflags); 3325 cap_rights_init(&kif->kf_cap_rights); 3326 kif->kf_fd = fd; 3327 kif->kf_ref_count = -1; 3328 kif->kf_offset = -1; 3329 pack_kinfo(kif); 3330 vrele(vp); 3331 } 3332 3333 struct export_fd_buf { 3334 struct filedesc *fdp; 3335 struct sbuf *sb; 3336 ssize_t remainder; 3337 struct kinfo_file kif; 3338 }; 3339 3340 static int 3341 export_kinfo_to_sb(struct export_fd_buf *efbuf) 3342 { 3343 struct kinfo_file *kif; 3344 3345 kif = &efbuf->kif; 3346 if (efbuf->remainder != -1) { 3347 if (efbuf->remainder < kif->kf_structsize) { 3348 /* Terminate export. */ 3349 efbuf->remainder = 0; 3350 return (0); 3351 } 3352 efbuf->remainder -= kif->kf_structsize; 3353 } 3354 return (sbuf_bcat(efbuf->sb, kif, kif->kf_structsize) == 0 ? 0 : ENOMEM); 3355 } 3356 3357 static int 3358 export_file_to_sb(struct file *fp, int fd, cap_rights_t *rightsp, 3359 struct export_fd_buf *efbuf) 3360 { 3361 int error; 3362 3363 if (efbuf->remainder == 0) 3364 return (0); 3365 export_file_to_kinfo(fp, fd, rightsp, &efbuf->kif, efbuf->fdp); 3366 FILEDESC_SUNLOCK(efbuf->fdp); 3367 error = export_kinfo_to_sb(efbuf); 3368 FILEDESC_SLOCK(efbuf->fdp); 3369 return (error); 3370 } 3371 3372 static int 3373 export_vnode_to_sb(struct vnode *vp, int fd, int fflags, 3374 struct export_fd_buf *efbuf) 3375 { 3376 int error; 3377 3378 if (efbuf->remainder == 0) 3379 return (0); 3380 if (efbuf->fdp != NULL) 3381 FILEDESC_SUNLOCK(efbuf->fdp); 3382 export_vnode_to_kinfo(vp, fd, fflags, &efbuf->kif); 3383 error = export_kinfo_to_sb(efbuf); 3384 if (efbuf->fdp != NULL) 3385 FILEDESC_SLOCK(efbuf->fdp); 3386 return (error); 3387 } 3388 3389 /* 3390 * Store a process file descriptor information to sbuf. 3391 * 3392 * Takes a locked proc as argument, and returns with the proc unlocked. 3393 */ 3394 int 3395 kern_proc_filedesc_out(struct proc *p, struct sbuf *sb, ssize_t maxlen) 3396 { 3397 struct file *fp; 3398 struct filedesc *fdp; 3399 struct export_fd_buf *efbuf; 3400 struct vnode *cttyvp, *textvp, *tracevp; 3401 int error, i; 3402 cap_rights_t rights; 3403 3404 PROC_LOCK_ASSERT(p, MA_OWNED); 3405 3406 /* ktrace vnode */ 3407 tracevp = p->p_tracevp; 3408 if (tracevp != NULL) 3409 vref(tracevp); 3410 /* text vnode */ 3411 textvp = p->p_textvp; 3412 if (textvp != NULL) 3413 vref(textvp); 3414 /* Controlling tty. */ 3415 cttyvp = NULL; 3416 if (p->p_pgrp != NULL && p->p_pgrp->pg_session != NULL) { 3417 cttyvp = p->p_pgrp->pg_session->s_ttyvp; 3418 if (cttyvp != NULL) 3419 vref(cttyvp); 3420 } 3421 fdp = fdhold(p); 3422 PROC_UNLOCK(p); 3423 efbuf = malloc(sizeof(*efbuf), M_TEMP, M_WAITOK); 3424 efbuf->fdp = NULL; 3425 efbuf->sb = sb; 3426 efbuf->remainder = maxlen; 3427 if (tracevp != NULL) 3428 export_vnode_to_sb(tracevp, KF_FD_TYPE_TRACE, FREAD | FWRITE, 3429 efbuf); 3430 if (textvp != NULL) 3431 export_vnode_to_sb(textvp, KF_FD_TYPE_TEXT, FREAD, efbuf); 3432 if (cttyvp != NULL) 3433 export_vnode_to_sb(cttyvp, KF_FD_TYPE_CTTY, FREAD | FWRITE, 3434 efbuf); 3435 error = 0; 3436 if (fdp == NULL) 3437 goto fail; 3438 efbuf->fdp = fdp; 3439 FILEDESC_SLOCK(fdp); 3440 /* working directory */ 3441 if (fdp->fd_cdir != NULL) { 3442 vref(fdp->fd_cdir); 3443 export_vnode_to_sb(fdp->fd_cdir, KF_FD_TYPE_CWD, FREAD, efbuf); 3444 } 3445 /* root directory */ 3446 if (fdp->fd_rdir != NULL) { 3447 vref(fdp->fd_rdir); 3448 export_vnode_to_sb(fdp->fd_rdir, KF_FD_TYPE_ROOT, FREAD, efbuf); 3449 } 3450 /* jail directory */ 3451 if (fdp->fd_jdir != NULL) { 3452 vref(fdp->fd_jdir); 3453 export_vnode_to_sb(fdp->fd_jdir, KF_FD_TYPE_JAIL, FREAD, efbuf); 3454 } 3455 for (i = 0; fdp->fd_refcnt > 0 && i <= fdp->fd_lastfile; i++) { 3456 if ((fp = fdp->fd_ofiles[i].fde_file) == NULL) 3457 continue; 3458 #ifdef CAPABILITIES 3459 rights = *cap_rights(fdp, i); 3460 #else /* !CAPABILITIES */ 3461 cap_rights_init(&rights); 3462 #endif 3463 /* 3464 * Create sysctl entry. It is OK to drop the filedesc 3465 * lock inside of export_file_to_sb() as we will 3466 * re-validate and re-evaluate its properties when the 3467 * loop continues. 3468 */ 3469 error = export_file_to_sb(fp, i, &rights, efbuf); 3470 if (error != 0 || efbuf->remainder == 0) 3471 break; 3472 } 3473 FILEDESC_SUNLOCK(fdp); 3474 fddrop(fdp); 3475 fail: 3476 free(efbuf, M_TEMP); 3477 return (error); 3478 } 3479 3480 #define FILEDESC_SBUF_SIZE (sizeof(struct kinfo_file) * 5) 3481 3482 /* 3483 * Get per-process file descriptors for use by procstat(1), et al. 3484 */ 3485 static int 3486 sysctl_kern_proc_filedesc(SYSCTL_HANDLER_ARGS) 3487 { 3488 struct sbuf sb; 3489 struct proc *p; 3490 ssize_t maxlen; 3491 int error, error2, *name; 3492 3493 name = (int *)arg1; 3494 3495 sbuf_new_for_sysctl(&sb, NULL, FILEDESC_SBUF_SIZE, req); 3496 sbuf_clear_flags(&sb, SBUF_INCLUDENUL); 3497 error = pget((pid_t)name[0], PGET_CANDEBUG | PGET_NOTWEXIT, &p); 3498 if (error != 0) { 3499 sbuf_delete(&sb); 3500 return (error); 3501 } 3502 maxlen = req->oldptr != NULL ? req->oldlen : -1; 3503 error = kern_proc_filedesc_out(p, &sb, maxlen); 3504 error2 = sbuf_finish(&sb); 3505 sbuf_delete(&sb); 3506 return (error != 0 ? error : error2); 3507 } 3508 3509 #ifdef KINFO_OFILE_SIZE 3510 CTASSERT(sizeof(struct kinfo_ofile) == KINFO_OFILE_SIZE); 3511 #endif 3512 3513 #ifdef COMPAT_FREEBSD7 3514 static void 3515 kinfo_to_okinfo(struct kinfo_file *kif, struct kinfo_ofile *okif) 3516 { 3517 3518 okif->kf_structsize = sizeof(*okif); 3519 okif->kf_type = kif->kf_type; 3520 okif->kf_fd = kif->kf_fd; 3521 okif->kf_ref_count = kif->kf_ref_count; 3522 okif->kf_flags = kif->kf_flags & (KF_FLAG_READ | KF_FLAG_WRITE | 3523 KF_FLAG_APPEND | KF_FLAG_ASYNC | KF_FLAG_FSYNC | KF_FLAG_NONBLOCK | 3524 KF_FLAG_DIRECT | KF_FLAG_HASLOCK); 3525 okif->kf_offset = kif->kf_offset; 3526 okif->kf_vnode_type = kif->kf_vnode_type; 3527 okif->kf_sock_domain = kif->kf_sock_domain; 3528 okif->kf_sock_type = kif->kf_sock_type; 3529 okif->kf_sock_protocol = kif->kf_sock_protocol; 3530 strlcpy(okif->kf_path, kif->kf_path, sizeof(okif->kf_path)); 3531 okif->kf_sa_local = kif->kf_sa_local; 3532 okif->kf_sa_peer = kif->kf_sa_peer; 3533 } 3534 3535 static int 3536 export_vnode_for_osysctl(struct vnode *vp, int type, struct kinfo_file *kif, 3537 struct kinfo_ofile *okif, struct filedesc *fdp, struct sysctl_req *req) 3538 { 3539 int error; 3540 3541 vref(vp); 3542 FILEDESC_SUNLOCK(fdp); 3543 export_vnode_to_kinfo(vp, type, 0, kif); 3544 kinfo_to_okinfo(kif, okif); 3545 error = SYSCTL_OUT(req, okif, sizeof(*okif)); 3546 FILEDESC_SLOCK(fdp); 3547 return (error); 3548 } 3549 3550 /* 3551 * Get per-process file descriptors for use by procstat(1), et al. 3552 */ 3553 static int 3554 sysctl_kern_proc_ofiledesc(SYSCTL_HANDLER_ARGS) 3555 { 3556 struct kinfo_ofile *okif; 3557 struct kinfo_file *kif; 3558 struct filedesc *fdp; 3559 int error, i, *name; 3560 struct file *fp; 3561 struct proc *p; 3562 3563 name = (int *)arg1; 3564 error = pget((pid_t)name[0], PGET_CANDEBUG | PGET_NOTWEXIT, &p); 3565 if (error != 0) 3566 return (error); 3567 fdp = fdhold(p); 3568 PROC_UNLOCK(p); 3569 if (fdp == NULL) 3570 return (ENOENT); 3571 kif = malloc(sizeof(*kif), M_TEMP, M_WAITOK); 3572 okif = malloc(sizeof(*okif), M_TEMP, M_WAITOK); 3573 FILEDESC_SLOCK(fdp); 3574 if (fdp->fd_cdir != NULL) 3575 export_vnode_for_osysctl(fdp->fd_cdir, KF_FD_TYPE_CWD, kif, 3576 okif, fdp, req); 3577 if (fdp->fd_rdir != NULL) 3578 export_vnode_for_osysctl(fdp->fd_rdir, KF_FD_TYPE_ROOT, kif, 3579 okif, fdp, req); 3580 if (fdp->fd_jdir != NULL) 3581 export_vnode_for_osysctl(fdp->fd_jdir, KF_FD_TYPE_JAIL, kif, 3582 okif, fdp, req); 3583 for (i = 0; fdp->fd_refcnt > 0 && i <= fdp->fd_lastfile; i++) { 3584 if ((fp = fdp->fd_ofiles[i].fde_file) == NULL) 3585 continue; 3586 export_file_to_kinfo(fp, i, NULL, kif, fdp); 3587 FILEDESC_SUNLOCK(fdp); 3588 kinfo_to_okinfo(kif, okif); 3589 error = SYSCTL_OUT(req, okif, sizeof(*okif)); 3590 FILEDESC_SLOCK(fdp); 3591 if (error) 3592 break; 3593 } 3594 FILEDESC_SUNLOCK(fdp); 3595 fddrop(fdp); 3596 free(kif, M_TEMP); 3597 free(okif, M_TEMP); 3598 return (0); 3599 } 3600 3601 static SYSCTL_NODE(_kern_proc, KERN_PROC_OFILEDESC, ofiledesc, 3602 CTLFLAG_RD|CTLFLAG_MPSAFE, sysctl_kern_proc_ofiledesc, 3603 "Process ofiledesc entries"); 3604 #endif /* COMPAT_FREEBSD7 */ 3605 3606 int 3607 vntype_to_kinfo(int vtype) 3608 { 3609 struct { 3610 int vtype; 3611 int kf_vtype; 3612 } vtypes_table[] = { 3613 { VBAD, KF_VTYPE_VBAD }, 3614 { VBLK, KF_VTYPE_VBLK }, 3615 { VCHR, KF_VTYPE_VCHR }, 3616 { VDIR, KF_VTYPE_VDIR }, 3617 { VFIFO, KF_VTYPE_VFIFO }, 3618 { VLNK, KF_VTYPE_VLNK }, 3619 { VNON, KF_VTYPE_VNON }, 3620 { VREG, KF_VTYPE_VREG }, 3621 { VSOCK, KF_VTYPE_VSOCK } 3622 }; 3623 unsigned int i; 3624 3625 /* 3626 * Perform vtype translation. 3627 */ 3628 for (i = 0; i < nitems(vtypes_table); i++) 3629 if (vtypes_table[i].vtype == vtype) 3630 return (vtypes_table[i].kf_vtype); 3631 3632 return (KF_VTYPE_UNKNOWN); 3633 } 3634 3635 static SYSCTL_NODE(_kern_proc, KERN_PROC_FILEDESC, filedesc, 3636 CTLFLAG_RD|CTLFLAG_MPSAFE, sysctl_kern_proc_filedesc, 3637 "Process filedesc entries"); 3638 3639 /* 3640 * Store a process current working directory information to sbuf. 3641 * 3642 * Takes a locked proc as argument, and returns with the proc unlocked. 3643 */ 3644 int 3645 kern_proc_cwd_out(struct proc *p, struct sbuf *sb, ssize_t maxlen) 3646 { 3647 struct filedesc *fdp; 3648 struct export_fd_buf *efbuf; 3649 int error; 3650 3651 PROC_LOCK_ASSERT(p, MA_OWNED); 3652 3653 fdp = fdhold(p); 3654 PROC_UNLOCK(p); 3655 if (fdp == NULL) 3656 return (EINVAL); 3657 3658 efbuf = malloc(sizeof(*efbuf), M_TEMP, M_WAITOK); 3659 efbuf->fdp = fdp; 3660 efbuf->sb = sb; 3661 efbuf->remainder = maxlen; 3662 3663 FILEDESC_SLOCK(fdp); 3664 if (fdp->fd_cdir == NULL) 3665 error = EINVAL; 3666 else { 3667 vref(fdp->fd_cdir); 3668 error = export_vnode_to_sb(fdp->fd_cdir, KF_FD_TYPE_CWD, 3669 FREAD, efbuf); 3670 } 3671 FILEDESC_SUNLOCK(fdp); 3672 fddrop(fdp); 3673 free(efbuf, M_TEMP); 3674 return (error); 3675 } 3676 3677 /* 3678 * Get per-process current working directory. 3679 */ 3680 static int 3681 sysctl_kern_proc_cwd(SYSCTL_HANDLER_ARGS) 3682 { 3683 struct sbuf sb; 3684 struct proc *p; 3685 ssize_t maxlen; 3686 int error, error2, *name; 3687 3688 name = (int *)arg1; 3689 3690 sbuf_new_for_sysctl(&sb, NULL, sizeof(struct kinfo_file), req); 3691 sbuf_clear_flags(&sb, SBUF_INCLUDENUL); 3692 error = pget((pid_t)name[0], PGET_CANDEBUG | PGET_NOTWEXIT, &p); 3693 if (error != 0) { 3694 sbuf_delete(&sb); 3695 return (error); 3696 } 3697 maxlen = req->oldptr != NULL ? req->oldlen : -1; 3698 error = kern_proc_cwd_out(p, &sb, maxlen); 3699 error2 = sbuf_finish(&sb); 3700 sbuf_delete(&sb); 3701 return (error != 0 ? error : error2); 3702 } 3703 3704 static SYSCTL_NODE(_kern_proc, KERN_PROC_CWD, cwd, CTLFLAG_RD|CTLFLAG_MPSAFE, 3705 sysctl_kern_proc_cwd, "Process current working directory"); 3706 3707 #ifdef DDB 3708 /* 3709 * For the purposes of debugging, generate a human-readable string for the 3710 * file type. 3711 */ 3712 static const char * 3713 file_type_to_name(short type) 3714 { 3715 3716 switch (type) { 3717 case 0: 3718 return ("zero"); 3719 case DTYPE_VNODE: 3720 return ("vnod"); 3721 case DTYPE_SOCKET: 3722 return ("sock"); 3723 case DTYPE_PIPE: 3724 return ("pipe"); 3725 case DTYPE_FIFO: 3726 return ("fifo"); 3727 case DTYPE_KQUEUE: 3728 return ("kque"); 3729 case DTYPE_CRYPTO: 3730 return ("crpt"); 3731 case DTYPE_MQUEUE: 3732 return ("mque"); 3733 case DTYPE_SHM: 3734 return ("shm"); 3735 case DTYPE_SEM: 3736 return ("ksem"); 3737 default: 3738 return ("unkn"); 3739 } 3740 } 3741 3742 /* 3743 * For the purposes of debugging, identify a process (if any, perhaps one of 3744 * many) that references the passed file in its file descriptor array. Return 3745 * NULL if none. 3746 */ 3747 static struct proc * 3748 file_to_first_proc(struct file *fp) 3749 { 3750 struct filedesc *fdp; 3751 struct proc *p; 3752 int n; 3753 3754 FOREACH_PROC_IN_SYSTEM(p) { 3755 if (p->p_state == PRS_NEW) 3756 continue; 3757 fdp = p->p_fd; 3758 if (fdp == NULL) 3759 continue; 3760 for (n = 0; n <= fdp->fd_lastfile; n++) { 3761 if (fp == fdp->fd_ofiles[n].fde_file) 3762 return (p); 3763 } 3764 } 3765 return (NULL); 3766 } 3767 3768 static void 3769 db_print_file(struct file *fp, int header) 3770 { 3771 struct proc *p; 3772 3773 if (header) 3774 db_printf("%8s %4s %8s %8s %4s %5s %6s %8s %5s %12s\n", 3775 "File", "Type", "Data", "Flag", "GCFl", "Count", 3776 "MCount", "Vnode", "FPID", "FCmd"); 3777 p = file_to_first_proc(fp); 3778 db_printf("%8p %4s %8p %08x %04x %5d %6d %8p %5d %12s\n", fp, 3779 file_type_to_name(fp->f_type), fp->f_data, fp->f_flag, 3780 0, fp->f_count, 0, fp->f_vnode, 3781 p != NULL ? p->p_pid : -1, p != NULL ? p->p_comm : "-"); 3782 } 3783 3784 DB_SHOW_COMMAND(file, db_show_file) 3785 { 3786 struct file *fp; 3787 3788 if (!have_addr) { 3789 db_printf("usage: show file <addr>\n"); 3790 return; 3791 } 3792 fp = (struct file *)addr; 3793 db_print_file(fp, 1); 3794 } 3795 3796 DB_SHOW_COMMAND(files, db_show_files) 3797 { 3798 struct filedesc *fdp; 3799 struct file *fp; 3800 struct proc *p; 3801 int header; 3802 int n; 3803 3804 header = 1; 3805 FOREACH_PROC_IN_SYSTEM(p) { 3806 if (p->p_state == PRS_NEW) 3807 continue; 3808 if ((fdp = p->p_fd) == NULL) 3809 continue; 3810 for (n = 0; n <= fdp->fd_lastfile; ++n) { 3811 if ((fp = fdp->fd_ofiles[n].fde_file) == NULL) 3812 continue; 3813 db_print_file(fp, header); 3814 header = 0; 3815 } 3816 } 3817 } 3818 #endif 3819 3820 SYSCTL_INT(_kern, KERN_MAXFILESPERPROC, maxfilesperproc, CTLFLAG_RW, 3821 &maxfilesperproc, 0, "Maximum files allowed open per process"); 3822 3823 SYSCTL_INT(_kern, KERN_MAXFILES, maxfiles, CTLFLAG_RW, 3824 &maxfiles, 0, "Maximum number of files"); 3825 3826 SYSCTL_INT(_kern, OID_AUTO, openfiles, CTLFLAG_RD, 3827 __DEVOLATILE(int *, &openfiles), 0, "System-wide number of open files"); 3828 3829 /* ARGSUSED*/ 3830 static void 3831 filelistinit(void *dummy) 3832 { 3833 3834 file_zone = uma_zcreate("Files", sizeof(struct file), NULL, NULL, 3835 NULL, NULL, UMA_ALIGN_PTR, UMA_ZONE_NOFREE); 3836 filedesc0_zone = uma_zcreate("filedesc0", sizeof(struct filedesc0), 3837 NULL, NULL, NULL, NULL, UMA_ALIGN_PTR, 0); 3838 mtx_init(&sigio_lock, "sigio lock", NULL, MTX_DEF); 3839 } 3840 SYSINIT(select, SI_SUB_LOCK, SI_ORDER_FIRST, filelistinit, NULL); 3841 3842 /*-------------------------------------------------------------------*/ 3843 3844 static int 3845 badfo_readwrite(struct file *fp, struct uio *uio, struct ucred *active_cred, 3846 int flags, struct thread *td) 3847 { 3848 3849 return (EBADF); 3850 } 3851 3852 static int 3853 badfo_truncate(struct file *fp, off_t length, struct ucred *active_cred, 3854 struct thread *td) 3855 { 3856 3857 return (EINVAL); 3858 } 3859 3860 static int 3861 badfo_ioctl(struct file *fp, u_long com, void *data, struct ucred *active_cred, 3862 struct thread *td) 3863 { 3864 3865 return (EBADF); 3866 } 3867 3868 static int 3869 badfo_poll(struct file *fp, int events, struct ucred *active_cred, 3870 struct thread *td) 3871 { 3872 3873 return (0); 3874 } 3875 3876 static int 3877 badfo_kqfilter(struct file *fp, struct knote *kn) 3878 { 3879 3880 return (EBADF); 3881 } 3882 3883 static int 3884 badfo_stat(struct file *fp, struct stat *sb, struct ucred *active_cred, 3885 struct thread *td) 3886 { 3887 3888 return (EBADF); 3889 } 3890 3891 static int 3892 badfo_close(struct file *fp, struct thread *td) 3893 { 3894 3895 return (0); 3896 } 3897 3898 static int 3899 badfo_chmod(struct file *fp, mode_t mode, struct ucred *active_cred, 3900 struct thread *td) 3901 { 3902 3903 return (EBADF); 3904 } 3905 3906 static int 3907 badfo_chown(struct file *fp, uid_t uid, gid_t gid, struct ucred *active_cred, 3908 struct thread *td) 3909 { 3910 3911 return (EBADF); 3912 } 3913 3914 static int 3915 badfo_sendfile(struct file *fp, int sockfd, struct uio *hdr_uio, 3916 struct uio *trl_uio, off_t offset, size_t nbytes, off_t *sent, int flags, 3917 int kflags, struct thread *td) 3918 { 3919 3920 return (EBADF); 3921 } 3922 3923 static int 3924 badfo_fill_kinfo(struct file *fp, struct kinfo_file *kif, struct filedesc *fdp) 3925 { 3926 3927 return (0); 3928 } 3929 3930 struct fileops badfileops = { 3931 .fo_read = badfo_readwrite, 3932 .fo_write = badfo_readwrite, 3933 .fo_truncate = badfo_truncate, 3934 .fo_ioctl = badfo_ioctl, 3935 .fo_poll = badfo_poll, 3936 .fo_kqfilter = badfo_kqfilter, 3937 .fo_stat = badfo_stat, 3938 .fo_close = badfo_close, 3939 .fo_chmod = badfo_chmod, 3940 .fo_chown = badfo_chown, 3941 .fo_sendfile = badfo_sendfile, 3942 .fo_fill_kinfo = badfo_fill_kinfo, 3943 }; 3944 3945 int 3946 invfo_rdwr(struct file *fp, struct uio *uio, struct ucred *active_cred, 3947 int flags, struct thread *td) 3948 { 3949 3950 return (EOPNOTSUPP); 3951 } 3952 3953 int 3954 invfo_truncate(struct file *fp, off_t length, struct ucred *active_cred, 3955 struct thread *td) 3956 { 3957 3958 return (EINVAL); 3959 } 3960 3961 int 3962 invfo_ioctl(struct file *fp, u_long com, void *data, 3963 struct ucred *active_cred, struct thread *td) 3964 { 3965 3966 return (ENOTTY); 3967 } 3968 3969 int 3970 invfo_poll(struct file *fp, int events, struct ucred *active_cred, 3971 struct thread *td) 3972 { 3973 3974 return (poll_no_poll(events)); 3975 } 3976 3977 int 3978 invfo_kqfilter(struct file *fp, struct knote *kn) 3979 { 3980 3981 return (EINVAL); 3982 } 3983 3984 int 3985 invfo_chmod(struct file *fp, mode_t mode, struct ucred *active_cred, 3986 struct thread *td) 3987 { 3988 3989 return (EINVAL); 3990 } 3991 3992 int 3993 invfo_chown(struct file *fp, uid_t uid, gid_t gid, struct ucred *active_cred, 3994 struct thread *td) 3995 { 3996 3997 return (EINVAL); 3998 } 3999 4000 int 4001 invfo_sendfile(struct file *fp, int sockfd, struct uio *hdr_uio, 4002 struct uio *trl_uio, off_t offset, size_t nbytes, off_t *sent, int flags, 4003 int kflags, struct thread *td) 4004 { 4005 4006 return (EINVAL); 4007 } 4008 4009 /*-------------------------------------------------------------------*/ 4010 4011 /* 4012 * File Descriptor pseudo-device driver (/dev/fd/). 4013 * 4014 * Opening minor device N dup()s the file (if any) connected to file 4015 * descriptor N belonging to the calling process. Note that this driver 4016 * consists of only the ``open()'' routine, because all subsequent 4017 * references to this file will be direct to the other driver. 4018 * 4019 * XXX: we could give this one a cloning event handler if necessary. 4020 */ 4021 4022 /* ARGSUSED */ 4023 static int 4024 fdopen(struct cdev *dev, int mode, int type, struct thread *td) 4025 { 4026 4027 /* 4028 * XXX Kludge: set curthread->td_dupfd to contain the value of the 4029 * the file descriptor being sought for duplication. The error 4030 * return ensures that the vnode for this device will be released 4031 * by vn_open. Open will detect this special error and take the 4032 * actions in dupfdopen below. Other callers of vn_open or VOP_OPEN 4033 * will simply report the error. 4034 */ 4035 td->td_dupfd = dev2unit(dev); 4036 return (ENODEV); 4037 } 4038 4039 static struct cdevsw fildesc_cdevsw = { 4040 .d_version = D_VERSION, 4041 .d_open = fdopen, 4042 .d_name = "FD", 4043 }; 4044 4045 static void 4046 fildesc_drvinit(void *unused) 4047 { 4048 struct cdev *dev; 4049 4050 dev = make_dev_credf(MAKEDEV_ETERNAL, &fildesc_cdevsw, 0, NULL, 4051 UID_ROOT, GID_WHEEL, 0666, "fd/0"); 4052 make_dev_alias(dev, "stdin"); 4053 dev = make_dev_credf(MAKEDEV_ETERNAL, &fildesc_cdevsw, 1, NULL, 4054 UID_ROOT, GID_WHEEL, 0666, "fd/1"); 4055 make_dev_alias(dev, "stdout"); 4056 dev = make_dev_credf(MAKEDEV_ETERNAL, &fildesc_cdevsw, 2, NULL, 4057 UID_ROOT, GID_WHEEL, 0666, "fd/2"); 4058 make_dev_alias(dev, "stderr"); 4059 } 4060 4061 SYSINIT(fildescdev, SI_SUB_DRIVERS, SI_ORDER_MIDDLE, fildesc_drvinit, NULL); 4062