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