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