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