Deleted Added
full compact
uipc_usrreq.c (157927) uipc_usrreq.c (157999)
1/*-
2 * Copyright (c) 1982, 1986, 1989, 1991, 1993
3 * The Regents of the University of California.
4 * Copyright 2004-2006 Robert N. M. Watson
5 * All rights reserved.
6 *
7 * Redistribution and use in source and binary forms, with or without
8 * modification, are permitted provided that the following conditions
9 * are met:
10 * 1. Redistributions of source code must retain the above copyright
11 * notice, this list of conditions and the following disclaimer.
12 * 2. Redistributions in binary form must reproduce the above copyright
13 * notice, this list of conditions and the following disclaimer in the
14 * documentation and/or other materials provided with the distribution.
15 * 4. Neither the name of the University nor the names of its contributors
16 * may be used to endorse or promote products derived from this software
17 * without specific prior written permission.
18 *
19 * THIS SOFTWARE IS PROVIDED BY THE REGENTS AND CONTRIBUTORS ``AS IS'' AND
20 * ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
21 * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE
22 * ARE DISCLAIMED. IN NO EVENT SHALL THE REGENTS OR CONTRIBUTORS BE LIABLE
23 * FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL
24 * DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS
25 * OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION)
26 * HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT
27 * LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY
28 * OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF
29 * SUCH DAMAGE.
30 *
31 * From: @(#)uipc_usrreq.c 8.3 (Berkeley) 1/4/94
32 */
33
34#include <sys/cdefs.h>
1/*-
2 * Copyright (c) 1982, 1986, 1989, 1991, 1993
3 * The Regents of the University of California.
4 * Copyright 2004-2006 Robert N. M. Watson
5 * All rights reserved.
6 *
7 * Redistribution and use in source and binary forms, with or without
8 * modification, are permitted provided that the following conditions
9 * are met:
10 * 1. Redistributions of source code must retain the above copyright
11 * notice, this list of conditions and the following disclaimer.
12 * 2. Redistributions in binary form must reproduce the above copyright
13 * notice, this list of conditions and the following disclaimer in the
14 * documentation and/or other materials provided with the distribution.
15 * 4. Neither the name of the University nor the names of its contributors
16 * may be used to endorse or promote products derived from this software
17 * without specific prior written permission.
18 *
19 * THIS SOFTWARE IS PROVIDED BY THE REGENTS AND CONTRIBUTORS ``AS IS'' AND
20 * ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
21 * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE
22 * ARE DISCLAIMED. IN NO EVENT SHALL THE REGENTS OR CONTRIBUTORS BE LIABLE
23 * FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL
24 * DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS
25 * OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION)
26 * HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT
27 * LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY
28 * OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF
29 * SUCH DAMAGE.
30 *
31 * From: @(#)uipc_usrreq.c 8.3 (Berkeley) 1/4/94
32 */
33
34#include <sys/cdefs.h>
35__FBSDID("$FreeBSD: head/sys/kern/uipc_usrreq.c 157927 2006-04-21 09:25:40Z ps $");
35__FBSDID("$FreeBSD: head/sys/kern/uipc_usrreq.c 157999 2006-04-24 19:09:33Z maxim $");
36
37#include "opt_mac.h"
38
39#include <sys/param.h>
40#include <sys/domain.h>
41#include <sys/fcntl.h>
42#include <sys/malloc.h> /* XXX must be before <sys/file.h> */
43#include <sys/eventhandler.h>
44#include <sys/file.h>
45#include <sys/filedesc.h>
46#include <sys/jail.h>
47#include <sys/kernel.h>
48#include <sys/lock.h>
49#include <sys/mac.h>
50#include <sys/mbuf.h>
51#include <sys/mount.h>
52#include <sys/mutex.h>
53#include <sys/namei.h>
54#include <sys/proc.h>
55#include <sys/protosw.h>
56#include <sys/resourcevar.h>
57#include <sys/socket.h>
58#include <sys/socketvar.h>
59#include <sys/signalvar.h>
60#include <sys/stat.h>
61#include <sys/sx.h>
62#include <sys/sysctl.h>
63#include <sys/systm.h>
64#include <sys/taskqueue.h>
65#include <sys/un.h>
66#include <sys/unpcb.h>
67#include <sys/vnode.h>
68
69#include <vm/uma.h>
70
71static uma_zone_t unp_zone;
72static unp_gen_t unp_gencnt;
73static u_int unp_count;
74
75static struct unp_head unp_shead, unp_dhead;
76
77/*
78 * Unix communications domain.
79 *
80 * TODO:
81 * SEQPACKET, RDM
82 * rethink name space problems
83 * need a proper out-of-band
84 * lock pushdown
85 */
86static const struct sockaddr sun_noname = { sizeof(sun_noname), AF_LOCAL };
87static ino_t unp_ino; /* prototype for fake inode numbers */
88struct mbuf *unp_addsockcred(struct thread *, struct mbuf *);
89
90/*
91 * Currently, UNIX domain sockets are protected by a single subsystem lock,
92 * which covers global data structures and variables, the contents of each
93 * per-socket unpcb structure, and the so_pcb field in sockets attached to
94 * the UNIX domain. This provides for a moderate degree of paralellism, as
95 * receive operations on UNIX domain sockets do not need to acquire the
96 * subsystem lock. Finer grained locking to permit send() without acquiring
97 * a global lock would be a logical next step.
98 *
99 * The UNIX domain socket lock preceds all socket layer locks, including the
100 * socket lock and socket buffer lock, permitting UNIX domain socket code to
101 * call into socket support routines without releasing its locks.
102 *
103 * Some caution is required in areas where the UNIX domain socket code enters
104 * VFS in order to create or find rendezvous points. This results in
105 * dropping of the UNIX domain socket subsystem lock, acquisition of the
106 * Giant lock, and potential sleeping. This increases the chances of races,
107 * and exposes weaknesses in the socket->protocol API by offering poor
108 * failure modes.
109 */
110static struct mtx unp_mtx;
111#define UNP_LOCK_INIT() \
112 mtx_init(&unp_mtx, "unp", NULL, MTX_DEF)
113#define UNP_LOCK() mtx_lock(&unp_mtx)
114#define UNP_UNLOCK() mtx_unlock(&unp_mtx)
115#define UNP_LOCK_ASSERT() mtx_assert(&unp_mtx, MA_OWNED)
116#define UNP_UNLOCK_ASSERT() mtx_assert(&unp_mtx, MA_NOTOWNED)
117
118/*
119 * Garbage collection of cyclic file descriptor/socket references occurs
120 * asynchronously in a taskqueue context in order to avoid recursion and
121 * reentrance in the UNIX domain socket, file descriptor, and socket layer
122 * code. See unp_gc() for a full description.
123 */
124static struct task unp_gc_task;
125
126static int unp_attach(struct socket *);
127static void unp_detach(struct unpcb *);
128static int unp_bind(struct unpcb *,struct sockaddr *, struct thread *);
129static int unp_connect(struct socket *,struct sockaddr *, struct thread *);
130static int unp_connect2(struct socket *so, struct socket *so2, int);
131static void unp_disconnect(struct unpcb *);
132static void unp_shutdown(struct unpcb *);
133static void unp_drop(struct unpcb *, int);
134static void unp_gc(__unused void *, int);
135static void unp_scan(struct mbuf *, void (*)(struct file *));
136static void unp_mark(struct file *);
137static void unp_discard(struct file *);
138static void unp_freerights(struct file **, int);
139static int unp_internalize(struct mbuf **, struct thread *);
140static int unp_listen(struct socket *, struct unpcb *, int,
141 struct thread *);
142
143static void
144uipc_abort(struct socket *so)
145{
146 struct unpcb *unp;
147
148 unp = sotounpcb(so);
149 KASSERT(unp != NULL, ("uipc_abort: unp == NULL"));
150 UNP_LOCK();
151 unp_drop(unp, ECONNABORTED);
152 unp_detach(unp);
153 UNP_UNLOCK_ASSERT();
154}
155
156static int
157uipc_accept(struct socket *so, struct sockaddr **nam)
158{
159 struct unpcb *unp;
160 const struct sockaddr *sa;
161
162 /*
163 * Pass back name of connected socket,
164 * if it was bound and we are still connected
165 * (our peer may have closed already!).
166 */
167 unp = sotounpcb(so);
168 KASSERT(unp != NULL, ("uipc_accept: unp == NULL"));
169 *nam = malloc(sizeof(struct sockaddr_un), M_SONAME, M_WAITOK);
170 UNP_LOCK();
171 if (unp->unp_conn != NULL && unp->unp_conn->unp_addr != NULL)
172 sa = (struct sockaddr *) unp->unp_conn->unp_addr;
173 else
174 sa = &sun_noname;
175 bcopy(sa, *nam, sa->sa_len);
176 UNP_UNLOCK();
177 return (0);
178}
179
180static int
181uipc_attach(struct socket *so, int proto, struct thread *td)
182{
183
184 return (unp_attach(so));
185}
186
187static int
188uipc_bind(struct socket *so, struct sockaddr *nam, struct thread *td)
189{
190 struct unpcb *unp;
191 int error;
192
193 unp = sotounpcb(so);
194 KASSERT(unp != NULL, ("uipc_bind: unp == NULL"));
195 UNP_LOCK();
196 error = unp_bind(unp, nam, td);
197 UNP_UNLOCK();
198 return (error);
199}
200
201static int
202uipc_connect(struct socket *so, struct sockaddr *nam, struct thread *td)
203{
204 struct unpcb *unp;
205 int error;
206
207 KASSERT(td == curthread, ("uipc_connect: td != curthread"));
208 unp = sotounpcb(so);
209 KASSERT(unp != NULL, ("uipc_connect: unp == NULL"));
210 UNP_LOCK();
211 error = unp_connect(so, nam, td);
212 UNP_UNLOCK();
213 return (error);
214}
215
216int
217uipc_connect2(struct socket *so1, struct socket *so2)
218{
219 struct unpcb *unp;
220 int error;
221
222 unp = sotounpcb(so1);
223 KASSERT(unp != NULL, ("uipc_connect2: unp == NULL"));
224 UNP_LOCK();
225 error = unp_connect2(so1, so2, PRU_CONNECT2);
226 UNP_UNLOCK();
227 return (error);
228}
229
230/* control is EOPNOTSUPP */
231
232static void
233uipc_detach(struct socket *so)
234{
235 struct unpcb *unp;
236
237 unp = sotounpcb(so);
238 KASSERT(unp != NULL, ("uipc_detach: unp == NULL"));
239 UNP_LOCK();
240 unp_detach(unp);
241 UNP_UNLOCK_ASSERT();
242}
243
244static int
245uipc_disconnect(struct socket *so)
246{
247 struct unpcb *unp;
248
249 unp = sotounpcb(so);
250 KASSERT(unp != NULL, ("uipc_disconnect: unp == NULL"));
251 UNP_LOCK();
252 unp_disconnect(unp);
253 UNP_UNLOCK();
254 return (0);
255}
256
257static int
258uipc_listen(struct socket *so, int backlog, struct thread *td)
259{
260 struct unpcb *unp;
261 int error;
262
263 unp = sotounpcb(so);
264 KASSERT(unp != NULL, ("uipc_listen: unp == NULL"));
265 UNP_LOCK();
266 if (unp->unp_vnode == NULL) {
267 UNP_UNLOCK();
268 return (EINVAL);
269 }
270 error = unp_listen(so, unp, backlog, td);
271 UNP_UNLOCK();
272 return (error);
273}
274
275static int
276uipc_peeraddr(struct socket *so, struct sockaddr **nam)
277{
278 struct unpcb *unp;
279 const struct sockaddr *sa;
280
281 unp = sotounpcb(so);
282 KASSERT(unp != NULL, ("uipc_peeraddr: unp == NULL"));
283 *nam = malloc(sizeof(struct sockaddr_un), M_SONAME, M_WAITOK);
284 UNP_LOCK();
285 if (unp->unp_conn != NULL && unp->unp_conn->unp_addr!= NULL)
286 sa = (struct sockaddr *) unp->unp_conn->unp_addr;
287 else {
288 /*
289 * XXX: It seems that this test always fails even when
290 * connection is established. So, this else clause is
291 * added as workaround to return PF_LOCAL sockaddr.
292 */
293 sa = &sun_noname;
294 }
295 bcopy(sa, *nam, sa->sa_len);
296 UNP_UNLOCK();
297 return (0);
298}
299
300static int
301uipc_rcvd(struct socket *so, int flags)
302{
303 struct unpcb *unp;
304 struct socket *so2;
305 u_long newhiwat;
306
307 unp = sotounpcb(so);
308 KASSERT(unp != NULL, ("uipc_rcvd: unp == NULL"));
309 UNP_LOCK();
310 switch (so->so_type) {
311 case SOCK_DGRAM:
312 panic("uipc_rcvd DGRAM?");
313 /*NOTREACHED*/
314
315 case SOCK_STREAM:
316 if (unp->unp_conn == NULL)
317 break;
318 so2 = unp->unp_conn->unp_socket;
319 SOCKBUF_LOCK(&so2->so_snd);
320 SOCKBUF_LOCK(&so->so_rcv);
321 /*
322 * Adjust backpressure on sender
323 * and wakeup any waiting to write.
324 */
325 so2->so_snd.sb_mbmax += unp->unp_mbcnt - so->so_rcv.sb_mbcnt;
326 unp->unp_mbcnt = so->so_rcv.sb_mbcnt;
327 newhiwat = so2->so_snd.sb_hiwat + unp->unp_cc -
328 so->so_rcv.sb_cc;
329 (void)chgsbsize(so2->so_cred->cr_uidinfo, &so2->so_snd.sb_hiwat,
330 newhiwat, RLIM_INFINITY);
331 unp->unp_cc = so->so_rcv.sb_cc;
332 SOCKBUF_UNLOCK(&so->so_rcv);
333 sowwakeup_locked(so2);
334 break;
335
336 default:
337 panic("uipc_rcvd unknown socktype");
338 }
339 UNP_UNLOCK();
340 return (0);
341}
342
343/* pru_rcvoob is EOPNOTSUPP */
344
345static int
346uipc_send(struct socket *so, int flags, struct mbuf *m, struct sockaddr *nam,
347 struct mbuf *control, struct thread *td)
348{
349 int error = 0;
350 struct unpcb *unp;
351 struct socket *so2;
352 u_long newhiwat;
353
354 unp = sotounpcb(so);
355 KASSERT(unp != NULL, ("uipc_send: unp == NULL"));
356 if (flags & PRUS_OOB) {
357 error = EOPNOTSUPP;
358 goto release;
359 }
360
361 if (control != NULL && (error = unp_internalize(&control, td)))
362 goto release;
363
364 UNP_LOCK();
365 switch (so->so_type) {
366 case SOCK_DGRAM:
367 {
368 const struct sockaddr *from;
369
370 if (nam != NULL) {
371 if (unp->unp_conn != NULL) {
372 error = EISCONN;
373 break;
374 }
375 error = unp_connect(so, nam, td);
376 if (error)
377 break;
378 } else {
379 if (unp->unp_conn == NULL) {
380 error = ENOTCONN;
381 break;
382 }
383 }
384 so2 = unp->unp_conn->unp_socket;
385 if (unp->unp_addr != NULL)
386 from = (struct sockaddr *)unp->unp_addr;
387 else
388 from = &sun_noname;
389 if (unp->unp_conn->unp_flags & UNP_WANTCRED)
390 control = unp_addsockcred(td, control);
391 SOCKBUF_LOCK(&so2->so_rcv);
392 if (sbappendaddr_locked(&so2->so_rcv, from, m, control)) {
393 sorwakeup_locked(so2);
394 m = NULL;
395 control = NULL;
396 } else {
397 SOCKBUF_UNLOCK(&so2->so_rcv);
398 error = ENOBUFS;
399 }
400 if (nam != NULL)
401 unp_disconnect(unp);
402 break;
403 }
404
405 case SOCK_STREAM:
406 /* Connect if not connected yet. */
407 /*
408 * Note: A better implementation would complain
409 * if not equal to the peer's address.
410 */
411 if ((so->so_state & SS_ISCONNECTED) == 0) {
412 if (nam != NULL) {
413 error = unp_connect(so, nam, td);
414 if (error)
415 break; /* XXX */
416 } else {
417 error = ENOTCONN;
418 break;
419 }
420 }
421
422 SOCKBUF_LOCK(&so->so_snd);
423 if (so->so_snd.sb_state & SBS_CANTSENDMORE) {
424 SOCKBUF_UNLOCK(&so->so_snd);
425 error = EPIPE;
426 break;
427 }
428 if (unp->unp_conn == NULL)
429 panic("uipc_send connected but no connection?");
430 so2 = unp->unp_conn->unp_socket;
431 SOCKBUF_LOCK(&so2->so_rcv);
432 if (unp->unp_conn->unp_flags & UNP_WANTCRED) {
433 /*
434 * Credentials are passed only once on
435 * SOCK_STREAM.
436 */
437 unp->unp_conn->unp_flags &= ~UNP_WANTCRED;
438 control = unp_addsockcred(td, control);
439 }
440 /*
441 * Send to paired receive port, and then reduce
442 * send buffer hiwater marks to maintain backpressure.
443 * Wake up readers.
444 */
445 if (control != NULL) {
446 if (sbappendcontrol_locked(&so2->so_rcv, m, control))
447 control = NULL;
448 } else {
449 sbappend_locked(&so2->so_rcv, m);
450 }
451 so->so_snd.sb_mbmax -=
452 so2->so_rcv.sb_mbcnt - unp->unp_conn->unp_mbcnt;
453 unp->unp_conn->unp_mbcnt = so2->so_rcv.sb_mbcnt;
454 newhiwat = so->so_snd.sb_hiwat -
455 (so2->so_rcv.sb_cc - unp->unp_conn->unp_cc);
456 (void)chgsbsize(so->so_cred->cr_uidinfo, &so->so_snd.sb_hiwat,
457 newhiwat, RLIM_INFINITY);
458 SOCKBUF_UNLOCK(&so->so_snd);
459 unp->unp_conn->unp_cc = so2->so_rcv.sb_cc;
460 sorwakeup_locked(so2);
461 m = NULL;
462 break;
463
464 default:
465 panic("uipc_send unknown socktype");
466 }
467
468 /*
469 * SEND_EOF is equivalent to a SEND followed by
470 * a SHUTDOWN.
471 */
472 if (flags & PRUS_EOF) {
473 socantsendmore(so);
474 unp_shutdown(unp);
475 }
476 UNP_UNLOCK();
477
478 if (control != NULL && error != 0)
479 unp_dispose(control);
480
481release:
482 if (control != NULL)
483 m_freem(control);
484 if (m != NULL)
485 m_freem(m);
486 return (error);
487}
488
489static int
490uipc_sense(struct socket *so, struct stat *sb)
491{
492 struct unpcb *unp;
493 struct socket *so2;
494
495 unp = sotounpcb(so);
496 KASSERT(unp != NULL, ("uipc_sense: unp == NULL"));
497 UNP_LOCK();
498 sb->st_blksize = so->so_snd.sb_hiwat;
499 if (so->so_type == SOCK_STREAM && unp->unp_conn != NULL) {
500 so2 = unp->unp_conn->unp_socket;
501 sb->st_blksize += so2->so_rcv.sb_cc;
502 }
503 sb->st_dev = NODEV;
504 if (unp->unp_ino == 0)
505 unp->unp_ino = (++unp_ino == 0) ? ++unp_ino : unp_ino;
506 sb->st_ino = unp->unp_ino;
507 UNP_UNLOCK();
508 return (0);
509}
510
511static int
512uipc_shutdown(struct socket *so)
513{
514 struct unpcb *unp;
515
516 unp = sotounpcb(so);
517 KASSERT(unp != NULL, ("uipc_shutdown: unp == NULL"));
518 UNP_LOCK();
519 socantsendmore(so);
520 unp_shutdown(unp);
521 UNP_UNLOCK();
522 return (0);
523}
524
525static int
526uipc_sockaddr(struct socket *so, struct sockaddr **nam)
527{
528 struct unpcb *unp;
529 const struct sockaddr *sa;
530
531 unp = sotounpcb(so);
532 KASSERT(unp != NULL, ("uipc_sockaddr: unp == NULL"));
533 *nam = malloc(sizeof(struct sockaddr_un), M_SONAME, M_WAITOK);
534 UNP_LOCK();
535 if (unp->unp_addr != NULL)
536 sa = (struct sockaddr *) unp->unp_addr;
537 else
538 sa = &sun_noname;
539 bcopy(sa, *nam, sa->sa_len);
540 UNP_UNLOCK();
541 return (0);
542}
543
544struct pr_usrreqs uipc_usrreqs = {
545 .pru_abort = uipc_abort,
546 .pru_accept = uipc_accept,
547 .pru_attach = uipc_attach,
548 .pru_bind = uipc_bind,
549 .pru_connect = uipc_connect,
550 .pru_connect2 = uipc_connect2,
551 .pru_detach = uipc_detach,
552 .pru_disconnect = uipc_disconnect,
553 .pru_listen = uipc_listen,
554 .pru_peeraddr = uipc_peeraddr,
555 .pru_rcvd = uipc_rcvd,
556 .pru_send = uipc_send,
557 .pru_sense = uipc_sense,
558 .pru_shutdown = uipc_shutdown,
559 .pru_sockaddr = uipc_sockaddr,
560 .pru_sosend = sosend,
561 .pru_soreceive = soreceive,
562 .pru_sopoll = sopoll,
563};
564
565int
566uipc_ctloutput(struct socket *so, struct sockopt *sopt)
567{
568 struct unpcb *unp;
569 struct xucred xu;
570 int error, optval;
571
572 if (sopt->sopt_level != 0)
573 return (EINVAL);
574
575 unp = sotounpcb(so);
576 KASSERT(unp != NULL, ("uipc_ctloutput: unp == NULL"));
577 UNP_LOCK();
578 error = 0;
579 switch (sopt->sopt_dir) {
580 case SOPT_GET:
581 switch (sopt->sopt_name) {
582 case LOCAL_PEERCRED:
583 if (unp->unp_flags & UNP_HAVEPC)
584 xu = unp->unp_peercred;
585 else {
586 if (so->so_type == SOCK_STREAM)
587 error = ENOTCONN;
588 else
589 error = EINVAL;
590 }
591 if (error == 0)
592 error = sooptcopyout(sopt, &xu, sizeof(xu));
593 break;
594 case LOCAL_CREDS:
595 optval = unp->unp_flags & UNP_WANTCRED ? 1 : 0;
596 error = sooptcopyout(sopt, &optval, sizeof(optval));
597 break;
598 case LOCAL_CONNWAIT:
599 optval = unp->unp_flags & UNP_CONNWAIT ? 1 : 0;
600 error = sooptcopyout(sopt, &optval, sizeof(optval));
601 break;
602 default:
603 error = EOPNOTSUPP;
604 break;
605 }
606 break;
607 case SOPT_SET:
608 switch (sopt->sopt_name) {
609 case LOCAL_CREDS:
610 case LOCAL_CONNWAIT:
611 error = sooptcopyin(sopt, &optval, sizeof(optval),
612 sizeof(optval));
613 if (error)
614 break;
615
616#define OPTSET(bit) \
617 if (optval) \
618 unp->unp_flags |= bit; \
619 else \
620 unp->unp_flags &= ~bit;
621
622 switch (sopt->sopt_name) {
623 case LOCAL_CREDS:
624 OPTSET(UNP_WANTCRED);
625 break;
626 case LOCAL_CONNWAIT:
627 OPTSET(UNP_CONNWAIT);
628 break;
629 default:
630 break;
631 }
632 break;
633#undef OPTSET
634 default:
635 error = ENOPROTOOPT;
636 break;
637 }
638 break;
639 default:
640 error = EOPNOTSUPP;
641 break;
642 }
643 UNP_UNLOCK();
644 return (error);
645}
646
647/*
648 * Both send and receive buffers are allocated PIPSIZ bytes of buffering
649 * for stream sockets, although the total for sender and receiver is
650 * actually only PIPSIZ.
651 * Datagram sockets really use the sendspace as the maximum datagram size,
652 * and don't really want to reserve the sendspace. Their recvspace should
653 * be large enough for at least one max-size datagram plus address.
654 */
655#ifndef PIPSIZ
656#define PIPSIZ 8192
657#endif
658static u_long unpst_sendspace = PIPSIZ;
659static u_long unpst_recvspace = PIPSIZ;
660static u_long unpdg_sendspace = 2*1024; /* really max datagram size */
661static u_long unpdg_recvspace = 4*1024;
662
663static int unp_rights; /* file descriptors in flight */
664
665SYSCTL_DECL(_net_local_stream);
666SYSCTL_ULONG(_net_local_stream, OID_AUTO, sendspace, CTLFLAG_RW,
667 &unpst_sendspace, 0, "");
668SYSCTL_ULONG(_net_local_stream, OID_AUTO, recvspace, CTLFLAG_RW,
669 &unpst_recvspace, 0, "");
670SYSCTL_DECL(_net_local_dgram);
671SYSCTL_ULONG(_net_local_dgram, OID_AUTO, maxdgram, CTLFLAG_RW,
672 &unpdg_sendspace, 0, "");
673SYSCTL_ULONG(_net_local_dgram, OID_AUTO, recvspace, CTLFLAG_RW,
674 &unpdg_recvspace, 0, "");
675SYSCTL_DECL(_net_local);
676SYSCTL_INT(_net_local, OID_AUTO, inflight, CTLFLAG_RD, &unp_rights, 0, "");
677
678static int
679unp_attach(struct socket *so)
680{
681 struct unpcb *unp;
682 int error;
683
684 KASSERT(so->so_pcb == NULL, ("unp_attach: so_pcb != NULL"));
685 if (so->so_snd.sb_hiwat == 0 || so->so_rcv.sb_hiwat == 0) {
686 switch (so->so_type) {
687
688 case SOCK_STREAM:
689 error = soreserve(so, unpst_sendspace, unpst_recvspace);
690 break;
691
692 case SOCK_DGRAM:
693 error = soreserve(so, unpdg_sendspace, unpdg_recvspace);
694 break;
695
696 default:
697 panic("unp_attach");
698 }
699 if (error)
700 return (error);
701 }
702 unp = uma_zalloc(unp_zone, M_WAITOK | M_ZERO);
703 if (unp == NULL)
704 return (ENOBUFS);
705 LIST_INIT(&unp->unp_refs);
706 unp->unp_socket = so;
707 so->so_pcb = unp;
708
709 UNP_LOCK();
710 unp->unp_gencnt = ++unp_gencnt;
711 unp_count++;
712 LIST_INSERT_HEAD(so->so_type == SOCK_DGRAM ? &unp_dhead
713 : &unp_shead, unp, unp_link);
714 UNP_UNLOCK();
715
716 return (0);
717}
718
719static void
720unp_detach(struct unpcb *unp)
721{
722 struct vnode *vp;
723 int local_unp_rights;
724
725 UNP_LOCK_ASSERT();
726
727 LIST_REMOVE(unp, unp_link);
728 unp->unp_gencnt = ++unp_gencnt;
729 --unp_count;
730 if ((vp = unp->unp_vnode) != NULL) {
731 /*
732 * XXXRW: should v_socket be frobbed only while holding
733 * Giant?
734 */
735 unp->unp_vnode->v_socket = NULL;
736 unp->unp_vnode = NULL;
737 }
738 if (unp->unp_conn != NULL)
739 unp_disconnect(unp);
740 while (!LIST_EMPTY(&unp->unp_refs)) {
741 struct unpcb *ref = LIST_FIRST(&unp->unp_refs);
742 unp_drop(ref, ECONNRESET);
743 }
744 soisdisconnected(unp->unp_socket);
745 unp->unp_socket->so_pcb = NULL;
746 local_unp_rights = unp_rights;
747 UNP_UNLOCK();
748 if (unp->unp_addr != NULL)
749 FREE(unp->unp_addr, M_SONAME);
750 uma_zfree(unp_zone, unp);
751 if (vp) {
752 int vfslocked;
753
754 vfslocked = VFS_LOCK_GIANT(vp->v_mount);
755 vrele(vp);
756 VFS_UNLOCK_GIANT(vfslocked);
757 }
758 if (local_unp_rights)
759 taskqueue_enqueue(taskqueue_thread, &unp_gc_task);
760}
761
762static int
763unp_bind(struct unpcb *unp, struct sockaddr *nam, struct thread *td)
764{
765 struct sockaddr_un *soun = (struct sockaddr_un *)nam;
766 struct vnode *vp;
767 struct mount *mp;
768 struct vattr vattr;
769 int error, namelen;
770 struct nameidata nd;
771 char *buf;
772
773 UNP_LOCK_ASSERT();
774
775 /*
776 * XXXRW: This test-and-set of unp_vnode is non-atomic; the
777 * unlocked read here is fine, but the value of unp_vnode needs
778 * to be tested again after we do all the lookups to see if the
779 * pcb is still unbound?
780 */
781 if (unp->unp_vnode != NULL)
782 return (EINVAL);
783
784 namelen = soun->sun_len - offsetof(struct sockaddr_un, sun_path);
785 if (namelen <= 0)
786 return (EINVAL);
787
788 UNP_UNLOCK();
789
790 buf = malloc(namelen + 1, M_TEMP, M_WAITOK);
791 strlcpy(buf, soun->sun_path, namelen + 1);
792
793 mtx_lock(&Giant);
794restart:
795 mtx_assert(&Giant, MA_OWNED);
796 NDINIT(&nd, CREATE, NOFOLLOW | LOCKPARENT | SAVENAME, UIO_SYSSPACE,
797 buf, td);
798/* SHOULD BE ABLE TO ADOPT EXISTING AND wakeup() ALA FIFO's */
799 error = namei(&nd);
800 if (error)
801 goto done;
802 vp = nd.ni_vp;
803 if (vp != NULL || vn_start_write(nd.ni_dvp, &mp, V_NOWAIT) != 0) {
804 NDFREE(&nd, NDF_ONLY_PNBUF);
805 if (nd.ni_dvp == vp)
806 vrele(nd.ni_dvp);
807 else
808 vput(nd.ni_dvp);
809 if (vp != NULL) {
810 vrele(vp);
811 error = EADDRINUSE;
812 goto done;
813 }
814 error = vn_start_write(NULL, &mp, V_XSLEEP | PCATCH);
815 if (error)
816 goto done;
817 goto restart;
818 }
819 VATTR_NULL(&vattr);
820 vattr.va_type = VSOCK;
821 vattr.va_mode = (ACCESSPERMS & ~td->td_proc->p_fd->fd_cmask);
822#ifdef MAC
823 error = mac_check_vnode_create(td->td_ucred, nd.ni_dvp, &nd.ni_cnd,
824 &vattr);
825#endif
826 if (error == 0) {
827 VOP_LEASE(nd.ni_dvp, td, td->td_ucred, LEASE_WRITE);
828 error = VOP_CREATE(nd.ni_dvp, &nd.ni_vp, &nd.ni_cnd, &vattr);
829 }
830 NDFREE(&nd, NDF_ONLY_PNBUF);
831 vput(nd.ni_dvp);
832 if (error) {
833 vn_finished_write(mp);
834 goto done;
835 }
836 vp = nd.ni_vp;
837 ASSERT_VOP_LOCKED(vp, "unp_bind");
838 soun = (struct sockaddr_un *)sodupsockaddr(nam, M_WAITOK);
839 UNP_LOCK();
840 vp->v_socket = unp->unp_socket;
841 unp->unp_vnode = vp;
842 unp->unp_addr = soun;
843 UNP_UNLOCK();
844 VOP_UNLOCK(vp, 0, td);
845 vn_finished_write(mp);
846done:
847 mtx_unlock(&Giant);
848 free(buf, M_TEMP);
849 UNP_LOCK();
850 return (error);
851}
852
853static int
854unp_connect(struct socket *so, struct sockaddr *nam, struct thread *td)
855{
856 struct sockaddr_un *soun = (struct sockaddr_un *)nam;
857 struct vnode *vp;
858 struct socket *so2, *so3;
859 struct unpcb *unp, *unp2, *unp3;
860 int error, len;
861 struct nameidata nd;
862 char buf[SOCK_MAXADDRLEN];
863 struct sockaddr *sa;
864
865 UNP_LOCK_ASSERT();
866
867 unp = sotounpcb(so);
868 KASSERT(unp != NULL, ("unp_connect: unp == NULL"));
869 len = nam->sa_len - offsetof(struct sockaddr_un, sun_path);
870 if (len <= 0)
871 return (EINVAL);
872 strlcpy(buf, soun->sun_path, len + 1);
873 UNP_UNLOCK();
874 sa = malloc(sizeof(struct sockaddr_un), M_SONAME, M_WAITOK);
875 mtx_lock(&Giant);
876 NDINIT(&nd, LOOKUP, FOLLOW | LOCKLEAF, UIO_SYSSPACE, buf, td);
877 error = namei(&nd);
878 if (error)
879 vp = NULL;
880 else
881 vp = nd.ni_vp;
882 ASSERT_VOP_LOCKED(vp, "unp_connect");
883 NDFREE(&nd, NDF_ONLY_PNBUF);
884 if (error)
885 goto bad;
886
887 if (vp->v_type != VSOCK) {
888 error = ENOTSOCK;
889 goto bad;
890 }
891 error = VOP_ACCESS(vp, VWRITE, td->td_ucred, td);
892 if (error)
893 goto bad;
894 mtx_unlock(&Giant);
895 UNP_LOCK();
896 unp = sotounpcb(so);
897 KASSERT(unp != NULL, ("unp_connect: unp == NULL"));
898 so2 = vp->v_socket;
899 if (so2 == NULL) {
900 error = ECONNREFUSED;
901 goto bad2;
902 }
903 if (so->so_type != so2->so_type) {
904 error = EPROTOTYPE;
905 goto bad2;
906 }
907 if (so->so_proto->pr_flags & PR_CONNREQUIRED) {
908 if (so2->so_options & SO_ACCEPTCONN) {
909 /*
910 * NB: drop locks here so unp_attach is entered
911 * w/o locks; this avoids a recursive lock
912 * of the head and holding sleep locks across
913 * a (potentially) blocking malloc.
914 */
915 UNP_UNLOCK();
916 so3 = sonewconn(so2, 0);
917 UNP_LOCK();
918 } else
919 so3 = NULL;
920 if (so3 == NULL) {
921 error = ECONNREFUSED;
922 goto bad2;
923 }
924 unp = sotounpcb(so);
925 unp2 = sotounpcb(so2);
926 unp3 = sotounpcb(so3);
927 if (unp2->unp_addr != NULL) {
928 bcopy(unp2->unp_addr, sa, unp2->unp_addr->sun_len);
929 unp3->unp_addr = (struct sockaddr_un *) sa;
930 sa = NULL;
931 }
932 /*
933 * unp_peercred management:
934 *
935 * The connecter's (client's) credentials are copied
936 * from its process structure at the time of connect()
937 * (which is now).
938 */
939 cru2x(td->td_ucred, &unp3->unp_peercred);
940 unp3->unp_flags |= UNP_HAVEPC;
941 /*
942 * The receiver's (server's) credentials are copied
943 * from the unp_peercred member of socket on which the
944 * former called listen(); unp_listen() cached that
945 * process's credentials at that time so we can use
946 * them now.
947 */
948 KASSERT(unp2->unp_flags & UNP_HAVEPCCACHED,
949 ("unp_connect: listener without cached peercred"));
950 memcpy(&unp->unp_peercred, &unp2->unp_peercred,
951 sizeof(unp->unp_peercred));
952 unp->unp_flags |= UNP_HAVEPC;
36
37#include "opt_mac.h"
38
39#include <sys/param.h>
40#include <sys/domain.h>
41#include <sys/fcntl.h>
42#include <sys/malloc.h> /* XXX must be before <sys/file.h> */
43#include <sys/eventhandler.h>
44#include <sys/file.h>
45#include <sys/filedesc.h>
46#include <sys/jail.h>
47#include <sys/kernel.h>
48#include <sys/lock.h>
49#include <sys/mac.h>
50#include <sys/mbuf.h>
51#include <sys/mount.h>
52#include <sys/mutex.h>
53#include <sys/namei.h>
54#include <sys/proc.h>
55#include <sys/protosw.h>
56#include <sys/resourcevar.h>
57#include <sys/socket.h>
58#include <sys/socketvar.h>
59#include <sys/signalvar.h>
60#include <sys/stat.h>
61#include <sys/sx.h>
62#include <sys/sysctl.h>
63#include <sys/systm.h>
64#include <sys/taskqueue.h>
65#include <sys/un.h>
66#include <sys/unpcb.h>
67#include <sys/vnode.h>
68
69#include <vm/uma.h>
70
71static uma_zone_t unp_zone;
72static unp_gen_t unp_gencnt;
73static u_int unp_count;
74
75static struct unp_head unp_shead, unp_dhead;
76
77/*
78 * Unix communications domain.
79 *
80 * TODO:
81 * SEQPACKET, RDM
82 * rethink name space problems
83 * need a proper out-of-band
84 * lock pushdown
85 */
86static const struct sockaddr sun_noname = { sizeof(sun_noname), AF_LOCAL };
87static ino_t unp_ino; /* prototype for fake inode numbers */
88struct mbuf *unp_addsockcred(struct thread *, struct mbuf *);
89
90/*
91 * Currently, UNIX domain sockets are protected by a single subsystem lock,
92 * which covers global data structures and variables, the contents of each
93 * per-socket unpcb structure, and the so_pcb field in sockets attached to
94 * the UNIX domain. This provides for a moderate degree of paralellism, as
95 * receive operations on UNIX domain sockets do not need to acquire the
96 * subsystem lock. Finer grained locking to permit send() without acquiring
97 * a global lock would be a logical next step.
98 *
99 * The UNIX domain socket lock preceds all socket layer locks, including the
100 * socket lock and socket buffer lock, permitting UNIX domain socket code to
101 * call into socket support routines without releasing its locks.
102 *
103 * Some caution is required in areas where the UNIX domain socket code enters
104 * VFS in order to create or find rendezvous points. This results in
105 * dropping of the UNIX domain socket subsystem lock, acquisition of the
106 * Giant lock, and potential sleeping. This increases the chances of races,
107 * and exposes weaknesses in the socket->protocol API by offering poor
108 * failure modes.
109 */
110static struct mtx unp_mtx;
111#define UNP_LOCK_INIT() \
112 mtx_init(&unp_mtx, "unp", NULL, MTX_DEF)
113#define UNP_LOCK() mtx_lock(&unp_mtx)
114#define UNP_UNLOCK() mtx_unlock(&unp_mtx)
115#define UNP_LOCK_ASSERT() mtx_assert(&unp_mtx, MA_OWNED)
116#define UNP_UNLOCK_ASSERT() mtx_assert(&unp_mtx, MA_NOTOWNED)
117
118/*
119 * Garbage collection of cyclic file descriptor/socket references occurs
120 * asynchronously in a taskqueue context in order to avoid recursion and
121 * reentrance in the UNIX domain socket, file descriptor, and socket layer
122 * code. See unp_gc() for a full description.
123 */
124static struct task unp_gc_task;
125
126static int unp_attach(struct socket *);
127static void unp_detach(struct unpcb *);
128static int unp_bind(struct unpcb *,struct sockaddr *, struct thread *);
129static int unp_connect(struct socket *,struct sockaddr *, struct thread *);
130static int unp_connect2(struct socket *so, struct socket *so2, int);
131static void unp_disconnect(struct unpcb *);
132static void unp_shutdown(struct unpcb *);
133static void unp_drop(struct unpcb *, int);
134static void unp_gc(__unused void *, int);
135static void unp_scan(struct mbuf *, void (*)(struct file *));
136static void unp_mark(struct file *);
137static void unp_discard(struct file *);
138static void unp_freerights(struct file **, int);
139static int unp_internalize(struct mbuf **, struct thread *);
140static int unp_listen(struct socket *, struct unpcb *, int,
141 struct thread *);
142
143static void
144uipc_abort(struct socket *so)
145{
146 struct unpcb *unp;
147
148 unp = sotounpcb(so);
149 KASSERT(unp != NULL, ("uipc_abort: unp == NULL"));
150 UNP_LOCK();
151 unp_drop(unp, ECONNABORTED);
152 unp_detach(unp);
153 UNP_UNLOCK_ASSERT();
154}
155
156static int
157uipc_accept(struct socket *so, struct sockaddr **nam)
158{
159 struct unpcb *unp;
160 const struct sockaddr *sa;
161
162 /*
163 * Pass back name of connected socket,
164 * if it was bound and we are still connected
165 * (our peer may have closed already!).
166 */
167 unp = sotounpcb(so);
168 KASSERT(unp != NULL, ("uipc_accept: unp == NULL"));
169 *nam = malloc(sizeof(struct sockaddr_un), M_SONAME, M_WAITOK);
170 UNP_LOCK();
171 if (unp->unp_conn != NULL && unp->unp_conn->unp_addr != NULL)
172 sa = (struct sockaddr *) unp->unp_conn->unp_addr;
173 else
174 sa = &sun_noname;
175 bcopy(sa, *nam, sa->sa_len);
176 UNP_UNLOCK();
177 return (0);
178}
179
180static int
181uipc_attach(struct socket *so, int proto, struct thread *td)
182{
183
184 return (unp_attach(so));
185}
186
187static int
188uipc_bind(struct socket *so, struct sockaddr *nam, struct thread *td)
189{
190 struct unpcb *unp;
191 int error;
192
193 unp = sotounpcb(so);
194 KASSERT(unp != NULL, ("uipc_bind: unp == NULL"));
195 UNP_LOCK();
196 error = unp_bind(unp, nam, td);
197 UNP_UNLOCK();
198 return (error);
199}
200
201static int
202uipc_connect(struct socket *so, struct sockaddr *nam, struct thread *td)
203{
204 struct unpcb *unp;
205 int error;
206
207 KASSERT(td == curthread, ("uipc_connect: td != curthread"));
208 unp = sotounpcb(so);
209 KASSERT(unp != NULL, ("uipc_connect: unp == NULL"));
210 UNP_LOCK();
211 error = unp_connect(so, nam, td);
212 UNP_UNLOCK();
213 return (error);
214}
215
216int
217uipc_connect2(struct socket *so1, struct socket *so2)
218{
219 struct unpcb *unp;
220 int error;
221
222 unp = sotounpcb(so1);
223 KASSERT(unp != NULL, ("uipc_connect2: unp == NULL"));
224 UNP_LOCK();
225 error = unp_connect2(so1, so2, PRU_CONNECT2);
226 UNP_UNLOCK();
227 return (error);
228}
229
230/* control is EOPNOTSUPP */
231
232static void
233uipc_detach(struct socket *so)
234{
235 struct unpcb *unp;
236
237 unp = sotounpcb(so);
238 KASSERT(unp != NULL, ("uipc_detach: unp == NULL"));
239 UNP_LOCK();
240 unp_detach(unp);
241 UNP_UNLOCK_ASSERT();
242}
243
244static int
245uipc_disconnect(struct socket *so)
246{
247 struct unpcb *unp;
248
249 unp = sotounpcb(so);
250 KASSERT(unp != NULL, ("uipc_disconnect: unp == NULL"));
251 UNP_LOCK();
252 unp_disconnect(unp);
253 UNP_UNLOCK();
254 return (0);
255}
256
257static int
258uipc_listen(struct socket *so, int backlog, struct thread *td)
259{
260 struct unpcb *unp;
261 int error;
262
263 unp = sotounpcb(so);
264 KASSERT(unp != NULL, ("uipc_listen: unp == NULL"));
265 UNP_LOCK();
266 if (unp->unp_vnode == NULL) {
267 UNP_UNLOCK();
268 return (EINVAL);
269 }
270 error = unp_listen(so, unp, backlog, td);
271 UNP_UNLOCK();
272 return (error);
273}
274
275static int
276uipc_peeraddr(struct socket *so, struct sockaddr **nam)
277{
278 struct unpcb *unp;
279 const struct sockaddr *sa;
280
281 unp = sotounpcb(so);
282 KASSERT(unp != NULL, ("uipc_peeraddr: unp == NULL"));
283 *nam = malloc(sizeof(struct sockaddr_un), M_SONAME, M_WAITOK);
284 UNP_LOCK();
285 if (unp->unp_conn != NULL && unp->unp_conn->unp_addr!= NULL)
286 sa = (struct sockaddr *) unp->unp_conn->unp_addr;
287 else {
288 /*
289 * XXX: It seems that this test always fails even when
290 * connection is established. So, this else clause is
291 * added as workaround to return PF_LOCAL sockaddr.
292 */
293 sa = &sun_noname;
294 }
295 bcopy(sa, *nam, sa->sa_len);
296 UNP_UNLOCK();
297 return (0);
298}
299
300static int
301uipc_rcvd(struct socket *so, int flags)
302{
303 struct unpcb *unp;
304 struct socket *so2;
305 u_long newhiwat;
306
307 unp = sotounpcb(so);
308 KASSERT(unp != NULL, ("uipc_rcvd: unp == NULL"));
309 UNP_LOCK();
310 switch (so->so_type) {
311 case SOCK_DGRAM:
312 panic("uipc_rcvd DGRAM?");
313 /*NOTREACHED*/
314
315 case SOCK_STREAM:
316 if (unp->unp_conn == NULL)
317 break;
318 so2 = unp->unp_conn->unp_socket;
319 SOCKBUF_LOCK(&so2->so_snd);
320 SOCKBUF_LOCK(&so->so_rcv);
321 /*
322 * Adjust backpressure on sender
323 * and wakeup any waiting to write.
324 */
325 so2->so_snd.sb_mbmax += unp->unp_mbcnt - so->so_rcv.sb_mbcnt;
326 unp->unp_mbcnt = so->so_rcv.sb_mbcnt;
327 newhiwat = so2->so_snd.sb_hiwat + unp->unp_cc -
328 so->so_rcv.sb_cc;
329 (void)chgsbsize(so2->so_cred->cr_uidinfo, &so2->so_snd.sb_hiwat,
330 newhiwat, RLIM_INFINITY);
331 unp->unp_cc = so->so_rcv.sb_cc;
332 SOCKBUF_UNLOCK(&so->so_rcv);
333 sowwakeup_locked(so2);
334 break;
335
336 default:
337 panic("uipc_rcvd unknown socktype");
338 }
339 UNP_UNLOCK();
340 return (0);
341}
342
343/* pru_rcvoob is EOPNOTSUPP */
344
345static int
346uipc_send(struct socket *so, int flags, struct mbuf *m, struct sockaddr *nam,
347 struct mbuf *control, struct thread *td)
348{
349 int error = 0;
350 struct unpcb *unp;
351 struct socket *so2;
352 u_long newhiwat;
353
354 unp = sotounpcb(so);
355 KASSERT(unp != NULL, ("uipc_send: unp == NULL"));
356 if (flags & PRUS_OOB) {
357 error = EOPNOTSUPP;
358 goto release;
359 }
360
361 if (control != NULL && (error = unp_internalize(&control, td)))
362 goto release;
363
364 UNP_LOCK();
365 switch (so->so_type) {
366 case SOCK_DGRAM:
367 {
368 const struct sockaddr *from;
369
370 if (nam != NULL) {
371 if (unp->unp_conn != NULL) {
372 error = EISCONN;
373 break;
374 }
375 error = unp_connect(so, nam, td);
376 if (error)
377 break;
378 } else {
379 if (unp->unp_conn == NULL) {
380 error = ENOTCONN;
381 break;
382 }
383 }
384 so2 = unp->unp_conn->unp_socket;
385 if (unp->unp_addr != NULL)
386 from = (struct sockaddr *)unp->unp_addr;
387 else
388 from = &sun_noname;
389 if (unp->unp_conn->unp_flags & UNP_WANTCRED)
390 control = unp_addsockcred(td, control);
391 SOCKBUF_LOCK(&so2->so_rcv);
392 if (sbappendaddr_locked(&so2->so_rcv, from, m, control)) {
393 sorwakeup_locked(so2);
394 m = NULL;
395 control = NULL;
396 } else {
397 SOCKBUF_UNLOCK(&so2->so_rcv);
398 error = ENOBUFS;
399 }
400 if (nam != NULL)
401 unp_disconnect(unp);
402 break;
403 }
404
405 case SOCK_STREAM:
406 /* Connect if not connected yet. */
407 /*
408 * Note: A better implementation would complain
409 * if not equal to the peer's address.
410 */
411 if ((so->so_state & SS_ISCONNECTED) == 0) {
412 if (nam != NULL) {
413 error = unp_connect(so, nam, td);
414 if (error)
415 break; /* XXX */
416 } else {
417 error = ENOTCONN;
418 break;
419 }
420 }
421
422 SOCKBUF_LOCK(&so->so_snd);
423 if (so->so_snd.sb_state & SBS_CANTSENDMORE) {
424 SOCKBUF_UNLOCK(&so->so_snd);
425 error = EPIPE;
426 break;
427 }
428 if (unp->unp_conn == NULL)
429 panic("uipc_send connected but no connection?");
430 so2 = unp->unp_conn->unp_socket;
431 SOCKBUF_LOCK(&so2->so_rcv);
432 if (unp->unp_conn->unp_flags & UNP_WANTCRED) {
433 /*
434 * Credentials are passed only once on
435 * SOCK_STREAM.
436 */
437 unp->unp_conn->unp_flags &= ~UNP_WANTCRED;
438 control = unp_addsockcred(td, control);
439 }
440 /*
441 * Send to paired receive port, and then reduce
442 * send buffer hiwater marks to maintain backpressure.
443 * Wake up readers.
444 */
445 if (control != NULL) {
446 if (sbappendcontrol_locked(&so2->so_rcv, m, control))
447 control = NULL;
448 } else {
449 sbappend_locked(&so2->so_rcv, m);
450 }
451 so->so_snd.sb_mbmax -=
452 so2->so_rcv.sb_mbcnt - unp->unp_conn->unp_mbcnt;
453 unp->unp_conn->unp_mbcnt = so2->so_rcv.sb_mbcnt;
454 newhiwat = so->so_snd.sb_hiwat -
455 (so2->so_rcv.sb_cc - unp->unp_conn->unp_cc);
456 (void)chgsbsize(so->so_cred->cr_uidinfo, &so->so_snd.sb_hiwat,
457 newhiwat, RLIM_INFINITY);
458 SOCKBUF_UNLOCK(&so->so_snd);
459 unp->unp_conn->unp_cc = so2->so_rcv.sb_cc;
460 sorwakeup_locked(so2);
461 m = NULL;
462 break;
463
464 default:
465 panic("uipc_send unknown socktype");
466 }
467
468 /*
469 * SEND_EOF is equivalent to a SEND followed by
470 * a SHUTDOWN.
471 */
472 if (flags & PRUS_EOF) {
473 socantsendmore(so);
474 unp_shutdown(unp);
475 }
476 UNP_UNLOCK();
477
478 if (control != NULL && error != 0)
479 unp_dispose(control);
480
481release:
482 if (control != NULL)
483 m_freem(control);
484 if (m != NULL)
485 m_freem(m);
486 return (error);
487}
488
489static int
490uipc_sense(struct socket *so, struct stat *sb)
491{
492 struct unpcb *unp;
493 struct socket *so2;
494
495 unp = sotounpcb(so);
496 KASSERT(unp != NULL, ("uipc_sense: unp == NULL"));
497 UNP_LOCK();
498 sb->st_blksize = so->so_snd.sb_hiwat;
499 if (so->so_type == SOCK_STREAM && unp->unp_conn != NULL) {
500 so2 = unp->unp_conn->unp_socket;
501 sb->st_blksize += so2->so_rcv.sb_cc;
502 }
503 sb->st_dev = NODEV;
504 if (unp->unp_ino == 0)
505 unp->unp_ino = (++unp_ino == 0) ? ++unp_ino : unp_ino;
506 sb->st_ino = unp->unp_ino;
507 UNP_UNLOCK();
508 return (0);
509}
510
511static int
512uipc_shutdown(struct socket *so)
513{
514 struct unpcb *unp;
515
516 unp = sotounpcb(so);
517 KASSERT(unp != NULL, ("uipc_shutdown: unp == NULL"));
518 UNP_LOCK();
519 socantsendmore(so);
520 unp_shutdown(unp);
521 UNP_UNLOCK();
522 return (0);
523}
524
525static int
526uipc_sockaddr(struct socket *so, struct sockaddr **nam)
527{
528 struct unpcb *unp;
529 const struct sockaddr *sa;
530
531 unp = sotounpcb(so);
532 KASSERT(unp != NULL, ("uipc_sockaddr: unp == NULL"));
533 *nam = malloc(sizeof(struct sockaddr_un), M_SONAME, M_WAITOK);
534 UNP_LOCK();
535 if (unp->unp_addr != NULL)
536 sa = (struct sockaddr *) unp->unp_addr;
537 else
538 sa = &sun_noname;
539 bcopy(sa, *nam, sa->sa_len);
540 UNP_UNLOCK();
541 return (0);
542}
543
544struct pr_usrreqs uipc_usrreqs = {
545 .pru_abort = uipc_abort,
546 .pru_accept = uipc_accept,
547 .pru_attach = uipc_attach,
548 .pru_bind = uipc_bind,
549 .pru_connect = uipc_connect,
550 .pru_connect2 = uipc_connect2,
551 .pru_detach = uipc_detach,
552 .pru_disconnect = uipc_disconnect,
553 .pru_listen = uipc_listen,
554 .pru_peeraddr = uipc_peeraddr,
555 .pru_rcvd = uipc_rcvd,
556 .pru_send = uipc_send,
557 .pru_sense = uipc_sense,
558 .pru_shutdown = uipc_shutdown,
559 .pru_sockaddr = uipc_sockaddr,
560 .pru_sosend = sosend,
561 .pru_soreceive = soreceive,
562 .pru_sopoll = sopoll,
563};
564
565int
566uipc_ctloutput(struct socket *so, struct sockopt *sopt)
567{
568 struct unpcb *unp;
569 struct xucred xu;
570 int error, optval;
571
572 if (sopt->sopt_level != 0)
573 return (EINVAL);
574
575 unp = sotounpcb(so);
576 KASSERT(unp != NULL, ("uipc_ctloutput: unp == NULL"));
577 UNP_LOCK();
578 error = 0;
579 switch (sopt->sopt_dir) {
580 case SOPT_GET:
581 switch (sopt->sopt_name) {
582 case LOCAL_PEERCRED:
583 if (unp->unp_flags & UNP_HAVEPC)
584 xu = unp->unp_peercred;
585 else {
586 if (so->so_type == SOCK_STREAM)
587 error = ENOTCONN;
588 else
589 error = EINVAL;
590 }
591 if (error == 0)
592 error = sooptcopyout(sopt, &xu, sizeof(xu));
593 break;
594 case LOCAL_CREDS:
595 optval = unp->unp_flags & UNP_WANTCRED ? 1 : 0;
596 error = sooptcopyout(sopt, &optval, sizeof(optval));
597 break;
598 case LOCAL_CONNWAIT:
599 optval = unp->unp_flags & UNP_CONNWAIT ? 1 : 0;
600 error = sooptcopyout(sopt, &optval, sizeof(optval));
601 break;
602 default:
603 error = EOPNOTSUPP;
604 break;
605 }
606 break;
607 case SOPT_SET:
608 switch (sopt->sopt_name) {
609 case LOCAL_CREDS:
610 case LOCAL_CONNWAIT:
611 error = sooptcopyin(sopt, &optval, sizeof(optval),
612 sizeof(optval));
613 if (error)
614 break;
615
616#define OPTSET(bit) \
617 if (optval) \
618 unp->unp_flags |= bit; \
619 else \
620 unp->unp_flags &= ~bit;
621
622 switch (sopt->sopt_name) {
623 case LOCAL_CREDS:
624 OPTSET(UNP_WANTCRED);
625 break;
626 case LOCAL_CONNWAIT:
627 OPTSET(UNP_CONNWAIT);
628 break;
629 default:
630 break;
631 }
632 break;
633#undef OPTSET
634 default:
635 error = ENOPROTOOPT;
636 break;
637 }
638 break;
639 default:
640 error = EOPNOTSUPP;
641 break;
642 }
643 UNP_UNLOCK();
644 return (error);
645}
646
647/*
648 * Both send and receive buffers are allocated PIPSIZ bytes of buffering
649 * for stream sockets, although the total for sender and receiver is
650 * actually only PIPSIZ.
651 * Datagram sockets really use the sendspace as the maximum datagram size,
652 * and don't really want to reserve the sendspace. Their recvspace should
653 * be large enough for at least one max-size datagram plus address.
654 */
655#ifndef PIPSIZ
656#define PIPSIZ 8192
657#endif
658static u_long unpst_sendspace = PIPSIZ;
659static u_long unpst_recvspace = PIPSIZ;
660static u_long unpdg_sendspace = 2*1024; /* really max datagram size */
661static u_long unpdg_recvspace = 4*1024;
662
663static int unp_rights; /* file descriptors in flight */
664
665SYSCTL_DECL(_net_local_stream);
666SYSCTL_ULONG(_net_local_stream, OID_AUTO, sendspace, CTLFLAG_RW,
667 &unpst_sendspace, 0, "");
668SYSCTL_ULONG(_net_local_stream, OID_AUTO, recvspace, CTLFLAG_RW,
669 &unpst_recvspace, 0, "");
670SYSCTL_DECL(_net_local_dgram);
671SYSCTL_ULONG(_net_local_dgram, OID_AUTO, maxdgram, CTLFLAG_RW,
672 &unpdg_sendspace, 0, "");
673SYSCTL_ULONG(_net_local_dgram, OID_AUTO, recvspace, CTLFLAG_RW,
674 &unpdg_recvspace, 0, "");
675SYSCTL_DECL(_net_local);
676SYSCTL_INT(_net_local, OID_AUTO, inflight, CTLFLAG_RD, &unp_rights, 0, "");
677
678static int
679unp_attach(struct socket *so)
680{
681 struct unpcb *unp;
682 int error;
683
684 KASSERT(so->so_pcb == NULL, ("unp_attach: so_pcb != NULL"));
685 if (so->so_snd.sb_hiwat == 0 || so->so_rcv.sb_hiwat == 0) {
686 switch (so->so_type) {
687
688 case SOCK_STREAM:
689 error = soreserve(so, unpst_sendspace, unpst_recvspace);
690 break;
691
692 case SOCK_DGRAM:
693 error = soreserve(so, unpdg_sendspace, unpdg_recvspace);
694 break;
695
696 default:
697 panic("unp_attach");
698 }
699 if (error)
700 return (error);
701 }
702 unp = uma_zalloc(unp_zone, M_WAITOK | M_ZERO);
703 if (unp == NULL)
704 return (ENOBUFS);
705 LIST_INIT(&unp->unp_refs);
706 unp->unp_socket = so;
707 so->so_pcb = unp;
708
709 UNP_LOCK();
710 unp->unp_gencnt = ++unp_gencnt;
711 unp_count++;
712 LIST_INSERT_HEAD(so->so_type == SOCK_DGRAM ? &unp_dhead
713 : &unp_shead, unp, unp_link);
714 UNP_UNLOCK();
715
716 return (0);
717}
718
719static void
720unp_detach(struct unpcb *unp)
721{
722 struct vnode *vp;
723 int local_unp_rights;
724
725 UNP_LOCK_ASSERT();
726
727 LIST_REMOVE(unp, unp_link);
728 unp->unp_gencnt = ++unp_gencnt;
729 --unp_count;
730 if ((vp = unp->unp_vnode) != NULL) {
731 /*
732 * XXXRW: should v_socket be frobbed only while holding
733 * Giant?
734 */
735 unp->unp_vnode->v_socket = NULL;
736 unp->unp_vnode = NULL;
737 }
738 if (unp->unp_conn != NULL)
739 unp_disconnect(unp);
740 while (!LIST_EMPTY(&unp->unp_refs)) {
741 struct unpcb *ref = LIST_FIRST(&unp->unp_refs);
742 unp_drop(ref, ECONNRESET);
743 }
744 soisdisconnected(unp->unp_socket);
745 unp->unp_socket->so_pcb = NULL;
746 local_unp_rights = unp_rights;
747 UNP_UNLOCK();
748 if (unp->unp_addr != NULL)
749 FREE(unp->unp_addr, M_SONAME);
750 uma_zfree(unp_zone, unp);
751 if (vp) {
752 int vfslocked;
753
754 vfslocked = VFS_LOCK_GIANT(vp->v_mount);
755 vrele(vp);
756 VFS_UNLOCK_GIANT(vfslocked);
757 }
758 if (local_unp_rights)
759 taskqueue_enqueue(taskqueue_thread, &unp_gc_task);
760}
761
762static int
763unp_bind(struct unpcb *unp, struct sockaddr *nam, struct thread *td)
764{
765 struct sockaddr_un *soun = (struct sockaddr_un *)nam;
766 struct vnode *vp;
767 struct mount *mp;
768 struct vattr vattr;
769 int error, namelen;
770 struct nameidata nd;
771 char *buf;
772
773 UNP_LOCK_ASSERT();
774
775 /*
776 * XXXRW: This test-and-set of unp_vnode is non-atomic; the
777 * unlocked read here is fine, but the value of unp_vnode needs
778 * to be tested again after we do all the lookups to see if the
779 * pcb is still unbound?
780 */
781 if (unp->unp_vnode != NULL)
782 return (EINVAL);
783
784 namelen = soun->sun_len - offsetof(struct sockaddr_un, sun_path);
785 if (namelen <= 0)
786 return (EINVAL);
787
788 UNP_UNLOCK();
789
790 buf = malloc(namelen + 1, M_TEMP, M_WAITOK);
791 strlcpy(buf, soun->sun_path, namelen + 1);
792
793 mtx_lock(&Giant);
794restart:
795 mtx_assert(&Giant, MA_OWNED);
796 NDINIT(&nd, CREATE, NOFOLLOW | LOCKPARENT | SAVENAME, UIO_SYSSPACE,
797 buf, td);
798/* SHOULD BE ABLE TO ADOPT EXISTING AND wakeup() ALA FIFO's */
799 error = namei(&nd);
800 if (error)
801 goto done;
802 vp = nd.ni_vp;
803 if (vp != NULL || vn_start_write(nd.ni_dvp, &mp, V_NOWAIT) != 0) {
804 NDFREE(&nd, NDF_ONLY_PNBUF);
805 if (nd.ni_dvp == vp)
806 vrele(nd.ni_dvp);
807 else
808 vput(nd.ni_dvp);
809 if (vp != NULL) {
810 vrele(vp);
811 error = EADDRINUSE;
812 goto done;
813 }
814 error = vn_start_write(NULL, &mp, V_XSLEEP | PCATCH);
815 if (error)
816 goto done;
817 goto restart;
818 }
819 VATTR_NULL(&vattr);
820 vattr.va_type = VSOCK;
821 vattr.va_mode = (ACCESSPERMS & ~td->td_proc->p_fd->fd_cmask);
822#ifdef MAC
823 error = mac_check_vnode_create(td->td_ucred, nd.ni_dvp, &nd.ni_cnd,
824 &vattr);
825#endif
826 if (error == 0) {
827 VOP_LEASE(nd.ni_dvp, td, td->td_ucred, LEASE_WRITE);
828 error = VOP_CREATE(nd.ni_dvp, &nd.ni_vp, &nd.ni_cnd, &vattr);
829 }
830 NDFREE(&nd, NDF_ONLY_PNBUF);
831 vput(nd.ni_dvp);
832 if (error) {
833 vn_finished_write(mp);
834 goto done;
835 }
836 vp = nd.ni_vp;
837 ASSERT_VOP_LOCKED(vp, "unp_bind");
838 soun = (struct sockaddr_un *)sodupsockaddr(nam, M_WAITOK);
839 UNP_LOCK();
840 vp->v_socket = unp->unp_socket;
841 unp->unp_vnode = vp;
842 unp->unp_addr = soun;
843 UNP_UNLOCK();
844 VOP_UNLOCK(vp, 0, td);
845 vn_finished_write(mp);
846done:
847 mtx_unlock(&Giant);
848 free(buf, M_TEMP);
849 UNP_LOCK();
850 return (error);
851}
852
853static int
854unp_connect(struct socket *so, struct sockaddr *nam, struct thread *td)
855{
856 struct sockaddr_un *soun = (struct sockaddr_un *)nam;
857 struct vnode *vp;
858 struct socket *so2, *so3;
859 struct unpcb *unp, *unp2, *unp3;
860 int error, len;
861 struct nameidata nd;
862 char buf[SOCK_MAXADDRLEN];
863 struct sockaddr *sa;
864
865 UNP_LOCK_ASSERT();
866
867 unp = sotounpcb(so);
868 KASSERT(unp != NULL, ("unp_connect: unp == NULL"));
869 len = nam->sa_len - offsetof(struct sockaddr_un, sun_path);
870 if (len <= 0)
871 return (EINVAL);
872 strlcpy(buf, soun->sun_path, len + 1);
873 UNP_UNLOCK();
874 sa = malloc(sizeof(struct sockaddr_un), M_SONAME, M_WAITOK);
875 mtx_lock(&Giant);
876 NDINIT(&nd, LOOKUP, FOLLOW | LOCKLEAF, UIO_SYSSPACE, buf, td);
877 error = namei(&nd);
878 if (error)
879 vp = NULL;
880 else
881 vp = nd.ni_vp;
882 ASSERT_VOP_LOCKED(vp, "unp_connect");
883 NDFREE(&nd, NDF_ONLY_PNBUF);
884 if (error)
885 goto bad;
886
887 if (vp->v_type != VSOCK) {
888 error = ENOTSOCK;
889 goto bad;
890 }
891 error = VOP_ACCESS(vp, VWRITE, td->td_ucred, td);
892 if (error)
893 goto bad;
894 mtx_unlock(&Giant);
895 UNP_LOCK();
896 unp = sotounpcb(so);
897 KASSERT(unp != NULL, ("unp_connect: unp == NULL"));
898 so2 = vp->v_socket;
899 if (so2 == NULL) {
900 error = ECONNREFUSED;
901 goto bad2;
902 }
903 if (so->so_type != so2->so_type) {
904 error = EPROTOTYPE;
905 goto bad2;
906 }
907 if (so->so_proto->pr_flags & PR_CONNREQUIRED) {
908 if (so2->so_options & SO_ACCEPTCONN) {
909 /*
910 * NB: drop locks here so unp_attach is entered
911 * w/o locks; this avoids a recursive lock
912 * of the head and holding sleep locks across
913 * a (potentially) blocking malloc.
914 */
915 UNP_UNLOCK();
916 so3 = sonewconn(so2, 0);
917 UNP_LOCK();
918 } else
919 so3 = NULL;
920 if (so3 == NULL) {
921 error = ECONNREFUSED;
922 goto bad2;
923 }
924 unp = sotounpcb(so);
925 unp2 = sotounpcb(so2);
926 unp3 = sotounpcb(so3);
927 if (unp2->unp_addr != NULL) {
928 bcopy(unp2->unp_addr, sa, unp2->unp_addr->sun_len);
929 unp3->unp_addr = (struct sockaddr_un *) sa;
930 sa = NULL;
931 }
932 /*
933 * unp_peercred management:
934 *
935 * The connecter's (client's) credentials are copied
936 * from its process structure at the time of connect()
937 * (which is now).
938 */
939 cru2x(td->td_ucred, &unp3->unp_peercred);
940 unp3->unp_flags |= UNP_HAVEPC;
941 /*
942 * The receiver's (server's) credentials are copied
943 * from the unp_peercred member of socket on which the
944 * former called listen(); unp_listen() cached that
945 * process's credentials at that time so we can use
946 * them now.
947 */
948 KASSERT(unp2->unp_flags & UNP_HAVEPCCACHED,
949 ("unp_connect: listener without cached peercred"));
950 memcpy(&unp->unp_peercred, &unp2->unp_peercred,
951 sizeof(unp->unp_peercred));
952 unp->unp_flags |= UNP_HAVEPC;
953 if (unp2->unp_flags & UNP_WANTCRED)
954 unp3->unp_flags |= UNP_WANTCRED;
953#ifdef MAC
954 SOCK_LOCK(so);
955 mac_set_socket_peer_from_socket(so, so3);
956 mac_set_socket_peer_from_socket(so3, so);
957 SOCK_UNLOCK(so);
958#endif
959
960 so2 = so3;
961 }
962 error = unp_connect2(so, so2, PRU_CONNECT);
963bad2:
964 UNP_UNLOCK();
965 mtx_lock(&Giant);
966bad:
967 mtx_assert(&Giant, MA_OWNED);
968 if (vp != NULL)
969 vput(vp);
970 mtx_unlock(&Giant);
971 free(sa, M_SONAME);
972 UNP_LOCK();
973 return (error);
974}
975
976static int
977unp_connect2(struct socket *so, struct socket *so2, int req)
978{
979 struct unpcb *unp = sotounpcb(so);
980 struct unpcb *unp2;
981
982 UNP_LOCK_ASSERT();
983
984 if (so2->so_type != so->so_type)
985 return (EPROTOTYPE);
986 unp2 = sotounpcb(so2);
987 KASSERT(unp2 != NULL, ("unp_connect2: unp2 == NULL"));
988 unp->unp_conn = unp2;
989 switch (so->so_type) {
990
991 case SOCK_DGRAM:
992 LIST_INSERT_HEAD(&unp2->unp_refs, unp, unp_reflink);
993 soisconnected(so);
994 break;
995
996 case SOCK_STREAM:
997 unp2->unp_conn = unp;
998 if (req == PRU_CONNECT &&
999 ((unp->unp_flags | unp2->unp_flags) & UNP_CONNWAIT))
1000 soisconnecting(so);
1001 else
1002 soisconnected(so);
1003 soisconnected(so2);
1004 break;
1005
1006 default:
1007 panic("unp_connect2");
1008 }
1009 return (0);
1010}
1011
1012static void
1013unp_disconnect(struct unpcb *unp)
1014{
1015 struct unpcb *unp2 = unp->unp_conn;
1016 struct socket *so;
1017
1018 UNP_LOCK_ASSERT();
1019
1020 if (unp2 == NULL)
1021 return;
1022 unp->unp_conn = NULL;
1023 switch (unp->unp_socket->so_type) {
1024 case SOCK_DGRAM:
1025 LIST_REMOVE(unp, unp_reflink);
1026 so = unp->unp_socket;
1027 SOCK_LOCK(so);
1028 so->so_state &= ~SS_ISCONNECTED;
1029 SOCK_UNLOCK(so);
1030 break;
1031
1032 case SOCK_STREAM:
1033 soisdisconnected(unp->unp_socket);
1034 unp2->unp_conn = NULL;
1035 soisdisconnected(unp2->unp_socket);
1036 break;
1037 }
1038}
1039
1040#ifdef notdef
1041void
1042unp_abort(struct unpcb *unp)
1043{
1044
1045 unp_detach(unp);
1046 UNP_UNLOCK_ASSERT();
1047}
1048#endif
1049
1050/*
1051 * unp_pcblist() assumes that UNIX domain socket memory is never reclaimed
1052 * by the zone (UMA_ZONE_NOFREE), and as such potentially stale pointers
1053 * are safe to reference. It first scans the list of struct unpcb's to
1054 * generate a pointer list, then it rescans its list one entry at a time to
1055 * externalize and copyout. It checks the generation number to see if a
1056 * struct unpcb has been reused, and will skip it if so.
1057 */
1058static int
1059unp_pcblist(SYSCTL_HANDLER_ARGS)
1060{
1061 int error, i, n;
1062 struct unpcb *unp, **unp_list;
1063 unp_gen_t gencnt;
1064 struct xunpgen *xug;
1065 struct unp_head *head;
1066 struct xunpcb *xu;
1067
1068 head = ((intptr_t)arg1 == SOCK_DGRAM ? &unp_dhead : &unp_shead);
1069
1070 /*
1071 * The process of preparing the PCB list is too time-consuming and
1072 * resource-intensive to repeat twice on every request.
1073 */
1074 if (req->oldptr == NULL) {
1075 n = unp_count;
1076 req->oldidx = 2 * (sizeof *xug)
1077 + (n + n/8) * sizeof(struct xunpcb);
1078 return (0);
1079 }
1080
1081 if (req->newptr != NULL)
1082 return (EPERM);
1083
1084 /*
1085 * OK, now we're committed to doing something.
1086 */
1087 xug = malloc(sizeof(*xug), M_TEMP, M_WAITOK);
1088 UNP_LOCK();
1089 gencnt = unp_gencnt;
1090 n = unp_count;
1091 UNP_UNLOCK();
1092
1093 xug->xug_len = sizeof *xug;
1094 xug->xug_count = n;
1095 xug->xug_gen = gencnt;
1096 xug->xug_sogen = so_gencnt;
1097 error = SYSCTL_OUT(req, xug, sizeof *xug);
1098 if (error) {
1099 free(xug, M_TEMP);
1100 return (error);
1101 }
1102
1103 unp_list = malloc(n * sizeof *unp_list, M_TEMP, M_WAITOK);
1104
1105 UNP_LOCK();
1106 for (unp = LIST_FIRST(head), i = 0; unp && i < n;
1107 unp = LIST_NEXT(unp, unp_link)) {
1108 if (unp->unp_gencnt <= gencnt) {
1109 if (cr_cansee(req->td->td_ucred,
1110 unp->unp_socket->so_cred))
1111 continue;
1112 unp_list[i++] = unp;
1113 }
1114 }
1115 UNP_UNLOCK();
1116 n = i; /* in case we lost some during malloc */
1117
1118 error = 0;
1119 xu = malloc(sizeof(*xu), M_TEMP, M_WAITOK | M_ZERO);
1120 for (i = 0; i < n; i++) {
1121 unp = unp_list[i];
1122 if (unp->unp_gencnt <= gencnt) {
1123 xu->xu_len = sizeof *xu;
1124 xu->xu_unpp = unp;
1125 /*
1126 * XXX - need more locking here to protect against
1127 * connect/disconnect races for SMP.
1128 */
1129 if (unp->unp_addr != NULL)
1130 bcopy(unp->unp_addr, &xu->xu_addr,
1131 unp->unp_addr->sun_len);
1132 if (unp->unp_conn != NULL &&
1133 unp->unp_conn->unp_addr != NULL)
1134 bcopy(unp->unp_conn->unp_addr,
1135 &xu->xu_caddr,
1136 unp->unp_conn->unp_addr->sun_len);
1137 bcopy(unp, &xu->xu_unp, sizeof *unp);
1138 sotoxsocket(unp->unp_socket, &xu->xu_socket);
1139 error = SYSCTL_OUT(req, xu, sizeof *xu);
1140 }
1141 }
1142 free(xu, M_TEMP);
1143 if (!error) {
1144 /*
1145 * Give the user an updated idea of our state.
1146 * If the generation differs from what we told
1147 * her before, she knows that something happened
1148 * while we were processing this request, and it
1149 * might be necessary to retry.
1150 */
1151 xug->xug_gen = unp_gencnt;
1152 xug->xug_sogen = so_gencnt;
1153 xug->xug_count = unp_count;
1154 error = SYSCTL_OUT(req, xug, sizeof *xug);
1155 }
1156 free(unp_list, M_TEMP);
1157 free(xug, M_TEMP);
1158 return (error);
1159}
1160
1161SYSCTL_PROC(_net_local_dgram, OID_AUTO, pcblist, CTLFLAG_RD,
1162 (caddr_t)(long)SOCK_DGRAM, 0, unp_pcblist, "S,xunpcb",
1163 "List of active local datagram sockets");
1164SYSCTL_PROC(_net_local_stream, OID_AUTO, pcblist, CTLFLAG_RD,
1165 (caddr_t)(long)SOCK_STREAM, 0, unp_pcblist, "S,xunpcb",
1166 "List of active local stream sockets");
1167
1168static void
1169unp_shutdown(struct unpcb *unp)
1170{
1171 struct socket *so;
1172
1173 UNP_LOCK_ASSERT();
1174
1175 if (unp->unp_socket->so_type == SOCK_STREAM && unp->unp_conn &&
1176 (so = unp->unp_conn->unp_socket))
1177 socantrcvmore(so);
1178}
1179
1180static void
1181unp_drop(struct unpcb *unp, int errno)
1182{
1183 struct socket *so = unp->unp_socket;
1184
1185 UNP_LOCK_ASSERT();
1186
1187 so->so_error = errno;
1188 unp_disconnect(unp);
1189}
1190
1191#ifdef notdef
1192void
1193unp_drain(void)
1194{
1195
1196}
1197#endif
1198
1199static void
1200unp_freerights(struct file **rp, int fdcount)
1201{
1202 int i;
1203 struct file *fp;
1204
1205 for (i = 0; i < fdcount; i++) {
1206 fp = *rp;
1207 /*
1208 * zero the pointer before calling
1209 * unp_discard since it may end up
1210 * in unp_gc()..
1211 *
1212 * XXXRW: This is less true than it used to be.
1213 */
1214 *rp++ = 0;
1215 unp_discard(fp);
1216 }
1217}
1218
1219int
1220unp_externalize(struct mbuf *control, struct mbuf **controlp)
1221{
1222 struct thread *td = curthread; /* XXX */
1223 struct cmsghdr *cm = mtod(control, struct cmsghdr *);
1224 int i;
1225 int *fdp;
1226 struct file **rp;
1227 struct file *fp;
1228 void *data;
1229 socklen_t clen = control->m_len, datalen;
1230 int error, newfds;
1231 int f;
1232 u_int newlen;
1233
1234 UNP_UNLOCK_ASSERT();
1235
1236 error = 0;
1237 if (controlp != NULL) /* controlp == NULL => free control messages */
1238 *controlp = NULL;
1239
1240 while (cm != NULL) {
1241 if (sizeof(*cm) > clen || cm->cmsg_len > clen) {
1242 error = EINVAL;
1243 break;
1244 }
1245
1246 data = CMSG_DATA(cm);
1247 datalen = (caddr_t)cm + cm->cmsg_len - (caddr_t)data;
1248
1249 if (cm->cmsg_level == SOL_SOCKET
1250 && cm->cmsg_type == SCM_RIGHTS) {
1251 newfds = datalen / sizeof(struct file *);
1252 rp = data;
1253
1254 /* If we're not outputting the descriptors free them. */
1255 if (error || controlp == NULL) {
1256 unp_freerights(rp, newfds);
1257 goto next;
1258 }
1259 FILEDESC_LOCK(td->td_proc->p_fd);
1260 /* if the new FD's will not fit free them. */
1261 if (!fdavail(td, newfds)) {
1262 FILEDESC_UNLOCK(td->td_proc->p_fd);
1263 error = EMSGSIZE;
1264 unp_freerights(rp, newfds);
1265 goto next;
1266 }
1267 /*
1268 * now change each pointer to an fd in the global
1269 * table to an integer that is the index to the
1270 * local fd table entry that we set up to point
1271 * to the global one we are transferring.
1272 */
1273 newlen = newfds * sizeof(int);
1274 *controlp = sbcreatecontrol(NULL, newlen,
1275 SCM_RIGHTS, SOL_SOCKET);
1276 if (*controlp == NULL) {
1277 FILEDESC_UNLOCK(td->td_proc->p_fd);
1278 error = E2BIG;
1279 unp_freerights(rp, newfds);
1280 goto next;
1281 }
1282
1283 fdp = (int *)
1284 CMSG_DATA(mtod(*controlp, struct cmsghdr *));
1285 for (i = 0; i < newfds; i++) {
1286 if (fdalloc(td, 0, &f))
1287 panic("unp_externalize fdalloc failed");
1288 fp = *rp++;
1289 td->td_proc->p_fd->fd_ofiles[f] = fp;
1290 FILE_LOCK(fp);
1291 fp->f_msgcount--;
1292 FILE_UNLOCK(fp);
1293 unp_rights--;
1294 *fdp++ = f;
1295 }
1296 FILEDESC_UNLOCK(td->td_proc->p_fd);
1297 } else { /* We can just copy anything else across */
1298 if (error || controlp == NULL)
1299 goto next;
1300 *controlp = sbcreatecontrol(NULL, datalen,
1301 cm->cmsg_type, cm->cmsg_level);
1302 if (*controlp == NULL) {
1303 error = ENOBUFS;
1304 goto next;
1305 }
1306 bcopy(data,
1307 CMSG_DATA(mtod(*controlp, struct cmsghdr *)),
1308 datalen);
1309 }
1310
1311 controlp = &(*controlp)->m_next;
1312
1313next:
1314 if (CMSG_SPACE(datalen) < clen) {
1315 clen -= CMSG_SPACE(datalen);
1316 cm = (struct cmsghdr *)
1317 ((caddr_t)cm + CMSG_SPACE(datalen));
1318 } else {
1319 clen = 0;
1320 cm = NULL;
1321 }
1322 }
1323
1324 m_freem(control);
1325
1326 return (error);
1327}
1328
1329static void
1330unp_zone_change(void *tag)
1331{
1332
1333 uma_zone_set_max(unp_zone, maxsockets);
1334}
1335
1336void
1337unp_init(void)
1338{
1339 unp_zone = uma_zcreate("unpcb", sizeof(struct unpcb), NULL, NULL,
1340 NULL, NULL, UMA_ALIGN_PTR, UMA_ZONE_NOFREE);
1341 if (unp_zone == NULL)
1342 panic("unp_init");
1343 uma_zone_set_max(unp_zone, maxsockets);
1344 EVENTHANDLER_REGISTER(maxsockets_change, unp_zone_change,
1345 NULL, EVENTHANDLER_PRI_ANY);
1346 LIST_INIT(&unp_dhead);
1347 LIST_INIT(&unp_shead);
1348 TASK_INIT(&unp_gc_task, 0, unp_gc, NULL);
1349 UNP_LOCK_INIT();
1350}
1351
1352static int
1353unp_internalize(struct mbuf **controlp, struct thread *td)
1354{
1355 struct mbuf *control = *controlp;
1356 struct proc *p = td->td_proc;
1357 struct filedesc *fdescp = p->p_fd;
1358 struct cmsghdr *cm = mtod(control, struct cmsghdr *);
1359 struct cmsgcred *cmcred;
1360 struct file **rp;
1361 struct file *fp;
1362 struct timeval *tv;
1363 int i, fd, *fdp;
1364 void *data;
1365 socklen_t clen = control->m_len, datalen;
1366 int error, oldfds;
1367 u_int newlen;
1368
1369 UNP_UNLOCK_ASSERT();
1370
1371 error = 0;
1372 *controlp = NULL;
1373
1374 while (cm != NULL) {
1375 if (sizeof(*cm) > clen || cm->cmsg_level != SOL_SOCKET
1376 || cm->cmsg_len > clen) {
1377 error = EINVAL;
1378 goto out;
1379 }
1380
1381 data = CMSG_DATA(cm);
1382 datalen = (caddr_t)cm + cm->cmsg_len - (caddr_t)data;
1383
1384 switch (cm->cmsg_type) {
1385 /*
1386 * Fill in credential information.
1387 */
1388 case SCM_CREDS:
1389 *controlp = sbcreatecontrol(NULL, sizeof(*cmcred),
1390 SCM_CREDS, SOL_SOCKET);
1391 if (*controlp == NULL) {
1392 error = ENOBUFS;
1393 goto out;
1394 }
1395
1396 cmcred = (struct cmsgcred *)
1397 CMSG_DATA(mtod(*controlp, struct cmsghdr *));
1398 cmcred->cmcred_pid = p->p_pid;
1399 cmcred->cmcred_uid = td->td_ucred->cr_ruid;
1400 cmcred->cmcred_gid = td->td_ucred->cr_rgid;
1401 cmcred->cmcred_euid = td->td_ucred->cr_uid;
1402 cmcred->cmcred_ngroups = MIN(td->td_ucred->cr_ngroups,
1403 CMGROUP_MAX);
1404 for (i = 0; i < cmcred->cmcred_ngroups; i++)
1405 cmcred->cmcred_groups[i] =
1406 td->td_ucred->cr_groups[i];
1407 break;
1408
1409 case SCM_RIGHTS:
1410 oldfds = datalen / sizeof (int);
1411 /*
1412 * check that all the FDs passed in refer to legal files
1413 * If not, reject the entire operation.
1414 */
1415 fdp = data;
1416 FILEDESC_LOCK(fdescp);
1417 for (i = 0; i < oldfds; i++) {
1418 fd = *fdp++;
1419 if ((unsigned)fd >= fdescp->fd_nfiles ||
1420 fdescp->fd_ofiles[fd] == NULL) {
1421 FILEDESC_UNLOCK(fdescp);
1422 error = EBADF;
1423 goto out;
1424 }
1425 fp = fdescp->fd_ofiles[fd];
1426 if (!(fp->f_ops->fo_flags & DFLAG_PASSABLE)) {
1427 FILEDESC_UNLOCK(fdescp);
1428 error = EOPNOTSUPP;
1429 goto out;
1430 }
1431
1432 }
1433 /*
1434 * Now replace the integer FDs with pointers to
1435 * the associated global file table entry..
1436 */
1437 newlen = oldfds * sizeof(struct file *);
1438 *controlp = sbcreatecontrol(NULL, newlen,
1439 SCM_RIGHTS, SOL_SOCKET);
1440 if (*controlp == NULL) {
1441 FILEDESC_UNLOCK(fdescp);
1442 error = E2BIG;
1443 goto out;
1444 }
1445
1446 fdp = data;
1447 rp = (struct file **)
1448 CMSG_DATA(mtod(*controlp, struct cmsghdr *));
1449 for (i = 0; i < oldfds; i++) {
1450 fp = fdescp->fd_ofiles[*fdp++];
1451 *rp++ = fp;
1452 FILE_LOCK(fp);
1453 fp->f_count++;
1454 fp->f_msgcount++;
1455 FILE_UNLOCK(fp);
1456 unp_rights++;
1457 }
1458 FILEDESC_UNLOCK(fdescp);
1459 break;
1460
1461 case SCM_TIMESTAMP:
1462 *controlp = sbcreatecontrol(NULL, sizeof(*tv),
1463 SCM_TIMESTAMP, SOL_SOCKET);
1464 if (*controlp == NULL) {
1465 error = ENOBUFS;
1466 goto out;
1467 }
1468 tv = (struct timeval *)
1469 CMSG_DATA(mtod(*controlp, struct cmsghdr *));
1470 microtime(tv);
1471 break;
1472
1473 default:
1474 error = EINVAL;
1475 goto out;
1476 }
1477
1478 controlp = &(*controlp)->m_next;
1479
1480 if (CMSG_SPACE(datalen) < clen) {
1481 clen -= CMSG_SPACE(datalen);
1482 cm = (struct cmsghdr *)
1483 ((caddr_t)cm + CMSG_SPACE(datalen));
1484 } else {
1485 clen = 0;
1486 cm = NULL;
1487 }
1488 }
1489
1490out:
1491 m_freem(control);
1492
1493 return (error);
1494}
1495
1496struct mbuf *
1497unp_addsockcred(struct thread *td, struct mbuf *control)
1498{
1499 struct mbuf *m, *n;
1500 struct sockcred *sc;
1501 int ngroups;
1502 int i;
1503
1504 ngroups = MIN(td->td_ucred->cr_ngroups, CMGROUP_MAX);
1505
1506 m = sbcreatecontrol(NULL, SOCKCREDSIZE(ngroups), SCM_CREDS, SOL_SOCKET);
1507 if (m == NULL)
1508 return (control);
1509 m->m_next = NULL;
1510
1511 sc = (struct sockcred *) CMSG_DATA(mtod(m, struct cmsghdr *));
1512 sc->sc_uid = td->td_ucred->cr_ruid;
1513 sc->sc_euid = td->td_ucred->cr_uid;
1514 sc->sc_gid = td->td_ucred->cr_rgid;
1515 sc->sc_egid = td->td_ucred->cr_gid;
1516 sc->sc_ngroups = ngroups;
1517 for (i = 0; i < sc->sc_ngroups; i++)
1518 sc->sc_groups[i] = td->td_ucred->cr_groups[i];
1519
1520 /*
1521 * If a control message already exists, append us to the end.
1522 */
1523 if (control != NULL) {
1524 for (n = control; n->m_next != NULL; n = n->m_next)
1525 ;
1526 n->m_next = m;
1527 } else
1528 control = m;
1529
1530 return (control);
1531}
1532
1533/*
1534 * unp_defer indicates whether additional work has been defered for a future
1535 * pass through unp_gc(). It is thread local and does not require explicit
1536 * synchronization.
1537 */
1538static int unp_defer;
1539
1540static int unp_taskcount;
1541SYSCTL_INT(_net_local, OID_AUTO, taskcount, CTLFLAG_RD, &unp_taskcount, 0, "");
1542
1543static int unp_recycled;
1544SYSCTL_INT(_net_local, OID_AUTO, recycled, CTLFLAG_RD, &unp_recycled, 0, "");
1545
1546static void
1547unp_gc(__unused void *arg, int pending)
1548{
1549 struct file *fp, *nextfp;
1550 struct socket *so;
1551 struct file **extra_ref, **fpp;
1552 int nunref, i;
1553 int nfiles_snap;
1554 int nfiles_slack = 20;
1555
1556 unp_taskcount++;
1557 unp_defer = 0;
1558 /*
1559 * before going through all this, set all FDs to
1560 * be NOT defered and NOT externally accessible
1561 */
1562 sx_slock(&filelist_lock);
1563 LIST_FOREACH(fp, &filehead, f_list)
1564 fp->f_gcflag &= ~(FMARK|FDEFER);
1565 do {
1566 KASSERT(unp_defer >= 0, ("unp_gc: unp_defer %d", unp_defer));
1567 LIST_FOREACH(fp, &filehead, f_list) {
1568 FILE_LOCK(fp);
1569 /*
1570 * If the file is not open, skip it -- could be a
1571 * file in the process of being opened, or in the
1572 * process of being closed. If the file is
1573 * "closing", it may have been marked for deferred
1574 * consideration. Clear the flag now if so.
1575 */
1576 if (fp->f_count == 0) {
1577 if (fp->f_gcflag & FDEFER)
1578 unp_defer--;
1579 fp->f_gcflag &= ~(FMARK|FDEFER);
1580 FILE_UNLOCK(fp);
1581 continue;
1582 }
1583 /*
1584 * If we already marked it as 'defer' in a
1585 * previous pass, then try process it this time
1586 * and un-mark it
1587 */
1588 if (fp->f_gcflag & FDEFER) {
1589 fp->f_gcflag &= ~FDEFER;
1590 unp_defer--;
1591 } else {
1592 /*
1593 * if it's not defered, then check if it's
1594 * already marked.. if so skip it
1595 */
1596 if (fp->f_gcflag & FMARK) {
1597 FILE_UNLOCK(fp);
1598 continue;
1599 }
1600 /*
1601 * If all references are from messages
1602 * in transit, then skip it. it's not
1603 * externally accessible.
1604 */
1605 if (fp->f_count == fp->f_msgcount) {
1606 FILE_UNLOCK(fp);
1607 continue;
1608 }
1609 /*
1610 * If it got this far then it must be
1611 * externally accessible.
1612 */
1613 fp->f_gcflag |= FMARK;
1614 }
1615 /*
1616 * either it was defered, or it is externally
1617 * accessible and not already marked so.
1618 * Now check if it is possibly one of OUR sockets.
1619 */
1620 if (fp->f_type != DTYPE_SOCKET ||
1621 (so = fp->f_data) == NULL) {
1622 FILE_UNLOCK(fp);
1623 continue;
1624 }
1625 FILE_UNLOCK(fp);
1626 if (so->so_proto->pr_domain != &localdomain ||
1627 (so->so_proto->pr_flags&PR_RIGHTS) == 0)
1628 continue;
1629 /*
1630 * So, Ok, it's one of our sockets and it IS externally
1631 * accessible (or was defered). Now we look
1632 * to see if we hold any file descriptors in its
1633 * message buffers. Follow those links and mark them
1634 * as accessible too.
1635 */
1636 SOCKBUF_LOCK(&so->so_rcv);
1637 unp_scan(so->so_rcv.sb_mb, unp_mark);
1638 SOCKBUF_UNLOCK(&so->so_rcv);
1639 }
1640 } while (unp_defer);
1641 sx_sunlock(&filelist_lock);
1642 /*
1643 * XXXRW: The following comments need updating for a post-SMPng and
1644 * deferred unp_gc() world, but are still generally accurate.
1645 *
1646 * We grab an extra reference to each of the file table entries
1647 * that are not otherwise accessible and then free the rights
1648 * that are stored in messages on them.
1649 *
1650 * The bug in the orginal code is a little tricky, so I'll describe
1651 * what's wrong with it here.
1652 *
1653 * It is incorrect to simply unp_discard each entry for f_msgcount
1654 * times -- consider the case of sockets A and B that contain
1655 * references to each other. On a last close of some other socket,
1656 * we trigger a gc since the number of outstanding rights (unp_rights)
1657 * is non-zero. If during the sweep phase the gc code unp_discards,
1658 * we end up doing a (full) closef on the descriptor. A closef on A
1659 * results in the following chain. Closef calls soo_close, which
1660 * calls soclose. Soclose calls first (through the switch
1661 * uipc_usrreq) unp_detach, which re-invokes unp_gc. Unp_gc simply
1662 * returns because the previous instance had set unp_gcing, and
1663 * we return all the way back to soclose, which marks the socket
1664 * with SS_NOFDREF, and then calls sofree. Sofree calls sorflush
1665 * to free up the rights that are queued in messages on the socket A,
1666 * i.e., the reference on B. The sorflush calls via the dom_dispose
1667 * switch unp_dispose, which unp_scans with unp_discard. This second
1668 * instance of unp_discard just calls closef on B.
1669 *
1670 * Well, a similar chain occurs on B, resulting in a sorflush on B,
1671 * which results in another closef on A. Unfortunately, A is already
1672 * being closed, and the descriptor has already been marked with
1673 * SS_NOFDREF, and soclose panics at this point.
1674 *
1675 * Here, we first take an extra reference to each inaccessible
1676 * descriptor. Then, we call sorflush ourself, since we know
1677 * it is a Unix domain socket anyhow. After we destroy all the
1678 * rights carried in messages, we do a last closef to get rid
1679 * of our extra reference. This is the last close, and the
1680 * unp_detach etc will shut down the socket.
1681 *
1682 * 91/09/19, bsy@cs.cmu.edu
1683 */
1684again:
1685 nfiles_snap = openfiles + nfiles_slack; /* some slack */
1686 extra_ref = malloc(nfiles_snap * sizeof(struct file *), M_TEMP,
1687 M_WAITOK);
1688 sx_slock(&filelist_lock);
1689 if (nfiles_snap < openfiles) {
1690 sx_sunlock(&filelist_lock);
1691 free(extra_ref, M_TEMP);
1692 nfiles_slack += 20;
1693 goto again;
1694 }
1695 for (nunref = 0, fp = LIST_FIRST(&filehead), fpp = extra_ref;
1696 fp != NULL; fp = nextfp) {
1697 nextfp = LIST_NEXT(fp, f_list);
1698 FILE_LOCK(fp);
1699 /*
1700 * If it's not open, skip it
1701 */
1702 if (fp->f_count == 0) {
1703 FILE_UNLOCK(fp);
1704 continue;
1705 }
1706 /*
1707 * If all refs are from msgs, and it's not marked accessible
1708 * then it must be referenced from some unreachable cycle
1709 * of (shut-down) FDs, so include it in our
1710 * list of FDs to remove
1711 */
1712 if (fp->f_count == fp->f_msgcount && !(fp->f_gcflag & FMARK)) {
1713 *fpp++ = fp;
1714 nunref++;
1715 fp->f_count++;
1716 }
1717 FILE_UNLOCK(fp);
1718 }
1719 sx_sunlock(&filelist_lock);
1720 /*
1721 * for each FD on our hit list, do the following two things
1722 */
1723 for (i = nunref, fpp = extra_ref; --i >= 0; ++fpp) {
1724 struct file *tfp = *fpp;
1725 FILE_LOCK(tfp);
1726 if (tfp->f_type == DTYPE_SOCKET &&
1727 tfp->f_data != NULL) {
1728 FILE_UNLOCK(tfp);
1729 sorflush(tfp->f_data);
1730 } else {
1731 FILE_UNLOCK(tfp);
1732 }
1733 }
1734 for (i = nunref, fpp = extra_ref; --i >= 0; ++fpp) {
1735 closef(*fpp, (struct thread *) NULL);
1736 unp_recycled++;
1737 }
1738 free(extra_ref, M_TEMP);
1739}
1740
1741void
1742unp_dispose(struct mbuf *m)
1743{
1744
1745 if (m)
1746 unp_scan(m, unp_discard);
1747}
1748
1749static int
1750unp_listen(struct socket *so, struct unpcb *unp, int backlog,
1751 struct thread *td)
1752{
1753 int error;
1754
1755 UNP_LOCK_ASSERT();
1756
1757 SOCK_LOCK(so);
1758 error = solisten_proto_check(so);
1759 if (error == 0) {
1760 cru2x(td->td_ucred, &unp->unp_peercred);
1761 unp->unp_flags |= UNP_HAVEPCCACHED;
1762 solisten_proto(so, backlog);
1763 }
1764 SOCK_UNLOCK(so);
1765 return (error);
1766}
1767
1768static void
1769unp_scan(struct mbuf *m0, void (*op)(struct file *))
1770{
1771 struct mbuf *m;
1772 struct file **rp;
1773 struct cmsghdr *cm;
1774 void *data;
1775 int i;
1776 socklen_t clen, datalen;
1777 int qfds;
1778
1779 while (m0 != NULL) {
1780 for (m = m0; m; m = m->m_next) {
1781 if (m->m_type != MT_CONTROL)
1782 continue;
1783
1784 cm = mtod(m, struct cmsghdr *);
1785 clen = m->m_len;
1786
1787 while (cm != NULL) {
1788 if (sizeof(*cm) > clen || cm->cmsg_len > clen)
1789 break;
1790
1791 data = CMSG_DATA(cm);
1792 datalen = (caddr_t)cm + cm->cmsg_len
1793 - (caddr_t)data;
1794
1795 if (cm->cmsg_level == SOL_SOCKET &&
1796 cm->cmsg_type == SCM_RIGHTS) {
1797 qfds = datalen / sizeof (struct file *);
1798 rp = data;
1799 for (i = 0; i < qfds; i++)
1800 (*op)(*rp++);
1801 }
1802
1803 if (CMSG_SPACE(datalen) < clen) {
1804 clen -= CMSG_SPACE(datalen);
1805 cm = (struct cmsghdr *)
1806 ((caddr_t)cm + CMSG_SPACE(datalen));
1807 } else {
1808 clen = 0;
1809 cm = NULL;
1810 }
1811 }
1812 }
1813 m0 = m0->m_act;
1814 }
1815}
1816
1817static void
1818unp_mark(struct file *fp)
1819{
1820 if (fp->f_gcflag & FMARK)
1821 return;
1822 unp_defer++;
1823 fp->f_gcflag |= (FMARK|FDEFER);
1824}
1825
1826static void
1827unp_discard(struct file *fp)
1828{
1829 UNP_LOCK();
1830 FILE_LOCK(fp);
1831 fp->f_msgcount--;
1832 unp_rights--;
1833 FILE_UNLOCK(fp);
1834 UNP_UNLOCK();
1835 (void) closef(fp, (struct thread *)NULL);
1836}
955#ifdef MAC
956 SOCK_LOCK(so);
957 mac_set_socket_peer_from_socket(so, so3);
958 mac_set_socket_peer_from_socket(so3, so);
959 SOCK_UNLOCK(so);
960#endif
961
962 so2 = so3;
963 }
964 error = unp_connect2(so, so2, PRU_CONNECT);
965bad2:
966 UNP_UNLOCK();
967 mtx_lock(&Giant);
968bad:
969 mtx_assert(&Giant, MA_OWNED);
970 if (vp != NULL)
971 vput(vp);
972 mtx_unlock(&Giant);
973 free(sa, M_SONAME);
974 UNP_LOCK();
975 return (error);
976}
977
978static int
979unp_connect2(struct socket *so, struct socket *so2, int req)
980{
981 struct unpcb *unp = sotounpcb(so);
982 struct unpcb *unp2;
983
984 UNP_LOCK_ASSERT();
985
986 if (so2->so_type != so->so_type)
987 return (EPROTOTYPE);
988 unp2 = sotounpcb(so2);
989 KASSERT(unp2 != NULL, ("unp_connect2: unp2 == NULL"));
990 unp->unp_conn = unp2;
991 switch (so->so_type) {
992
993 case SOCK_DGRAM:
994 LIST_INSERT_HEAD(&unp2->unp_refs, unp, unp_reflink);
995 soisconnected(so);
996 break;
997
998 case SOCK_STREAM:
999 unp2->unp_conn = unp;
1000 if (req == PRU_CONNECT &&
1001 ((unp->unp_flags | unp2->unp_flags) & UNP_CONNWAIT))
1002 soisconnecting(so);
1003 else
1004 soisconnected(so);
1005 soisconnected(so2);
1006 break;
1007
1008 default:
1009 panic("unp_connect2");
1010 }
1011 return (0);
1012}
1013
1014static void
1015unp_disconnect(struct unpcb *unp)
1016{
1017 struct unpcb *unp2 = unp->unp_conn;
1018 struct socket *so;
1019
1020 UNP_LOCK_ASSERT();
1021
1022 if (unp2 == NULL)
1023 return;
1024 unp->unp_conn = NULL;
1025 switch (unp->unp_socket->so_type) {
1026 case SOCK_DGRAM:
1027 LIST_REMOVE(unp, unp_reflink);
1028 so = unp->unp_socket;
1029 SOCK_LOCK(so);
1030 so->so_state &= ~SS_ISCONNECTED;
1031 SOCK_UNLOCK(so);
1032 break;
1033
1034 case SOCK_STREAM:
1035 soisdisconnected(unp->unp_socket);
1036 unp2->unp_conn = NULL;
1037 soisdisconnected(unp2->unp_socket);
1038 break;
1039 }
1040}
1041
1042#ifdef notdef
1043void
1044unp_abort(struct unpcb *unp)
1045{
1046
1047 unp_detach(unp);
1048 UNP_UNLOCK_ASSERT();
1049}
1050#endif
1051
1052/*
1053 * unp_pcblist() assumes that UNIX domain socket memory is never reclaimed
1054 * by the zone (UMA_ZONE_NOFREE), and as such potentially stale pointers
1055 * are safe to reference. It first scans the list of struct unpcb's to
1056 * generate a pointer list, then it rescans its list one entry at a time to
1057 * externalize and copyout. It checks the generation number to see if a
1058 * struct unpcb has been reused, and will skip it if so.
1059 */
1060static int
1061unp_pcblist(SYSCTL_HANDLER_ARGS)
1062{
1063 int error, i, n;
1064 struct unpcb *unp, **unp_list;
1065 unp_gen_t gencnt;
1066 struct xunpgen *xug;
1067 struct unp_head *head;
1068 struct xunpcb *xu;
1069
1070 head = ((intptr_t)arg1 == SOCK_DGRAM ? &unp_dhead : &unp_shead);
1071
1072 /*
1073 * The process of preparing the PCB list is too time-consuming and
1074 * resource-intensive to repeat twice on every request.
1075 */
1076 if (req->oldptr == NULL) {
1077 n = unp_count;
1078 req->oldidx = 2 * (sizeof *xug)
1079 + (n + n/8) * sizeof(struct xunpcb);
1080 return (0);
1081 }
1082
1083 if (req->newptr != NULL)
1084 return (EPERM);
1085
1086 /*
1087 * OK, now we're committed to doing something.
1088 */
1089 xug = malloc(sizeof(*xug), M_TEMP, M_WAITOK);
1090 UNP_LOCK();
1091 gencnt = unp_gencnt;
1092 n = unp_count;
1093 UNP_UNLOCK();
1094
1095 xug->xug_len = sizeof *xug;
1096 xug->xug_count = n;
1097 xug->xug_gen = gencnt;
1098 xug->xug_sogen = so_gencnt;
1099 error = SYSCTL_OUT(req, xug, sizeof *xug);
1100 if (error) {
1101 free(xug, M_TEMP);
1102 return (error);
1103 }
1104
1105 unp_list = malloc(n * sizeof *unp_list, M_TEMP, M_WAITOK);
1106
1107 UNP_LOCK();
1108 for (unp = LIST_FIRST(head), i = 0; unp && i < n;
1109 unp = LIST_NEXT(unp, unp_link)) {
1110 if (unp->unp_gencnt <= gencnt) {
1111 if (cr_cansee(req->td->td_ucred,
1112 unp->unp_socket->so_cred))
1113 continue;
1114 unp_list[i++] = unp;
1115 }
1116 }
1117 UNP_UNLOCK();
1118 n = i; /* in case we lost some during malloc */
1119
1120 error = 0;
1121 xu = malloc(sizeof(*xu), M_TEMP, M_WAITOK | M_ZERO);
1122 for (i = 0; i < n; i++) {
1123 unp = unp_list[i];
1124 if (unp->unp_gencnt <= gencnt) {
1125 xu->xu_len = sizeof *xu;
1126 xu->xu_unpp = unp;
1127 /*
1128 * XXX - need more locking here to protect against
1129 * connect/disconnect races for SMP.
1130 */
1131 if (unp->unp_addr != NULL)
1132 bcopy(unp->unp_addr, &xu->xu_addr,
1133 unp->unp_addr->sun_len);
1134 if (unp->unp_conn != NULL &&
1135 unp->unp_conn->unp_addr != NULL)
1136 bcopy(unp->unp_conn->unp_addr,
1137 &xu->xu_caddr,
1138 unp->unp_conn->unp_addr->sun_len);
1139 bcopy(unp, &xu->xu_unp, sizeof *unp);
1140 sotoxsocket(unp->unp_socket, &xu->xu_socket);
1141 error = SYSCTL_OUT(req, xu, sizeof *xu);
1142 }
1143 }
1144 free(xu, M_TEMP);
1145 if (!error) {
1146 /*
1147 * Give the user an updated idea of our state.
1148 * If the generation differs from what we told
1149 * her before, she knows that something happened
1150 * while we were processing this request, and it
1151 * might be necessary to retry.
1152 */
1153 xug->xug_gen = unp_gencnt;
1154 xug->xug_sogen = so_gencnt;
1155 xug->xug_count = unp_count;
1156 error = SYSCTL_OUT(req, xug, sizeof *xug);
1157 }
1158 free(unp_list, M_TEMP);
1159 free(xug, M_TEMP);
1160 return (error);
1161}
1162
1163SYSCTL_PROC(_net_local_dgram, OID_AUTO, pcblist, CTLFLAG_RD,
1164 (caddr_t)(long)SOCK_DGRAM, 0, unp_pcblist, "S,xunpcb",
1165 "List of active local datagram sockets");
1166SYSCTL_PROC(_net_local_stream, OID_AUTO, pcblist, CTLFLAG_RD,
1167 (caddr_t)(long)SOCK_STREAM, 0, unp_pcblist, "S,xunpcb",
1168 "List of active local stream sockets");
1169
1170static void
1171unp_shutdown(struct unpcb *unp)
1172{
1173 struct socket *so;
1174
1175 UNP_LOCK_ASSERT();
1176
1177 if (unp->unp_socket->so_type == SOCK_STREAM && unp->unp_conn &&
1178 (so = unp->unp_conn->unp_socket))
1179 socantrcvmore(so);
1180}
1181
1182static void
1183unp_drop(struct unpcb *unp, int errno)
1184{
1185 struct socket *so = unp->unp_socket;
1186
1187 UNP_LOCK_ASSERT();
1188
1189 so->so_error = errno;
1190 unp_disconnect(unp);
1191}
1192
1193#ifdef notdef
1194void
1195unp_drain(void)
1196{
1197
1198}
1199#endif
1200
1201static void
1202unp_freerights(struct file **rp, int fdcount)
1203{
1204 int i;
1205 struct file *fp;
1206
1207 for (i = 0; i < fdcount; i++) {
1208 fp = *rp;
1209 /*
1210 * zero the pointer before calling
1211 * unp_discard since it may end up
1212 * in unp_gc()..
1213 *
1214 * XXXRW: This is less true than it used to be.
1215 */
1216 *rp++ = 0;
1217 unp_discard(fp);
1218 }
1219}
1220
1221int
1222unp_externalize(struct mbuf *control, struct mbuf **controlp)
1223{
1224 struct thread *td = curthread; /* XXX */
1225 struct cmsghdr *cm = mtod(control, struct cmsghdr *);
1226 int i;
1227 int *fdp;
1228 struct file **rp;
1229 struct file *fp;
1230 void *data;
1231 socklen_t clen = control->m_len, datalen;
1232 int error, newfds;
1233 int f;
1234 u_int newlen;
1235
1236 UNP_UNLOCK_ASSERT();
1237
1238 error = 0;
1239 if (controlp != NULL) /* controlp == NULL => free control messages */
1240 *controlp = NULL;
1241
1242 while (cm != NULL) {
1243 if (sizeof(*cm) > clen || cm->cmsg_len > clen) {
1244 error = EINVAL;
1245 break;
1246 }
1247
1248 data = CMSG_DATA(cm);
1249 datalen = (caddr_t)cm + cm->cmsg_len - (caddr_t)data;
1250
1251 if (cm->cmsg_level == SOL_SOCKET
1252 && cm->cmsg_type == SCM_RIGHTS) {
1253 newfds = datalen / sizeof(struct file *);
1254 rp = data;
1255
1256 /* If we're not outputting the descriptors free them. */
1257 if (error || controlp == NULL) {
1258 unp_freerights(rp, newfds);
1259 goto next;
1260 }
1261 FILEDESC_LOCK(td->td_proc->p_fd);
1262 /* if the new FD's will not fit free them. */
1263 if (!fdavail(td, newfds)) {
1264 FILEDESC_UNLOCK(td->td_proc->p_fd);
1265 error = EMSGSIZE;
1266 unp_freerights(rp, newfds);
1267 goto next;
1268 }
1269 /*
1270 * now change each pointer to an fd in the global
1271 * table to an integer that is the index to the
1272 * local fd table entry that we set up to point
1273 * to the global one we are transferring.
1274 */
1275 newlen = newfds * sizeof(int);
1276 *controlp = sbcreatecontrol(NULL, newlen,
1277 SCM_RIGHTS, SOL_SOCKET);
1278 if (*controlp == NULL) {
1279 FILEDESC_UNLOCK(td->td_proc->p_fd);
1280 error = E2BIG;
1281 unp_freerights(rp, newfds);
1282 goto next;
1283 }
1284
1285 fdp = (int *)
1286 CMSG_DATA(mtod(*controlp, struct cmsghdr *));
1287 for (i = 0; i < newfds; i++) {
1288 if (fdalloc(td, 0, &f))
1289 panic("unp_externalize fdalloc failed");
1290 fp = *rp++;
1291 td->td_proc->p_fd->fd_ofiles[f] = fp;
1292 FILE_LOCK(fp);
1293 fp->f_msgcount--;
1294 FILE_UNLOCK(fp);
1295 unp_rights--;
1296 *fdp++ = f;
1297 }
1298 FILEDESC_UNLOCK(td->td_proc->p_fd);
1299 } else { /* We can just copy anything else across */
1300 if (error || controlp == NULL)
1301 goto next;
1302 *controlp = sbcreatecontrol(NULL, datalen,
1303 cm->cmsg_type, cm->cmsg_level);
1304 if (*controlp == NULL) {
1305 error = ENOBUFS;
1306 goto next;
1307 }
1308 bcopy(data,
1309 CMSG_DATA(mtod(*controlp, struct cmsghdr *)),
1310 datalen);
1311 }
1312
1313 controlp = &(*controlp)->m_next;
1314
1315next:
1316 if (CMSG_SPACE(datalen) < clen) {
1317 clen -= CMSG_SPACE(datalen);
1318 cm = (struct cmsghdr *)
1319 ((caddr_t)cm + CMSG_SPACE(datalen));
1320 } else {
1321 clen = 0;
1322 cm = NULL;
1323 }
1324 }
1325
1326 m_freem(control);
1327
1328 return (error);
1329}
1330
1331static void
1332unp_zone_change(void *tag)
1333{
1334
1335 uma_zone_set_max(unp_zone, maxsockets);
1336}
1337
1338void
1339unp_init(void)
1340{
1341 unp_zone = uma_zcreate("unpcb", sizeof(struct unpcb), NULL, NULL,
1342 NULL, NULL, UMA_ALIGN_PTR, UMA_ZONE_NOFREE);
1343 if (unp_zone == NULL)
1344 panic("unp_init");
1345 uma_zone_set_max(unp_zone, maxsockets);
1346 EVENTHANDLER_REGISTER(maxsockets_change, unp_zone_change,
1347 NULL, EVENTHANDLER_PRI_ANY);
1348 LIST_INIT(&unp_dhead);
1349 LIST_INIT(&unp_shead);
1350 TASK_INIT(&unp_gc_task, 0, unp_gc, NULL);
1351 UNP_LOCK_INIT();
1352}
1353
1354static int
1355unp_internalize(struct mbuf **controlp, struct thread *td)
1356{
1357 struct mbuf *control = *controlp;
1358 struct proc *p = td->td_proc;
1359 struct filedesc *fdescp = p->p_fd;
1360 struct cmsghdr *cm = mtod(control, struct cmsghdr *);
1361 struct cmsgcred *cmcred;
1362 struct file **rp;
1363 struct file *fp;
1364 struct timeval *tv;
1365 int i, fd, *fdp;
1366 void *data;
1367 socklen_t clen = control->m_len, datalen;
1368 int error, oldfds;
1369 u_int newlen;
1370
1371 UNP_UNLOCK_ASSERT();
1372
1373 error = 0;
1374 *controlp = NULL;
1375
1376 while (cm != NULL) {
1377 if (sizeof(*cm) > clen || cm->cmsg_level != SOL_SOCKET
1378 || cm->cmsg_len > clen) {
1379 error = EINVAL;
1380 goto out;
1381 }
1382
1383 data = CMSG_DATA(cm);
1384 datalen = (caddr_t)cm + cm->cmsg_len - (caddr_t)data;
1385
1386 switch (cm->cmsg_type) {
1387 /*
1388 * Fill in credential information.
1389 */
1390 case SCM_CREDS:
1391 *controlp = sbcreatecontrol(NULL, sizeof(*cmcred),
1392 SCM_CREDS, SOL_SOCKET);
1393 if (*controlp == NULL) {
1394 error = ENOBUFS;
1395 goto out;
1396 }
1397
1398 cmcred = (struct cmsgcred *)
1399 CMSG_DATA(mtod(*controlp, struct cmsghdr *));
1400 cmcred->cmcred_pid = p->p_pid;
1401 cmcred->cmcred_uid = td->td_ucred->cr_ruid;
1402 cmcred->cmcred_gid = td->td_ucred->cr_rgid;
1403 cmcred->cmcred_euid = td->td_ucred->cr_uid;
1404 cmcred->cmcred_ngroups = MIN(td->td_ucred->cr_ngroups,
1405 CMGROUP_MAX);
1406 for (i = 0; i < cmcred->cmcred_ngroups; i++)
1407 cmcred->cmcred_groups[i] =
1408 td->td_ucred->cr_groups[i];
1409 break;
1410
1411 case SCM_RIGHTS:
1412 oldfds = datalen / sizeof (int);
1413 /*
1414 * check that all the FDs passed in refer to legal files
1415 * If not, reject the entire operation.
1416 */
1417 fdp = data;
1418 FILEDESC_LOCK(fdescp);
1419 for (i = 0; i < oldfds; i++) {
1420 fd = *fdp++;
1421 if ((unsigned)fd >= fdescp->fd_nfiles ||
1422 fdescp->fd_ofiles[fd] == NULL) {
1423 FILEDESC_UNLOCK(fdescp);
1424 error = EBADF;
1425 goto out;
1426 }
1427 fp = fdescp->fd_ofiles[fd];
1428 if (!(fp->f_ops->fo_flags & DFLAG_PASSABLE)) {
1429 FILEDESC_UNLOCK(fdescp);
1430 error = EOPNOTSUPP;
1431 goto out;
1432 }
1433
1434 }
1435 /*
1436 * Now replace the integer FDs with pointers to
1437 * the associated global file table entry..
1438 */
1439 newlen = oldfds * sizeof(struct file *);
1440 *controlp = sbcreatecontrol(NULL, newlen,
1441 SCM_RIGHTS, SOL_SOCKET);
1442 if (*controlp == NULL) {
1443 FILEDESC_UNLOCK(fdescp);
1444 error = E2BIG;
1445 goto out;
1446 }
1447
1448 fdp = data;
1449 rp = (struct file **)
1450 CMSG_DATA(mtod(*controlp, struct cmsghdr *));
1451 for (i = 0; i < oldfds; i++) {
1452 fp = fdescp->fd_ofiles[*fdp++];
1453 *rp++ = fp;
1454 FILE_LOCK(fp);
1455 fp->f_count++;
1456 fp->f_msgcount++;
1457 FILE_UNLOCK(fp);
1458 unp_rights++;
1459 }
1460 FILEDESC_UNLOCK(fdescp);
1461 break;
1462
1463 case SCM_TIMESTAMP:
1464 *controlp = sbcreatecontrol(NULL, sizeof(*tv),
1465 SCM_TIMESTAMP, SOL_SOCKET);
1466 if (*controlp == NULL) {
1467 error = ENOBUFS;
1468 goto out;
1469 }
1470 tv = (struct timeval *)
1471 CMSG_DATA(mtod(*controlp, struct cmsghdr *));
1472 microtime(tv);
1473 break;
1474
1475 default:
1476 error = EINVAL;
1477 goto out;
1478 }
1479
1480 controlp = &(*controlp)->m_next;
1481
1482 if (CMSG_SPACE(datalen) < clen) {
1483 clen -= CMSG_SPACE(datalen);
1484 cm = (struct cmsghdr *)
1485 ((caddr_t)cm + CMSG_SPACE(datalen));
1486 } else {
1487 clen = 0;
1488 cm = NULL;
1489 }
1490 }
1491
1492out:
1493 m_freem(control);
1494
1495 return (error);
1496}
1497
1498struct mbuf *
1499unp_addsockcred(struct thread *td, struct mbuf *control)
1500{
1501 struct mbuf *m, *n;
1502 struct sockcred *sc;
1503 int ngroups;
1504 int i;
1505
1506 ngroups = MIN(td->td_ucred->cr_ngroups, CMGROUP_MAX);
1507
1508 m = sbcreatecontrol(NULL, SOCKCREDSIZE(ngroups), SCM_CREDS, SOL_SOCKET);
1509 if (m == NULL)
1510 return (control);
1511 m->m_next = NULL;
1512
1513 sc = (struct sockcred *) CMSG_DATA(mtod(m, struct cmsghdr *));
1514 sc->sc_uid = td->td_ucred->cr_ruid;
1515 sc->sc_euid = td->td_ucred->cr_uid;
1516 sc->sc_gid = td->td_ucred->cr_rgid;
1517 sc->sc_egid = td->td_ucred->cr_gid;
1518 sc->sc_ngroups = ngroups;
1519 for (i = 0; i < sc->sc_ngroups; i++)
1520 sc->sc_groups[i] = td->td_ucred->cr_groups[i];
1521
1522 /*
1523 * If a control message already exists, append us to the end.
1524 */
1525 if (control != NULL) {
1526 for (n = control; n->m_next != NULL; n = n->m_next)
1527 ;
1528 n->m_next = m;
1529 } else
1530 control = m;
1531
1532 return (control);
1533}
1534
1535/*
1536 * unp_defer indicates whether additional work has been defered for a future
1537 * pass through unp_gc(). It is thread local and does not require explicit
1538 * synchronization.
1539 */
1540static int unp_defer;
1541
1542static int unp_taskcount;
1543SYSCTL_INT(_net_local, OID_AUTO, taskcount, CTLFLAG_RD, &unp_taskcount, 0, "");
1544
1545static int unp_recycled;
1546SYSCTL_INT(_net_local, OID_AUTO, recycled, CTLFLAG_RD, &unp_recycled, 0, "");
1547
1548static void
1549unp_gc(__unused void *arg, int pending)
1550{
1551 struct file *fp, *nextfp;
1552 struct socket *so;
1553 struct file **extra_ref, **fpp;
1554 int nunref, i;
1555 int nfiles_snap;
1556 int nfiles_slack = 20;
1557
1558 unp_taskcount++;
1559 unp_defer = 0;
1560 /*
1561 * before going through all this, set all FDs to
1562 * be NOT defered and NOT externally accessible
1563 */
1564 sx_slock(&filelist_lock);
1565 LIST_FOREACH(fp, &filehead, f_list)
1566 fp->f_gcflag &= ~(FMARK|FDEFER);
1567 do {
1568 KASSERT(unp_defer >= 0, ("unp_gc: unp_defer %d", unp_defer));
1569 LIST_FOREACH(fp, &filehead, f_list) {
1570 FILE_LOCK(fp);
1571 /*
1572 * If the file is not open, skip it -- could be a
1573 * file in the process of being opened, or in the
1574 * process of being closed. If the file is
1575 * "closing", it may have been marked for deferred
1576 * consideration. Clear the flag now if so.
1577 */
1578 if (fp->f_count == 0) {
1579 if (fp->f_gcflag & FDEFER)
1580 unp_defer--;
1581 fp->f_gcflag &= ~(FMARK|FDEFER);
1582 FILE_UNLOCK(fp);
1583 continue;
1584 }
1585 /*
1586 * If we already marked it as 'defer' in a
1587 * previous pass, then try process it this time
1588 * and un-mark it
1589 */
1590 if (fp->f_gcflag & FDEFER) {
1591 fp->f_gcflag &= ~FDEFER;
1592 unp_defer--;
1593 } else {
1594 /*
1595 * if it's not defered, then check if it's
1596 * already marked.. if so skip it
1597 */
1598 if (fp->f_gcflag & FMARK) {
1599 FILE_UNLOCK(fp);
1600 continue;
1601 }
1602 /*
1603 * If all references are from messages
1604 * in transit, then skip it. it's not
1605 * externally accessible.
1606 */
1607 if (fp->f_count == fp->f_msgcount) {
1608 FILE_UNLOCK(fp);
1609 continue;
1610 }
1611 /*
1612 * If it got this far then it must be
1613 * externally accessible.
1614 */
1615 fp->f_gcflag |= FMARK;
1616 }
1617 /*
1618 * either it was defered, or it is externally
1619 * accessible and not already marked so.
1620 * Now check if it is possibly one of OUR sockets.
1621 */
1622 if (fp->f_type != DTYPE_SOCKET ||
1623 (so = fp->f_data) == NULL) {
1624 FILE_UNLOCK(fp);
1625 continue;
1626 }
1627 FILE_UNLOCK(fp);
1628 if (so->so_proto->pr_domain != &localdomain ||
1629 (so->so_proto->pr_flags&PR_RIGHTS) == 0)
1630 continue;
1631 /*
1632 * So, Ok, it's one of our sockets and it IS externally
1633 * accessible (or was defered). Now we look
1634 * to see if we hold any file descriptors in its
1635 * message buffers. Follow those links and mark them
1636 * as accessible too.
1637 */
1638 SOCKBUF_LOCK(&so->so_rcv);
1639 unp_scan(so->so_rcv.sb_mb, unp_mark);
1640 SOCKBUF_UNLOCK(&so->so_rcv);
1641 }
1642 } while (unp_defer);
1643 sx_sunlock(&filelist_lock);
1644 /*
1645 * XXXRW: The following comments need updating for a post-SMPng and
1646 * deferred unp_gc() world, but are still generally accurate.
1647 *
1648 * We grab an extra reference to each of the file table entries
1649 * that are not otherwise accessible and then free the rights
1650 * that are stored in messages on them.
1651 *
1652 * The bug in the orginal code is a little tricky, so I'll describe
1653 * what's wrong with it here.
1654 *
1655 * It is incorrect to simply unp_discard each entry for f_msgcount
1656 * times -- consider the case of sockets A and B that contain
1657 * references to each other. On a last close of some other socket,
1658 * we trigger a gc since the number of outstanding rights (unp_rights)
1659 * is non-zero. If during the sweep phase the gc code unp_discards,
1660 * we end up doing a (full) closef on the descriptor. A closef on A
1661 * results in the following chain. Closef calls soo_close, which
1662 * calls soclose. Soclose calls first (through the switch
1663 * uipc_usrreq) unp_detach, which re-invokes unp_gc. Unp_gc simply
1664 * returns because the previous instance had set unp_gcing, and
1665 * we return all the way back to soclose, which marks the socket
1666 * with SS_NOFDREF, and then calls sofree. Sofree calls sorflush
1667 * to free up the rights that are queued in messages on the socket A,
1668 * i.e., the reference on B. The sorflush calls via the dom_dispose
1669 * switch unp_dispose, which unp_scans with unp_discard. This second
1670 * instance of unp_discard just calls closef on B.
1671 *
1672 * Well, a similar chain occurs on B, resulting in a sorflush on B,
1673 * which results in another closef on A. Unfortunately, A is already
1674 * being closed, and the descriptor has already been marked with
1675 * SS_NOFDREF, and soclose panics at this point.
1676 *
1677 * Here, we first take an extra reference to each inaccessible
1678 * descriptor. Then, we call sorflush ourself, since we know
1679 * it is a Unix domain socket anyhow. After we destroy all the
1680 * rights carried in messages, we do a last closef to get rid
1681 * of our extra reference. This is the last close, and the
1682 * unp_detach etc will shut down the socket.
1683 *
1684 * 91/09/19, bsy@cs.cmu.edu
1685 */
1686again:
1687 nfiles_snap = openfiles + nfiles_slack; /* some slack */
1688 extra_ref = malloc(nfiles_snap * sizeof(struct file *), M_TEMP,
1689 M_WAITOK);
1690 sx_slock(&filelist_lock);
1691 if (nfiles_snap < openfiles) {
1692 sx_sunlock(&filelist_lock);
1693 free(extra_ref, M_TEMP);
1694 nfiles_slack += 20;
1695 goto again;
1696 }
1697 for (nunref = 0, fp = LIST_FIRST(&filehead), fpp = extra_ref;
1698 fp != NULL; fp = nextfp) {
1699 nextfp = LIST_NEXT(fp, f_list);
1700 FILE_LOCK(fp);
1701 /*
1702 * If it's not open, skip it
1703 */
1704 if (fp->f_count == 0) {
1705 FILE_UNLOCK(fp);
1706 continue;
1707 }
1708 /*
1709 * If all refs are from msgs, and it's not marked accessible
1710 * then it must be referenced from some unreachable cycle
1711 * of (shut-down) FDs, so include it in our
1712 * list of FDs to remove
1713 */
1714 if (fp->f_count == fp->f_msgcount && !(fp->f_gcflag & FMARK)) {
1715 *fpp++ = fp;
1716 nunref++;
1717 fp->f_count++;
1718 }
1719 FILE_UNLOCK(fp);
1720 }
1721 sx_sunlock(&filelist_lock);
1722 /*
1723 * for each FD on our hit list, do the following two things
1724 */
1725 for (i = nunref, fpp = extra_ref; --i >= 0; ++fpp) {
1726 struct file *tfp = *fpp;
1727 FILE_LOCK(tfp);
1728 if (tfp->f_type == DTYPE_SOCKET &&
1729 tfp->f_data != NULL) {
1730 FILE_UNLOCK(tfp);
1731 sorflush(tfp->f_data);
1732 } else {
1733 FILE_UNLOCK(tfp);
1734 }
1735 }
1736 for (i = nunref, fpp = extra_ref; --i >= 0; ++fpp) {
1737 closef(*fpp, (struct thread *) NULL);
1738 unp_recycled++;
1739 }
1740 free(extra_ref, M_TEMP);
1741}
1742
1743void
1744unp_dispose(struct mbuf *m)
1745{
1746
1747 if (m)
1748 unp_scan(m, unp_discard);
1749}
1750
1751static int
1752unp_listen(struct socket *so, struct unpcb *unp, int backlog,
1753 struct thread *td)
1754{
1755 int error;
1756
1757 UNP_LOCK_ASSERT();
1758
1759 SOCK_LOCK(so);
1760 error = solisten_proto_check(so);
1761 if (error == 0) {
1762 cru2x(td->td_ucred, &unp->unp_peercred);
1763 unp->unp_flags |= UNP_HAVEPCCACHED;
1764 solisten_proto(so, backlog);
1765 }
1766 SOCK_UNLOCK(so);
1767 return (error);
1768}
1769
1770static void
1771unp_scan(struct mbuf *m0, void (*op)(struct file *))
1772{
1773 struct mbuf *m;
1774 struct file **rp;
1775 struct cmsghdr *cm;
1776 void *data;
1777 int i;
1778 socklen_t clen, datalen;
1779 int qfds;
1780
1781 while (m0 != NULL) {
1782 for (m = m0; m; m = m->m_next) {
1783 if (m->m_type != MT_CONTROL)
1784 continue;
1785
1786 cm = mtod(m, struct cmsghdr *);
1787 clen = m->m_len;
1788
1789 while (cm != NULL) {
1790 if (sizeof(*cm) > clen || cm->cmsg_len > clen)
1791 break;
1792
1793 data = CMSG_DATA(cm);
1794 datalen = (caddr_t)cm + cm->cmsg_len
1795 - (caddr_t)data;
1796
1797 if (cm->cmsg_level == SOL_SOCKET &&
1798 cm->cmsg_type == SCM_RIGHTS) {
1799 qfds = datalen / sizeof (struct file *);
1800 rp = data;
1801 for (i = 0; i < qfds; i++)
1802 (*op)(*rp++);
1803 }
1804
1805 if (CMSG_SPACE(datalen) < clen) {
1806 clen -= CMSG_SPACE(datalen);
1807 cm = (struct cmsghdr *)
1808 ((caddr_t)cm + CMSG_SPACE(datalen));
1809 } else {
1810 clen = 0;
1811 cm = NULL;
1812 }
1813 }
1814 }
1815 m0 = m0->m_act;
1816 }
1817}
1818
1819static void
1820unp_mark(struct file *fp)
1821{
1822 if (fp->f_gcflag & FMARK)
1823 return;
1824 unp_defer++;
1825 fp->f_gcflag |= (FMARK|FDEFER);
1826}
1827
1828static void
1829unp_discard(struct file *fp)
1830{
1831 UNP_LOCK();
1832 FILE_LOCK(fp);
1833 fp->f_msgcount--;
1834 unp_rights--;
1835 FILE_UNLOCK(fp);
1836 UNP_UNLOCK();
1837 (void) closef(fp, (struct thread *)NULL);
1838}