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