1 /* $NetBSD: uipc_usrreq.c,v 1.136 2011/06/26 16:42:43 christos Exp $ */ 2 3 /*- 4 * Copyright (c) 1998, 2000, 2004, 2008, 2009 The NetBSD Foundation, Inc. 5 * All rights reserved. 6 * 7 * This code is derived from software contributed to The NetBSD Foundation 8 * by Jason R. Thorpe of the Numerical Aerospace Simulation Facility, 9 * NASA Ames Research Center, and by Andrew Doran. 10 * 11 * Redistribution and use in source and binary forms, with or without 12 * modification, are permitted provided that the following conditions 13 * are met: 14 * 1. Redistributions of source code must retain the above copyright 15 * notice, this list of conditions and the following disclaimer. 16 * 2. Redistributions in binary form must reproduce the above copyright 17 * notice, this list of conditions and the following disclaimer in the 18 * documentation and/or other materials provided with the distribution. 19 * 20 * THIS SOFTWARE IS PROVIDED BY THE NETBSD FOUNDATION, INC. AND CONTRIBUTORS 21 * ``AS IS'' AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED 22 * TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR 23 * PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE FOUNDATION OR CONTRIBUTORS 24 * BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR 25 * CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF 26 * SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS 27 * INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN 28 * CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) 29 * ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE 30 * POSSIBILITY OF SUCH DAMAGE. 31 */ 32 33 /* 34 * Copyright (c) 1982, 1986, 1989, 1991, 1993 35 * The Regents of the University of California. All rights reserved. 36 * 37 * Redistribution and use in source and binary forms, with or without 38 * modification, are permitted provided that the following conditions 39 * are met: 40 * 1. Redistributions of source code must retain the above copyright 41 * notice, this list of conditions and the following disclaimer. 42 * 2. Redistributions in binary form must reproduce the above copyright 43 * notice, this list of conditions and the following disclaimer in the 44 * documentation and/or other materials provided with the distribution. 45 * 3. Neither the name of the University nor the names of its contributors 46 * may be used to endorse or promote products derived from this software 47 * without specific prior written permission. 48 * 49 * THIS SOFTWARE IS PROVIDED BY THE REGENTS AND CONTRIBUTORS ``AS IS'' AND 50 * ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE 51 * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE 52 * ARE DISCLAIMED. IN NO EVENT SHALL THE REGENTS OR CONTRIBUTORS BE LIABLE 53 * FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL 54 * DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS 55 * OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) 56 * HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT 57 * LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY 58 * OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF 59 * SUCH DAMAGE. 60 * 61 * @(#)uipc_usrreq.c 8.9 (Berkeley) 5/14/95 62 */ 63 64 /* 65 * Copyright (c) 1997 Christopher G. Demetriou. All rights reserved. 66 * 67 * Redistribution and use in source and binary forms, with or without 68 * modification, are permitted provided that the following conditions 69 * are met: 70 * 1. Redistributions of source code must retain the above copyright 71 * notice, this list of conditions and the following disclaimer. 72 * 2. Redistributions in binary form must reproduce the above copyright 73 * notice, this list of conditions and the following disclaimer in the 74 * documentation and/or other materials provided with the distribution. 75 * 3. All advertising materials mentioning features or use of this software 76 * must display the following acknowledgement: 77 * This product includes software developed by the University of 78 * California, Berkeley and its contributors. 79 * 4. Neither the name of the University nor the names of its contributors 80 * may be used to endorse or promote products derived from this software 81 * without specific prior written permission. 82 * 83 * THIS SOFTWARE IS PROVIDED BY THE REGENTS AND CONTRIBUTORS ``AS IS'' AND 84 * ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE 85 * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE 86 * ARE DISCLAIMED. IN NO EVENT SHALL THE REGENTS OR CONTRIBUTORS BE LIABLE 87 * FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL 88 * DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS 89 * OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) 90 * HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT 91 * LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY 92 * OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF 93 * SUCH DAMAGE. 94 * 95 * @(#)uipc_usrreq.c 8.9 (Berkeley) 5/14/95 96 */ 97 98 #include <sys/cdefs.h> 99 __KERNEL_RCSID(0, "$NetBSD: uipc_usrreq.c,v 1.136 2011/06/26 16:42:43 christos Exp $"); 100 101 #include <sys/param.h> 102 #include <sys/systm.h> 103 #include <sys/proc.h> 104 #include <sys/filedesc.h> 105 #include <sys/domain.h> 106 #include <sys/protosw.h> 107 #include <sys/socket.h> 108 #include <sys/socketvar.h> 109 #include <sys/unpcb.h> 110 #include <sys/un.h> 111 #include <sys/namei.h> 112 #include <sys/vnode.h> 113 #include <sys/file.h> 114 #include <sys/stat.h> 115 #include <sys/mbuf.h> 116 #include <sys/kauth.h> 117 #include <sys/kmem.h> 118 #include <sys/atomic.h> 119 #include <sys/uidinfo.h> 120 #include <sys/kernel.h> 121 #include <sys/kthread.h> 122 123 /* 124 * Unix communications domain. 125 * 126 * TODO: 127 * RDM 128 * rethink name space problems 129 * need a proper out-of-band 130 * 131 * Notes on locking: 132 * 133 * The generic rules noted in uipc_socket2.c apply. In addition: 134 * 135 * o We have a global lock, uipc_lock. 136 * 137 * o All datagram sockets are locked by uipc_lock. 138 * 139 * o For stream socketpairs, the two endpoints are created sharing the same 140 * independent lock. Sockets presented to PRU_CONNECT2 must already have 141 * matching locks. 142 * 143 * o Stream sockets created via socket() start life with their own 144 * independent lock. 145 * 146 * o Stream connections to a named endpoint are slightly more complicated. 147 * Sockets that have called listen() have their lock pointer mutated to 148 * the global uipc_lock. When establishing a connection, the connecting 149 * socket also has its lock mutated to uipc_lock, which matches the head 150 * (listening socket). We create a new socket for accept() to return, and 151 * that also shares the head's lock. Until the connection is completely 152 * done on both ends, all three sockets are locked by uipc_lock. Once the 153 * connection is complete, the association with the head's lock is broken. 154 * The connecting socket and the socket returned from accept() have their 155 * lock pointers mutated away from uipc_lock, and back to the connecting 156 * socket's original, independent lock. The head continues to be locked 157 * by uipc_lock. 158 * 159 * o If uipc_lock is determined to be a significant source of contention, 160 * it could easily be hashed out. It is difficult to simply make it an 161 * independent lock because of visibility / garbage collection issues: 162 * if a socket has been associated with a lock at any point, that lock 163 * must remain valid until the socket is no longer visible in the system. 164 * The lock must not be freed or otherwise destroyed until any sockets 165 * that had referenced it have also been destroyed. 166 */ 167 const struct sockaddr_un sun_noname = { 168 .sun_len = sizeof(sun_noname), 169 .sun_family = AF_LOCAL, 170 }; 171 ino_t unp_ino; /* prototype for fake inode numbers */ 172 173 struct mbuf *unp_addsockcred(struct lwp *, struct mbuf *); 174 static void unp_mark(file_t *); 175 static void unp_scan(struct mbuf *, void (*)(file_t *), int); 176 static void unp_discard_now(file_t *); 177 static void unp_discard_later(file_t *); 178 static void unp_thread(void *); 179 static void unp_thread_kick(void); 180 static kmutex_t *uipc_lock; 181 182 static kcondvar_t unp_thread_cv; 183 static lwp_t *unp_thread_lwp; 184 static SLIST_HEAD(,file) unp_thread_discard; 185 static int unp_defer; 186 187 /* 188 * Initialize Unix protocols. 189 */ 190 void 191 uipc_init(void) 192 { 193 int error; 194 195 uipc_lock = mutex_obj_alloc(MUTEX_DEFAULT, IPL_NONE); 196 cv_init(&unp_thread_cv, "unpgc"); 197 198 error = kthread_create(PRI_NONE, KTHREAD_MPSAFE, NULL, unp_thread, 199 NULL, &unp_thread_lwp, "unpgc"); 200 if (error != 0) 201 panic("uipc_init %d", error); 202 } 203 204 /* 205 * A connection succeeded: disassociate both endpoints from the head's 206 * lock, and make them share their own lock. There is a race here: for 207 * a very brief time one endpoint will be locked by a different lock 208 * than the other end. However, since the current thread holds the old 209 * lock (the listening socket's lock, the head) access can still only be 210 * made to one side of the connection. 211 */ 212 static void 213 unp_setpeerlocks(struct socket *so, struct socket *so2) 214 { 215 struct unpcb *unp; 216 kmutex_t *lock; 217 218 KASSERT(solocked2(so, so2)); 219 220 /* 221 * Bail out if either end of the socket is not yet fully 222 * connected or accepted. We only break the lock association 223 * with the head when the pair of sockets stand completely 224 * on their own. 225 */ 226 KASSERT(so->so_head == NULL); 227 if (so2->so_head != NULL) 228 return; 229 230 /* 231 * Drop references to old lock. A third reference (from the 232 * queue head) must be held as we still hold its lock. Bonus: 233 * we don't need to worry about garbage collecting the lock. 234 */ 235 lock = so->so_lock; 236 KASSERT(lock == uipc_lock); 237 mutex_obj_free(lock); 238 mutex_obj_free(lock); 239 240 /* 241 * Grab stream lock from the initiator and share between the two 242 * endpoints. Issue memory barrier to ensure all modifications 243 * become globally visible before the lock change. so2 is 244 * assumed not to have a stream lock, because it was created 245 * purely for the server side to accept this connection and 246 * started out life using the domain-wide lock. 247 */ 248 unp = sotounpcb(so); 249 KASSERT(unp->unp_streamlock != NULL); 250 KASSERT(sotounpcb(so2)->unp_streamlock == NULL); 251 lock = unp->unp_streamlock; 252 unp->unp_streamlock = NULL; 253 mutex_obj_hold(lock); 254 membar_exit(); 255 /* 256 * possible race if lock is not held - see comment in 257 * uipc_usrreq(PRU_ACCEPT). 258 */ 259 KASSERT(mutex_owned(lock)); 260 solockreset(so, lock); 261 solockreset(so2, lock); 262 } 263 264 /* 265 * Reset a socket's lock back to the domain-wide lock. 266 */ 267 static void 268 unp_resetlock(struct socket *so) 269 { 270 kmutex_t *olock, *nlock; 271 struct unpcb *unp; 272 273 KASSERT(solocked(so)); 274 275 olock = so->so_lock; 276 nlock = uipc_lock; 277 if (olock == nlock) 278 return; 279 unp = sotounpcb(so); 280 KASSERT(unp->unp_streamlock == NULL); 281 unp->unp_streamlock = olock; 282 mutex_obj_hold(nlock); 283 mutex_enter(nlock); 284 solockreset(so, nlock); 285 mutex_exit(olock); 286 } 287 288 static void 289 unp_free(struct unpcb *unp) 290 { 291 292 if (unp->unp_addr) 293 free(unp->unp_addr, M_SONAME); 294 if (unp->unp_streamlock != NULL) 295 mutex_obj_free(unp->unp_streamlock); 296 free(unp, M_PCB); 297 } 298 299 int 300 unp_output(struct mbuf *m, struct mbuf *control, struct unpcb *unp, 301 struct lwp *l) 302 { 303 struct socket *so2; 304 const struct sockaddr_un *sun; 305 306 so2 = unp->unp_conn->unp_socket; 307 308 KASSERT(solocked(so2)); 309 310 if (unp->unp_addr) 311 sun = unp->unp_addr; 312 else 313 sun = &sun_noname; 314 if (unp->unp_conn->unp_flags & UNP_WANTCRED) 315 control = unp_addsockcred(l, control); 316 if (sbappendaddr(&so2->so_rcv, (const struct sockaddr *)sun, m, 317 control) == 0) { 318 so2->so_rcv.sb_overflowed++; 319 unp_dispose(control); 320 m_freem(control); 321 m_freem(m); 322 return (ENOBUFS); 323 } else { 324 sorwakeup(so2); 325 return (0); 326 } 327 } 328 329 void 330 unp_setaddr(struct socket *so, struct mbuf *nam, bool peeraddr) 331 { 332 const struct sockaddr_un *sun; 333 struct unpcb *unp; 334 bool ext; 335 336 KASSERT(solocked(so)); 337 unp = sotounpcb(so); 338 ext = false; 339 340 for (;;) { 341 sun = NULL; 342 if (peeraddr) { 343 if (unp->unp_conn && unp->unp_conn->unp_addr) 344 sun = unp->unp_conn->unp_addr; 345 } else { 346 if (unp->unp_addr) 347 sun = unp->unp_addr; 348 } 349 if (sun == NULL) 350 sun = &sun_noname; 351 nam->m_len = sun->sun_len; 352 if (nam->m_len > MLEN && !ext) { 353 sounlock(so); 354 MEXTMALLOC(nam, MAXPATHLEN * 2, M_WAITOK); 355 solock(so); 356 ext = true; 357 } else { 358 KASSERT(nam->m_len <= MAXPATHLEN * 2); 359 memcpy(mtod(nam, void *), sun, (size_t)nam->m_len); 360 break; 361 } 362 } 363 } 364 365 /*ARGSUSED*/ 366 int 367 uipc_usrreq(struct socket *so, int req, struct mbuf *m, struct mbuf *nam, 368 struct mbuf *control, struct lwp *l) 369 { 370 struct unpcb *unp = sotounpcb(so); 371 struct socket *so2; 372 struct proc *p; 373 u_int newhiwat; 374 int error = 0; 375 376 if (req == PRU_CONTROL) 377 return (EOPNOTSUPP); 378 379 #ifdef DIAGNOSTIC 380 if (req != PRU_SEND && req != PRU_SENDOOB && control) 381 panic("uipc_usrreq: unexpected control mbuf"); 382 #endif 383 p = l ? l->l_proc : NULL; 384 if (req != PRU_ATTACH) { 385 if (unp == NULL) { 386 error = EINVAL; 387 goto release; 388 } 389 KASSERT(solocked(so)); 390 } 391 392 switch (req) { 393 394 case PRU_ATTACH: 395 if (unp != NULL) { 396 error = EISCONN; 397 break; 398 } 399 error = unp_attach(so); 400 break; 401 402 case PRU_DETACH: 403 unp_detach(unp); 404 break; 405 406 case PRU_BIND: 407 KASSERT(l != NULL); 408 error = unp_bind(so, nam, l); 409 break; 410 411 case PRU_LISTEN: 412 /* 413 * If the socket can accept a connection, it must be 414 * locked by uipc_lock. 415 */ 416 unp_resetlock(so); 417 if (unp->unp_vnode == NULL) 418 error = EINVAL; 419 break; 420 421 case PRU_CONNECT: 422 KASSERT(l != NULL); 423 error = unp_connect(so, nam, l); 424 break; 425 426 case PRU_CONNECT2: 427 error = unp_connect2(so, (struct socket *)nam, PRU_CONNECT2); 428 break; 429 430 case PRU_DISCONNECT: 431 unp_disconnect(unp); 432 break; 433 434 case PRU_ACCEPT: 435 KASSERT(so->so_lock == uipc_lock); 436 /* 437 * Mark the initiating STREAM socket as connected *ONLY* 438 * after it's been accepted. This prevents a client from 439 * overrunning a server and receiving ECONNREFUSED. 440 */ 441 if (unp->unp_conn == NULL) 442 break; 443 so2 = unp->unp_conn->unp_socket; 444 if (so2->so_state & SS_ISCONNECTING) { 445 KASSERT(solocked2(so, so->so_head)); 446 KASSERT(solocked2(so2, so->so_head)); 447 soisconnected(so2); 448 } 449 /* 450 * If the connection is fully established, break the 451 * association with uipc_lock and give the connected 452 * pair a seperate lock to share. 453 * There is a race here: sotounpcb(so2)->unp_streamlock 454 * is not locked, so when changing so2->so_lock 455 * another thread can grab it while so->so_lock is still 456 * pointing to the (locked) uipc_lock. 457 * this should be harmless, except that this makes 458 * solocked2() and solocked() unreliable. 459 * Another problem is that unp_setaddr() expects the 460 * the socket locked. Grabing sotounpcb(so2)->unp_streamlock 461 * fixes both issues. 462 */ 463 mutex_enter(sotounpcb(so2)->unp_streamlock); 464 unp_setpeerlocks(so2, so); 465 /* 466 * Only now return peer's address, as we may need to 467 * block in order to allocate memory. 468 * 469 * XXX Minor race: connection can be broken while 470 * lock is dropped in unp_setaddr(). We will return 471 * error == 0 and sun_noname as the peer address. 472 */ 473 unp_setaddr(so, nam, true); 474 /* so_lock now points to unp_streamlock */ 475 mutex_exit(so2->so_lock); 476 break; 477 478 case PRU_SHUTDOWN: 479 socantsendmore(so); 480 unp_shutdown(unp); 481 break; 482 483 case PRU_RCVD: 484 switch (so->so_type) { 485 486 case SOCK_DGRAM: 487 panic("uipc 1"); 488 /*NOTREACHED*/ 489 490 case SOCK_SEQPACKET: /* FALLTHROUGH */ 491 case SOCK_STREAM: 492 #define rcv (&so->so_rcv) 493 #define snd (&so2->so_snd) 494 if (unp->unp_conn == 0) 495 break; 496 so2 = unp->unp_conn->unp_socket; 497 KASSERT(solocked2(so, so2)); 498 /* 499 * Adjust backpressure on sender 500 * and wakeup any waiting to write. 501 */ 502 snd->sb_mbmax += unp->unp_mbcnt - rcv->sb_mbcnt; 503 unp->unp_mbcnt = rcv->sb_mbcnt; 504 newhiwat = snd->sb_hiwat + unp->unp_cc - rcv->sb_cc; 505 (void)chgsbsize(so2->so_uidinfo, 506 &snd->sb_hiwat, newhiwat, RLIM_INFINITY); 507 unp->unp_cc = rcv->sb_cc; 508 sowwakeup(so2); 509 #undef snd 510 #undef rcv 511 break; 512 513 default: 514 panic("uipc 2"); 515 } 516 break; 517 518 case PRU_SEND: 519 /* 520 * Note: unp_internalize() rejects any control message 521 * other than SCM_RIGHTS, and only allows one. This 522 * has the side-effect of preventing a caller from 523 * forging SCM_CREDS. 524 */ 525 if (control) { 526 sounlock(so); 527 error = unp_internalize(&control); 528 solock(so); 529 if (error != 0) { 530 m_freem(control); 531 m_freem(m); 532 break; 533 } 534 } 535 switch (so->so_type) { 536 537 case SOCK_DGRAM: { 538 KASSERT(so->so_lock == uipc_lock); 539 if (nam) { 540 if ((so->so_state & SS_ISCONNECTED) != 0) 541 error = EISCONN; 542 else { 543 /* 544 * Note: once connected, the 545 * socket's lock must not be 546 * dropped until we have sent 547 * the message and disconnected. 548 * This is necessary to prevent 549 * intervening control ops, like 550 * another connection. 551 */ 552 error = unp_connect(so, nam, l); 553 } 554 } else { 555 if ((so->so_state & SS_ISCONNECTED) == 0) 556 error = ENOTCONN; 557 } 558 if (error) { 559 unp_dispose(control); 560 m_freem(control); 561 m_freem(m); 562 break; 563 } 564 KASSERT(p != NULL); 565 error = unp_output(m, control, unp, l); 566 if (nam) 567 unp_disconnect(unp); 568 break; 569 } 570 571 case SOCK_SEQPACKET: /* FALLTHROUGH */ 572 case SOCK_STREAM: 573 #define rcv (&so2->so_rcv) 574 #define snd (&so->so_snd) 575 if (unp->unp_conn == NULL) { 576 error = ENOTCONN; 577 break; 578 } 579 so2 = unp->unp_conn->unp_socket; 580 KASSERT(solocked2(so, so2)); 581 if (unp->unp_conn->unp_flags & UNP_WANTCRED) { 582 /* 583 * Credentials are passed only once on 584 * SOCK_STREAM and SOCK_SEQPACKET. 585 */ 586 unp->unp_conn->unp_flags &= ~UNP_WANTCRED; 587 control = unp_addsockcred(l, control); 588 } 589 /* 590 * Send to paired receive port, and then reduce 591 * send buffer hiwater marks to maintain backpressure. 592 * Wake up readers. 593 */ 594 if (control) { 595 if (sbappendcontrol(rcv, m, control) != 0) 596 control = NULL; 597 } else { 598 switch(so->so_type) { 599 case SOCK_SEQPACKET: 600 sbappendrecord(rcv, m); 601 break; 602 case SOCK_STREAM: 603 sbappend(rcv, m); 604 break; 605 default: 606 panic("uipc_usrreq"); 607 break; 608 } 609 } 610 snd->sb_mbmax -= 611 rcv->sb_mbcnt - unp->unp_conn->unp_mbcnt; 612 unp->unp_conn->unp_mbcnt = rcv->sb_mbcnt; 613 newhiwat = snd->sb_hiwat - 614 (rcv->sb_cc - unp->unp_conn->unp_cc); 615 (void)chgsbsize(so->so_uidinfo, 616 &snd->sb_hiwat, newhiwat, RLIM_INFINITY); 617 unp->unp_conn->unp_cc = rcv->sb_cc; 618 sorwakeup(so2); 619 #undef snd 620 #undef rcv 621 if (control != NULL) { 622 unp_dispose(control); 623 m_freem(control); 624 } 625 break; 626 627 default: 628 panic("uipc 4"); 629 } 630 break; 631 632 case PRU_ABORT: 633 (void)unp_drop(unp, ECONNABORTED); 634 635 KASSERT(so->so_head == NULL); 636 #ifdef DIAGNOSTIC 637 if (so->so_pcb == NULL) 638 panic("uipc 5: drop killed pcb"); 639 #endif 640 unp_detach(unp); 641 break; 642 643 case PRU_SENSE: 644 ((struct stat *) m)->st_blksize = so->so_snd.sb_hiwat; 645 switch (so->so_type) { 646 case SOCK_SEQPACKET: /* FALLTHROUGH */ 647 case SOCK_STREAM: 648 if (unp->unp_conn == 0) 649 break; 650 651 so2 = unp->unp_conn->unp_socket; 652 KASSERT(solocked2(so, so2)); 653 ((struct stat *) m)->st_blksize += so2->so_rcv.sb_cc; 654 break; 655 default: 656 break; 657 } 658 ((struct stat *) m)->st_dev = NODEV; 659 if (unp->unp_ino == 0) 660 unp->unp_ino = unp_ino++; 661 ((struct stat *) m)->st_atimespec = 662 ((struct stat *) m)->st_mtimespec = 663 ((struct stat *) m)->st_ctimespec = unp->unp_ctime; 664 ((struct stat *) m)->st_ino = unp->unp_ino; 665 return (0); 666 667 case PRU_RCVOOB: 668 error = EOPNOTSUPP; 669 break; 670 671 case PRU_SENDOOB: 672 m_freem(control); 673 m_freem(m); 674 error = EOPNOTSUPP; 675 break; 676 677 case PRU_SOCKADDR: 678 unp_setaddr(so, nam, false); 679 break; 680 681 case PRU_PEERADDR: 682 unp_setaddr(so, nam, true); 683 break; 684 685 default: 686 panic("piusrreq"); 687 } 688 689 release: 690 return (error); 691 } 692 693 /* 694 * Unix domain socket option processing. 695 */ 696 int 697 uipc_ctloutput(int op, struct socket *so, struct sockopt *sopt) 698 { 699 struct unpcb *unp = sotounpcb(so); 700 int optval = 0, error = 0; 701 702 KASSERT(solocked(so)); 703 704 if (sopt->sopt_level != 0) { 705 error = ENOPROTOOPT; 706 } else switch (op) { 707 708 case PRCO_SETOPT: 709 switch (sopt->sopt_name) { 710 case LOCAL_CREDS: 711 case LOCAL_CONNWAIT: 712 error = sockopt_getint(sopt, &optval); 713 if (error) 714 break; 715 switch (sopt->sopt_name) { 716 #define OPTSET(bit) \ 717 if (optval) \ 718 unp->unp_flags |= (bit); \ 719 else \ 720 unp->unp_flags &= ~(bit); 721 722 case LOCAL_CREDS: 723 OPTSET(UNP_WANTCRED); 724 break; 725 case LOCAL_CONNWAIT: 726 OPTSET(UNP_CONNWAIT); 727 break; 728 } 729 break; 730 #undef OPTSET 731 732 default: 733 error = ENOPROTOOPT; 734 break; 735 } 736 break; 737 738 case PRCO_GETOPT: 739 sounlock(so); 740 switch (sopt->sopt_name) { 741 case LOCAL_PEEREID: 742 if (unp->unp_flags & UNP_EIDSVALID) { 743 error = sockopt_set(sopt, 744 &unp->unp_connid, sizeof(unp->unp_connid)); 745 } else { 746 error = EINVAL; 747 } 748 break; 749 case LOCAL_CREDS: 750 #define OPTBIT(bit) (unp->unp_flags & (bit) ? 1 : 0) 751 752 optval = OPTBIT(UNP_WANTCRED); 753 error = sockopt_setint(sopt, optval); 754 break; 755 #undef OPTBIT 756 757 default: 758 error = ENOPROTOOPT; 759 break; 760 } 761 solock(so); 762 break; 763 } 764 return (error); 765 } 766 767 /* 768 * Both send and receive buffers are allocated PIPSIZ bytes of buffering 769 * for stream sockets, although the total for sender and receiver is 770 * actually only PIPSIZ. 771 * Datagram sockets really use the sendspace as the maximum datagram size, 772 * and don't really want to reserve the sendspace. Their recvspace should 773 * be large enough for at least one max-size datagram plus address. 774 */ 775 #define PIPSIZ 4096 776 u_long unpst_sendspace = PIPSIZ; 777 u_long unpst_recvspace = PIPSIZ; 778 u_long unpdg_sendspace = 2*1024; /* really max datagram size */ 779 u_long unpdg_recvspace = 4*1024; 780 781 u_int unp_rights; /* files in flight */ 782 u_int unp_rights_ratio = 2; /* limit, fraction of maxfiles */ 783 784 int 785 unp_attach(struct socket *so) 786 { 787 struct unpcb *unp; 788 int error; 789 790 switch (so->so_type) { 791 case SOCK_SEQPACKET: /* FALLTHROUGH */ 792 case SOCK_STREAM: 793 if (so->so_lock == NULL) { 794 /* 795 * XXX Assuming that no socket locks are held, 796 * as this call may sleep. 797 */ 798 so->so_lock = mutex_obj_alloc(MUTEX_DEFAULT, IPL_NONE); 799 solock(so); 800 } 801 if (so->so_snd.sb_hiwat == 0 || so->so_rcv.sb_hiwat == 0) { 802 error = soreserve(so, unpst_sendspace, unpst_recvspace); 803 if (error != 0) 804 return (error); 805 } 806 break; 807 808 case SOCK_DGRAM: 809 if (so->so_lock == NULL) { 810 mutex_obj_hold(uipc_lock); 811 so->so_lock = uipc_lock; 812 solock(so); 813 } 814 if (so->so_snd.sb_hiwat == 0 || so->so_rcv.sb_hiwat == 0) { 815 error = soreserve(so, unpdg_sendspace, unpdg_recvspace); 816 if (error != 0) 817 return (error); 818 } 819 break; 820 821 default: 822 panic("unp_attach"); 823 } 824 KASSERT(solocked(so)); 825 unp = malloc(sizeof(*unp), M_PCB, M_NOWAIT); 826 if (unp == NULL) 827 return (ENOBUFS); 828 memset(unp, 0, sizeof(*unp)); 829 unp->unp_socket = so; 830 so->so_pcb = unp; 831 nanotime(&unp->unp_ctime); 832 return (0); 833 } 834 835 void 836 unp_detach(struct unpcb *unp) 837 { 838 struct socket *so; 839 vnode_t *vp; 840 841 so = unp->unp_socket; 842 843 retry: 844 if ((vp = unp->unp_vnode) != NULL) { 845 sounlock(so); 846 /* Acquire v_interlock to protect against unp_connect(). */ 847 /* XXXAD racy */ 848 mutex_enter(vp->v_interlock); 849 vp->v_socket = NULL; 850 vrelel(vp, 0); 851 solock(so); 852 unp->unp_vnode = NULL; 853 } 854 if (unp->unp_conn) 855 unp_disconnect(unp); 856 while (unp->unp_refs) { 857 KASSERT(solocked2(so, unp->unp_refs->unp_socket)); 858 if (unp_drop(unp->unp_refs, ECONNRESET)) { 859 solock(so); 860 goto retry; 861 } 862 } 863 soisdisconnected(so); 864 so->so_pcb = NULL; 865 if (unp_rights) { 866 /* 867 * Normally the receive buffer is flushed later, in sofree, 868 * but if our receive buffer holds references to files that 869 * are now garbage, we will enqueue those file references to 870 * the garbage collector and kick it into action. 871 */ 872 sorflush(so); 873 unp_free(unp); 874 unp_thread_kick(); 875 } else 876 unp_free(unp); 877 } 878 879 int 880 unp_bind(struct socket *so, struct mbuf *nam, struct lwp *l) 881 { 882 struct sockaddr_un *sun; 883 struct unpcb *unp; 884 vnode_t *vp; 885 struct vattr vattr; 886 size_t addrlen; 887 int error; 888 struct pathbuf *pb; 889 struct nameidata nd; 890 proc_t *p; 891 892 unp = sotounpcb(so); 893 if (unp->unp_vnode != NULL) 894 return (EINVAL); 895 if ((unp->unp_flags & UNP_BUSY) != 0) { 896 /* 897 * EALREADY may not be strictly accurate, but since this 898 * is a major application error it's hardly a big deal. 899 */ 900 return (EALREADY); 901 } 902 unp->unp_flags |= UNP_BUSY; 903 sounlock(so); 904 905 /* 906 * Allocate the new sockaddr. We have to allocate one 907 * extra byte so that we can ensure that the pathname 908 * is nul-terminated. 909 */ 910 p = l->l_proc; 911 addrlen = nam->m_len + 1; 912 sun = malloc(addrlen, M_SONAME, M_WAITOK); 913 m_copydata(nam, 0, nam->m_len, (void *)sun); 914 *(((char *)sun) + nam->m_len) = '\0'; 915 916 pb = pathbuf_create(sun->sun_path); 917 if (pb == NULL) { 918 error = ENOMEM; 919 goto bad; 920 } 921 NDINIT(&nd, CREATE, FOLLOW | LOCKPARENT | TRYEMULROOT, pb); 922 923 /* SHOULD BE ABLE TO ADOPT EXISTING AND wakeup() ALA FIFO's */ 924 if ((error = namei(&nd)) != 0) { 925 pathbuf_destroy(pb); 926 goto bad; 927 } 928 vp = nd.ni_vp; 929 if (vp != NULL) { 930 VOP_ABORTOP(nd.ni_dvp, &nd.ni_cnd); 931 if (nd.ni_dvp == vp) 932 vrele(nd.ni_dvp); 933 else 934 vput(nd.ni_dvp); 935 vrele(vp); 936 pathbuf_destroy(pb); 937 error = EADDRINUSE; 938 goto bad; 939 } 940 vattr_null(&vattr); 941 vattr.va_type = VSOCK; 942 vattr.va_mode = ACCESSPERMS & ~(p->p_cwdi->cwdi_cmask); 943 error = VOP_CREATE(nd.ni_dvp, &nd.ni_vp, &nd.ni_cnd, &vattr); 944 if (error) { 945 pathbuf_destroy(pb); 946 goto bad; 947 } 948 vp = nd.ni_vp; 949 solock(so); 950 vp->v_socket = unp->unp_socket; 951 unp->unp_vnode = vp; 952 unp->unp_addrlen = addrlen; 953 unp->unp_addr = sun; 954 unp->unp_connid.unp_pid = p->p_pid; 955 unp->unp_connid.unp_euid = kauth_cred_geteuid(l->l_cred); 956 unp->unp_connid.unp_egid = kauth_cred_getegid(l->l_cred); 957 unp->unp_flags |= UNP_EIDSBIND; 958 VOP_UNLOCK(vp); 959 unp->unp_flags &= ~UNP_BUSY; 960 pathbuf_destroy(pb); 961 return (0); 962 963 bad: 964 free(sun, M_SONAME); 965 solock(so); 966 unp->unp_flags &= ~UNP_BUSY; 967 return (error); 968 } 969 970 int 971 unp_connect(struct socket *so, struct mbuf *nam, struct lwp *l) 972 { 973 struct sockaddr_un *sun; 974 vnode_t *vp; 975 struct socket *so2, *so3; 976 struct unpcb *unp, *unp2, *unp3; 977 size_t addrlen; 978 int error; 979 struct pathbuf *pb; 980 struct nameidata nd; 981 982 unp = sotounpcb(so); 983 if ((unp->unp_flags & UNP_BUSY) != 0) { 984 /* 985 * EALREADY may not be strictly accurate, but since this 986 * is a major application error it's hardly a big deal. 987 */ 988 return (EALREADY); 989 } 990 unp->unp_flags |= UNP_BUSY; 991 sounlock(so); 992 993 /* 994 * Allocate a temporary sockaddr. We have to allocate one extra 995 * byte so that we can ensure that the pathname is nul-terminated. 996 * When we establish the connection, we copy the other PCB's 997 * sockaddr to our own. 998 */ 999 addrlen = nam->m_len + 1; 1000 sun = malloc(addrlen, M_SONAME, M_WAITOK); 1001 m_copydata(nam, 0, nam->m_len, (void *)sun); 1002 *(((char *)sun) + nam->m_len) = '\0'; 1003 1004 pb = pathbuf_create(sun->sun_path); 1005 if (pb == NULL) { 1006 error = ENOMEM; 1007 goto bad2; 1008 } 1009 1010 NDINIT(&nd, LOOKUP, FOLLOW | LOCKLEAF | TRYEMULROOT, pb); 1011 1012 if ((error = namei(&nd)) != 0) { 1013 pathbuf_destroy(pb); 1014 goto bad2; 1015 } 1016 vp = nd.ni_vp; 1017 if (vp->v_type != VSOCK) { 1018 error = ENOTSOCK; 1019 goto bad; 1020 } 1021 pathbuf_destroy(pb); 1022 if ((error = VOP_ACCESS(vp, VWRITE, l->l_cred)) != 0) 1023 goto bad; 1024 /* Acquire v_interlock to protect against unp_detach(). */ 1025 mutex_enter(vp->v_interlock); 1026 so2 = vp->v_socket; 1027 if (so2 == NULL) { 1028 mutex_exit(vp->v_interlock); 1029 error = ECONNREFUSED; 1030 goto bad; 1031 } 1032 if (so->so_type != so2->so_type) { 1033 mutex_exit(vp->v_interlock); 1034 error = EPROTOTYPE; 1035 goto bad; 1036 } 1037 solock(so); 1038 unp_resetlock(so); 1039 mutex_exit(vp->v_interlock); 1040 if ((so->so_proto->pr_flags & PR_CONNREQUIRED) != 0) { 1041 /* 1042 * This may seem somewhat fragile but is OK: if we can 1043 * see SO_ACCEPTCONN set on the endpoint, then it must 1044 * be locked by the domain-wide uipc_lock. 1045 */ 1046 KASSERT((so2->so_options & SO_ACCEPTCONN) == 0 || 1047 so2->so_lock == uipc_lock); 1048 if ((so2->so_options & SO_ACCEPTCONN) == 0 || 1049 (so3 = sonewconn(so2, 0)) == NULL) { 1050 error = ECONNREFUSED; 1051 sounlock(so); 1052 goto bad; 1053 } 1054 unp2 = sotounpcb(so2); 1055 unp3 = sotounpcb(so3); 1056 if (unp2->unp_addr) { 1057 unp3->unp_addr = malloc(unp2->unp_addrlen, 1058 M_SONAME, M_WAITOK); 1059 memcpy(unp3->unp_addr, unp2->unp_addr, 1060 unp2->unp_addrlen); 1061 unp3->unp_addrlen = unp2->unp_addrlen; 1062 } 1063 unp3->unp_flags = unp2->unp_flags; 1064 unp3->unp_connid.unp_pid = l->l_proc->p_pid; 1065 unp3->unp_connid.unp_euid = kauth_cred_geteuid(l->l_cred); 1066 unp3->unp_connid.unp_egid = kauth_cred_getegid(l->l_cred); 1067 unp3->unp_flags |= UNP_EIDSVALID; 1068 if (unp2->unp_flags & UNP_EIDSBIND) { 1069 unp->unp_connid = unp2->unp_connid; 1070 unp->unp_flags |= UNP_EIDSVALID; 1071 } 1072 so2 = so3; 1073 } 1074 error = unp_connect2(so, so2, PRU_CONNECT); 1075 sounlock(so); 1076 bad: 1077 vput(vp); 1078 bad2: 1079 free(sun, M_SONAME); 1080 solock(so); 1081 unp->unp_flags &= ~UNP_BUSY; 1082 return (error); 1083 } 1084 1085 int 1086 unp_connect2(struct socket *so, struct socket *so2, int req) 1087 { 1088 struct unpcb *unp = sotounpcb(so); 1089 struct unpcb *unp2; 1090 1091 if (so2->so_type != so->so_type) 1092 return (EPROTOTYPE); 1093 1094 /* 1095 * All three sockets involved must be locked by same lock: 1096 * 1097 * local endpoint (so) 1098 * remote endpoint (so2) 1099 * queue head (so2->so_head, only if PR_CONNREQUIRED) 1100 */ 1101 KASSERT(solocked2(so, so2)); 1102 KASSERT(so->so_head == NULL); 1103 if (so2->so_head != NULL) { 1104 KASSERT(so2->so_lock == uipc_lock); 1105 KASSERT(solocked2(so2, so2->so_head)); 1106 } 1107 1108 unp2 = sotounpcb(so2); 1109 unp->unp_conn = unp2; 1110 switch (so->so_type) { 1111 1112 case SOCK_DGRAM: 1113 unp->unp_nextref = unp2->unp_refs; 1114 unp2->unp_refs = unp; 1115 soisconnected(so); 1116 break; 1117 1118 case SOCK_SEQPACKET: /* FALLTHROUGH */ 1119 case SOCK_STREAM: 1120 unp2->unp_conn = unp; 1121 if (req == PRU_CONNECT && 1122 ((unp->unp_flags | unp2->unp_flags) & UNP_CONNWAIT)) 1123 soisconnecting(so); 1124 else 1125 soisconnected(so); 1126 soisconnected(so2); 1127 /* 1128 * If the connection is fully established, break the 1129 * association with uipc_lock and give the connected 1130 * pair a seperate lock to share. For CONNECT2, we 1131 * require that the locks already match (the sockets 1132 * are created that way). 1133 */ 1134 if (req == PRU_CONNECT) { 1135 KASSERT(so2->so_head != NULL); 1136 unp_setpeerlocks(so, so2); 1137 } 1138 break; 1139 1140 default: 1141 panic("unp_connect2"); 1142 } 1143 return (0); 1144 } 1145 1146 void 1147 unp_disconnect(struct unpcb *unp) 1148 { 1149 struct unpcb *unp2 = unp->unp_conn; 1150 struct socket *so; 1151 1152 if (unp2 == 0) 1153 return; 1154 unp->unp_conn = 0; 1155 so = unp->unp_socket; 1156 switch (so->so_type) { 1157 case SOCK_DGRAM: 1158 if (unp2->unp_refs == unp) 1159 unp2->unp_refs = unp->unp_nextref; 1160 else { 1161 unp2 = unp2->unp_refs; 1162 for (;;) { 1163 KASSERT(solocked2(so, unp2->unp_socket)); 1164 if (unp2 == 0) 1165 panic("unp_disconnect"); 1166 if (unp2->unp_nextref == unp) 1167 break; 1168 unp2 = unp2->unp_nextref; 1169 } 1170 unp2->unp_nextref = unp->unp_nextref; 1171 } 1172 unp->unp_nextref = 0; 1173 so->so_state &= ~SS_ISCONNECTED; 1174 break; 1175 1176 case SOCK_SEQPACKET: /* FALLTHROUGH */ 1177 case SOCK_STREAM: 1178 KASSERT(solocked2(so, unp2->unp_socket)); 1179 soisdisconnected(so); 1180 unp2->unp_conn = 0; 1181 soisdisconnected(unp2->unp_socket); 1182 break; 1183 } 1184 } 1185 1186 #ifdef notdef 1187 unp_abort(struct unpcb *unp) 1188 { 1189 unp_detach(unp); 1190 } 1191 #endif 1192 1193 void 1194 unp_shutdown(struct unpcb *unp) 1195 { 1196 struct socket *so; 1197 1198 switch(unp->unp_socket->so_type) { 1199 case SOCK_SEQPACKET: /* FALLTHROUGH */ 1200 case SOCK_STREAM: 1201 if (unp->unp_conn && (so = unp->unp_conn->unp_socket)) 1202 socantrcvmore(so); 1203 break; 1204 default: 1205 break; 1206 } 1207 } 1208 1209 bool 1210 unp_drop(struct unpcb *unp, int errno) 1211 { 1212 struct socket *so = unp->unp_socket; 1213 1214 KASSERT(solocked(so)); 1215 1216 so->so_error = errno; 1217 unp_disconnect(unp); 1218 if (so->so_head) { 1219 so->so_pcb = NULL; 1220 /* sofree() drops the socket lock */ 1221 sofree(so); 1222 unp_free(unp); 1223 return true; 1224 } 1225 return false; 1226 } 1227 1228 #ifdef notdef 1229 unp_drain(void) 1230 { 1231 1232 } 1233 #endif 1234 1235 int 1236 unp_externalize(struct mbuf *rights, struct lwp *l, int flags) 1237 { 1238 struct cmsghdr *cm = mtod(rights, struct cmsghdr *); 1239 struct proc *p = l->l_proc; 1240 int i, *fdp; 1241 file_t **rp; 1242 file_t *fp; 1243 int nfds, error = 0; 1244 1245 nfds = (cm->cmsg_len - CMSG_ALIGN(sizeof(*cm))) / 1246 sizeof(file_t *); 1247 rp = (file_t **)CMSG_DATA(cm); 1248 1249 fdp = malloc(nfds * sizeof(int), M_TEMP, M_WAITOK); 1250 rw_enter(&p->p_cwdi->cwdi_lock, RW_READER); 1251 1252 /* Make sure the recipient should be able to see the files.. */ 1253 if (p->p_cwdi->cwdi_rdir != NULL) { 1254 rp = (file_t **)CMSG_DATA(cm); 1255 for (i = 0; i < nfds; i++) { 1256 fp = *rp++; 1257 /* 1258 * If we are in a chroot'ed directory, and 1259 * someone wants to pass us a directory, make 1260 * sure it's inside the subtree we're allowed 1261 * to access. 1262 */ 1263 if (fp->f_type == DTYPE_VNODE) { 1264 vnode_t *vp = (vnode_t *)fp->f_data; 1265 if ((vp->v_type == VDIR) && 1266 !vn_isunder(vp, p->p_cwdi->cwdi_rdir, l)) { 1267 error = EPERM; 1268 break; 1269 } 1270 } 1271 } 1272 } 1273 1274 restart: 1275 rp = (file_t **)CMSG_DATA(cm); 1276 if (error != 0) { 1277 for (i = 0; i < nfds; i++) { 1278 fp = *rp; 1279 *rp++ = 0; 1280 unp_discard_now(fp); 1281 } 1282 goto out; 1283 } 1284 1285 /* 1286 * First loop -- allocate file descriptor table slots for the 1287 * new files. 1288 */ 1289 for (i = 0; i < nfds; i++) { 1290 fp = *rp++; 1291 if ((error = fd_alloc(p, 0, &fdp[i])) != 0) { 1292 /* 1293 * Back out what we've done so far. 1294 */ 1295 for (--i; i >= 0; i--) { 1296 fd_abort(p, NULL, fdp[i]); 1297 } 1298 if (error == ENOSPC) { 1299 fd_tryexpand(p); 1300 error = 0; 1301 } else { 1302 /* 1303 * This is the error that has historically 1304 * been returned, and some callers may 1305 * expect it. 1306 */ 1307 error = EMSGSIZE; 1308 } 1309 goto restart; 1310 } 1311 } 1312 1313 /* 1314 * Now that adding them has succeeded, update all of the 1315 * file passing state and affix the descriptors. 1316 */ 1317 rp = (file_t **)CMSG_DATA(cm); 1318 for (i = 0; i < nfds; i++) { 1319 int fd = fdp[i]; 1320 fp = *rp++; 1321 atomic_dec_uint(&unp_rights); 1322 fd_set_exclose(l, fd, (flags & O_CLOEXEC) != 0); 1323 fd_affix(p, fp, fd); 1324 mutex_enter(&fp->f_lock); 1325 fp->f_msgcount--; 1326 mutex_exit(&fp->f_lock); 1327 /* 1328 * Note that fd_affix() adds a reference to the file. 1329 * The file may already have been closed by another 1330 * LWP in the process, so we must drop the reference 1331 * added by unp_internalize() with closef(). 1332 */ 1333 closef(fp); 1334 } 1335 1336 /* 1337 * Copy temporary array to message and adjust length, in case of 1338 * transition from large file_t pointers to ints. 1339 */ 1340 memcpy(CMSG_DATA(cm), fdp, nfds * sizeof(int)); 1341 cm->cmsg_len = CMSG_LEN(nfds * sizeof(int)); 1342 rights->m_len = CMSG_SPACE(nfds * sizeof(int)); 1343 out: 1344 rw_exit(&p->p_cwdi->cwdi_lock); 1345 free(fdp, M_TEMP); 1346 return (error); 1347 } 1348 1349 int 1350 unp_internalize(struct mbuf **controlp) 1351 { 1352 filedesc_t *fdescp = curlwp->l_fd; 1353 struct mbuf *control = *controlp; 1354 struct cmsghdr *newcm, *cm = mtod(control, struct cmsghdr *); 1355 file_t **rp, **files; 1356 file_t *fp; 1357 int i, fd, *fdp; 1358 int nfds, error; 1359 u_int maxmsg; 1360 1361 error = 0; 1362 newcm = NULL; 1363 1364 /* Sanity check the control message header. */ 1365 if (cm->cmsg_type != SCM_RIGHTS || cm->cmsg_level != SOL_SOCKET || 1366 cm->cmsg_len > control->m_len || 1367 cm->cmsg_len < CMSG_ALIGN(sizeof(*cm))) 1368 return (EINVAL); 1369 1370 /* 1371 * Verify that the file descriptors are valid, and acquire 1372 * a reference to each. 1373 */ 1374 nfds = (cm->cmsg_len - CMSG_ALIGN(sizeof(*cm))) / sizeof(int); 1375 fdp = (int *)CMSG_DATA(cm); 1376 maxmsg = maxfiles / unp_rights_ratio; 1377 for (i = 0; i < nfds; i++) { 1378 fd = *fdp++; 1379 if (atomic_inc_uint_nv(&unp_rights) > maxmsg) { 1380 atomic_dec_uint(&unp_rights); 1381 nfds = i; 1382 error = EAGAIN; 1383 goto out; 1384 } 1385 if ((fp = fd_getfile(fd)) == NULL) { 1386 atomic_dec_uint(&unp_rights); 1387 nfds = i; 1388 error = EBADF; 1389 goto out; 1390 } 1391 } 1392 1393 /* Allocate new space and copy header into it. */ 1394 newcm = malloc(CMSG_SPACE(nfds * sizeof(file_t *)), M_MBUF, M_WAITOK); 1395 if (newcm == NULL) { 1396 error = E2BIG; 1397 goto out; 1398 } 1399 memcpy(newcm, cm, sizeof(struct cmsghdr)); 1400 files = (file_t **)CMSG_DATA(newcm); 1401 1402 /* 1403 * Transform the file descriptors into file_t pointers, in 1404 * reverse order so that if pointers are bigger than ints, the 1405 * int won't get until we're done. No need to lock, as we have 1406 * already validated the descriptors with fd_getfile(). 1407 */ 1408 fdp = (int *)CMSG_DATA(cm) + nfds; 1409 rp = files + nfds; 1410 for (i = 0; i < nfds; i++) { 1411 fp = fdescp->fd_dt->dt_ff[*--fdp]->ff_file; 1412 KASSERT(fp != NULL); 1413 mutex_enter(&fp->f_lock); 1414 *--rp = fp; 1415 fp->f_count++; 1416 fp->f_msgcount++; 1417 mutex_exit(&fp->f_lock); 1418 } 1419 1420 out: 1421 /* Release descriptor references. */ 1422 fdp = (int *)CMSG_DATA(cm); 1423 for (i = 0; i < nfds; i++) { 1424 fd_putfile(*fdp++); 1425 if (error != 0) { 1426 atomic_dec_uint(&unp_rights); 1427 } 1428 } 1429 1430 if (error == 0) { 1431 if (control->m_flags & M_EXT) { 1432 m_freem(control); 1433 *controlp = control = m_get(M_WAIT, MT_CONTROL); 1434 } 1435 MEXTADD(control, newcm, CMSG_SPACE(nfds * sizeof(file_t *)), 1436 M_MBUF, NULL, NULL); 1437 cm = newcm; 1438 /* 1439 * Adjust message & mbuf to note amount of space 1440 * actually used. 1441 */ 1442 cm->cmsg_len = CMSG_LEN(nfds * sizeof(file_t *)); 1443 control->m_len = CMSG_SPACE(nfds * sizeof(file_t *)); 1444 } 1445 1446 return error; 1447 } 1448 1449 struct mbuf * 1450 unp_addsockcred(struct lwp *l, struct mbuf *control) 1451 { 1452 struct cmsghdr *cmp; 1453 struct sockcred *sc; 1454 struct mbuf *m, *n; 1455 int len, space, i; 1456 1457 len = CMSG_LEN(SOCKCREDSIZE(kauth_cred_ngroups(l->l_cred))); 1458 space = CMSG_SPACE(SOCKCREDSIZE(kauth_cred_ngroups(l->l_cred))); 1459 1460 m = m_get(M_WAIT, MT_CONTROL); 1461 if (space > MLEN) { 1462 if (space > MCLBYTES) 1463 MEXTMALLOC(m, space, M_WAITOK); 1464 else 1465 m_clget(m, M_WAIT); 1466 if ((m->m_flags & M_EXT) == 0) { 1467 m_free(m); 1468 return (control); 1469 } 1470 } 1471 1472 m->m_len = space; 1473 m->m_next = NULL; 1474 cmp = mtod(m, struct cmsghdr *); 1475 sc = (struct sockcred *)CMSG_DATA(cmp); 1476 cmp->cmsg_len = len; 1477 cmp->cmsg_level = SOL_SOCKET; 1478 cmp->cmsg_type = SCM_CREDS; 1479 sc->sc_uid = kauth_cred_getuid(l->l_cred); 1480 sc->sc_euid = kauth_cred_geteuid(l->l_cred); 1481 sc->sc_gid = kauth_cred_getgid(l->l_cred); 1482 sc->sc_egid = kauth_cred_getegid(l->l_cred); 1483 sc->sc_ngroups = kauth_cred_ngroups(l->l_cred); 1484 for (i = 0; i < sc->sc_ngroups; i++) 1485 sc->sc_groups[i] = kauth_cred_group(l->l_cred, i); 1486 1487 /* 1488 * If a control message already exists, append us to the end. 1489 */ 1490 if (control != NULL) { 1491 for (n = control; n->m_next != NULL; n = n->m_next) 1492 ; 1493 n->m_next = m; 1494 } else 1495 control = m; 1496 1497 return (control); 1498 } 1499 1500 /* 1501 * Do a mark-sweep GC of files in the system, to free up any which are 1502 * caught in flight to an about-to-be-closed socket. Additionally, 1503 * process deferred file closures. 1504 */ 1505 static void 1506 unp_gc(file_t *dp) 1507 { 1508 extern struct domain unixdomain; 1509 file_t *fp, *np; 1510 struct socket *so, *so1; 1511 u_int i, old, new; 1512 bool didwork; 1513 1514 KASSERT(curlwp == unp_thread_lwp); 1515 KASSERT(mutex_owned(&filelist_lock)); 1516 1517 /* 1518 * First, process deferred file closures. 1519 */ 1520 while (!SLIST_EMPTY(&unp_thread_discard)) { 1521 fp = SLIST_FIRST(&unp_thread_discard); 1522 KASSERT(fp->f_unpcount > 0); 1523 KASSERT(fp->f_count > 0); 1524 KASSERT(fp->f_msgcount > 0); 1525 KASSERT(fp->f_count >= fp->f_unpcount); 1526 KASSERT(fp->f_count >= fp->f_msgcount); 1527 KASSERT(fp->f_msgcount >= fp->f_unpcount); 1528 SLIST_REMOVE_HEAD(&unp_thread_discard, f_unplist); 1529 i = fp->f_unpcount; 1530 fp->f_unpcount = 0; 1531 mutex_exit(&filelist_lock); 1532 for (; i != 0; i--) { 1533 unp_discard_now(fp); 1534 } 1535 mutex_enter(&filelist_lock); 1536 } 1537 1538 /* 1539 * Clear mark bits. Ensure that we don't consider new files 1540 * entering the file table during this loop (they will not have 1541 * FSCAN set). 1542 */ 1543 unp_defer = 0; 1544 LIST_FOREACH(fp, &filehead, f_list) { 1545 for (old = fp->f_flag;; old = new) { 1546 new = atomic_cas_uint(&fp->f_flag, old, 1547 (old | FSCAN) & ~(FMARK|FDEFER)); 1548 if (__predict_true(old == new)) { 1549 break; 1550 } 1551 } 1552 } 1553 1554 /* 1555 * Iterate over the set of sockets, marking ones believed (based on 1556 * refcount) to be referenced from a process, and marking for rescan 1557 * sockets which are queued on a socket. Recan continues descending 1558 * and searching for sockets referenced by sockets (FDEFER), until 1559 * there are no more socket->socket references to be discovered. 1560 */ 1561 do { 1562 didwork = false; 1563 for (fp = LIST_FIRST(&filehead); fp != NULL; fp = np) { 1564 KASSERT(mutex_owned(&filelist_lock)); 1565 np = LIST_NEXT(fp, f_list); 1566 mutex_enter(&fp->f_lock); 1567 if ((fp->f_flag & FDEFER) != 0) { 1568 atomic_and_uint(&fp->f_flag, ~FDEFER); 1569 unp_defer--; 1570 KASSERT(fp->f_count != 0); 1571 } else { 1572 if (fp->f_count == 0 || 1573 (fp->f_flag & FMARK) != 0 || 1574 fp->f_count == fp->f_msgcount || 1575 fp->f_unpcount != 0) { 1576 mutex_exit(&fp->f_lock); 1577 continue; 1578 } 1579 } 1580 atomic_or_uint(&fp->f_flag, FMARK); 1581 1582 if (fp->f_type != DTYPE_SOCKET || 1583 (so = fp->f_data) == NULL || 1584 so->so_proto->pr_domain != &unixdomain || 1585 (so->so_proto->pr_flags & PR_RIGHTS) == 0) { 1586 mutex_exit(&fp->f_lock); 1587 continue; 1588 } 1589 1590 /* Gain file ref, mark our position, and unlock. */ 1591 didwork = true; 1592 LIST_INSERT_AFTER(fp, dp, f_list); 1593 fp->f_count++; 1594 mutex_exit(&fp->f_lock); 1595 mutex_exit(&filelist_lock); 1596 1597 /* 1598 * Mark files referenced from sockets queued on the 1599 * accept queue as well. 1600 */ 1601 solock(so); 1602 unp_scan(so->so_rcv.sb_mb, unp_mark, 0); 1603 if ((so->so_options & SO_ACCEPTCONN) != 0) { 1604 TAILQ_FOREACH(so1, &so->so_q0, so_qe) { 1605 unp_scan(so1->so_rcv.sb_mb, unp_mark, 0); 1606 } 1607 TAILQ_FOREACH(so1, &so->so_q, so_qe) { 1608 unp_scan(so1->so_rcv.sb_mb, unp_mark, 0); 1609 } 1610 } 1611 sounlock(so); 1612 1613 /* Re-lock and restart from where we left off. */ 1614 closef(fp); 1615 mutex_enter(&filelist_lock); 1616 np = LIST_NEXT(dp, f_list); 1617 LIST_REMOVE(dp, f_list); 1618 } 1619 /* 1620 * Bail early if we did nothing in the loop above. Could 1621 * happen because of concurrent activity causing unp_defer 1622 * to get out of sync. 1623 */ 1624 } while (unp_defer != 0 && didwork); 1625 1626 /* 1627 * Sweep pass. 1628 * 1629 * We grab an extra reference to each of the files that are 1630 * not otherwise accessible and then free the rights that are 1631 * stored in messages on them. 1632 */ 1633 for (fp = LIST_FIRST(&filehead); fp != NULL; fp = np) { 1634 KASSERT(mutex_owned(&filelist_lock)); 1635 np = LIST_NEXT(fp, f_list); 1636 mutex_enter(&fp->f_lock); 1637 1638 /* 1639 * Ignore non-sockets. 1640 * Ignore dead sockets, or sockets with pending close. 1641 * Ignore sockets obviously referenced elsewhere. 1642 * Ignore sockets marked as referenced by our scan. 1643 * Ignore new sockets that did not exist during the scan. 1644 */ 1645 if (fp->f_type != DTYPE_SOCKET || 1646 fp->f_count == 0 || fp->f_unpcount != 0 || 1647 fp->f_count != fp->f_msgcount || 1648 (fp->f_flag & (FMARK | FSCAN)) != FSCAN) { 1649 mutex_exit(&fp->f_lock); 1650 continue; 1651 } 1652 1653 /* Gain file ref, mark our position, and unlock. */ 1654 LIST_INSERT_AFTER(fp, dp, f_list); 1655 fp->f_count++; 1656 mutex_exit(&fp->f_lock); 1657 mutex_exit(&filelist_lock); 1658 1659 /* 1660 * Flush all data from the socket's receive buffer. 1661 * This will cause files referenced only by the 1662 * socket to be queued for close. 1663 */ 1664 so = fp->f_data; 1665 solock(so); 1666 sorflush(so); 1667 sounlock(so); 1668 1669 /* Re-lock and restart from where we left off. */ 1670 closef(fp); 1671 mutex_enter(&filelist_lock); 1672 np = LIST_NEXT(dp, f_list); 1673 LIST_REMOVE(dp, f_list); 1674 } 1675 } 1676 1677 /* 1678 * Garbage collector thread. While SCM_RIGHTS messages are in transit, 1679 * wake once per second to garbage collect. Run continually while we 1680 * have deferred closes to process. 1681 */ 1682 static void 1683 unp_thread(void *cookie) 1684 { 1685 file_t *dp; 1686 1687 /* Allocate a dummy file for our scans. */ 1688 if ((dp = fgetdummy()) == NULL) { 1689 panic("unp_thread"); 1690 } 1691 1692 mutex_enter(&filelist_lock); 1693 for (;;) { 1694 KASSERT(mutex_owned(&filelist_lock)); 1695 if (SLIST_EMPTY(&unp_thread_discard)) { 1696 if (unp_rights != 0) { 1697 (void)cv_timedwait(&unp_thread_cv, 1698 &filelist_lock, hz); 1699 } else { 1700 cv_wait(&unp_thread_cv, &filelist_lock); 1701 } 1702 } 1703 unp_gc(dp); 1704 } 1705 /* NOTREACHED */ 1706 } 1707 1708 /* 1709 * Kick the garbage collector into action if there is something for 1710 * it to process. 1711 */ 1712 static void 1713 unp_thread_kick(void) 1714 { 1715 1716 if (!SLIST_EMPTY(&unp_thread_discard) || unp_rights != 0) { 1717 mutex_enter(&filelist_lock); 1718 cv_signal(&unp_thread_cv); 1719 mutex_exit(&filelist_lock); 1720 } 1721 } 1722 1723 void 1724 unp_dispose(struct mbuf *m) 1725 { 1726 1727 if (m) 1728 unp_scan(m, unp_discard_later, 1); 1729 } 1730 1731 void 1732 unp_scan(struct mbuf *m0, void (*op)(file_t *), int discard) 1733 { 1734 struct mbuf *m; 1735 file_t **rp, *fp; 1736 struct cmsghdr *cm; 1737 int i, qfds; 1738 1739 while (m0) { 1740 for (m = m0; m; m = m->m_next) { 1741 if (m->m_type != MT_CONTROL || 1742 m->m_len < sizeof(*cm)) { 1743 continue; 1744 } 1745 cm = mtod(m, struct cmsghdr *); 1746 if (cm->cmsg_level != SOL_SOCKET || 1747 cm->cmsg_type != SCM_RIGHTS) 1748 continue; 1749 qfds = (cm->cmsg_len - CMSG_ALIGN(sizeof(*cm))) 1750 / sizeof(file_t *); 1751 rp = (file_t **)CMSG_DATA(cm); 1752 for (i = 0; i < qfds; i++) { 1753 fp = *rp; 1754 if (discard) { 1755 *rp = 0; 1756 } 1757 (*op)(fp); 1758 rp++; 1759 } 1760 } 1761 m0 = m0->m_nextpkt; 1762 } 1763 } 1764 1765 void 1766 unp_mark(file_t *fp) 1767 { 1768 1769 if (fp == NULL) 1770 return; 1771 1772 /* If we're already deferred, don't screw up the defer count */ 1773 mutex_enter(&fp->f_lock); 1774 if (fp->f_flag & (FMARK | FDEFER)) { 1775 mutex_exit(&fp->f_lock); 1776 return; 1777 } 1778 1779 /* 1780 * Minimize the number of deferrals... Sockets are the only type of 1781 * file which can hold references to another file, so just mark 1782 * other files, and defer unmarked sockets for the next pass. 1783 */ 1784 if (fp->f_type == DTYPE_SOCKET) { 1785 unp_defer++; 1786 KASSERT(fp->f_count != 0); 1787 atomic_or_uint(&fp->f_flag, FDEFER); 1788 } else { 1789 atomic_or_uint(&fp->f_flag, FMARK); 1790 } 1791 mutex_exit(&fp->f_lock); 1792 } 1793 1794 static void 1795 unp_discard_now(file_t *fp) 1796 { 1797 1798 if (fp == NULL) 1799 return; 1800 1801 KASSERT(fp->f_count > 0); 1802 KASSERT(fp->f_msgcount > 0); 1803 1804 mutex_enter(&fp->f_lock); 1805 fp->f_msgcount--; 1806 mutex_exit(&fp->f_lock); 1807 atomic_dec_uint(&unp_rights); 1808 (void)closef(fp); 1809 } 1810 1811 static void 1812 unp_discard_later(file_t *fp) 1813 { 1814 1815 if (fp == NULL) 1816 return; 1817 1818 KASSERT(fp->f_count > 0); 1819 KASSERT(fp->f_msgcount > 0); 1820 1821 mutex_enter(&filelist_lock); 1822 if (fp->f_unpcount++ == 0) { 1823 SLIST_INSERT_HEAD(&unp_thread_discard, fp, f_unplist); 1824 } 1825 mutex_exit(&filelist_lock); 1826 } 1827