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