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