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