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