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