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