uipc_usrreq.c revision 1.97 1 /* $NetBSD: uipc_usrreq.c,v 1.97 2007/04/22 08:30:00 dsl Exp $ */
2
3 /*-
4 * Copyright (c) 1998, 2000, 2004 The NetBSD Foundation, Inc.
5 * All rights reserved.
6 *
7 * This code is derived from software contributed to The NetBSD Foundation
8 * by Jason R. Thorpe of the Numerical Aerospace Simulation Facility,
9 * NASA Ames Research Center.
10 *
11 * Redistribution and use in source and binary forms, with or without
12 * modification, are permitted provided that the following conditions
13 * are met:
14 * 1. Redistributions of source code must retain the above copyright
15 * notice, this list of conditions and the following disclaimer.
16 * 2. Redistributions in binary form must reproduce the above copyright
17 * notice, this list of conditions and the following disclaimer in the
18 * documentation and/or other materials provided with the distribution.
19 * 3. All advertising materials mentioning features or use of this software
20 * must display the following acknowledgement:
21 * This product includes software developed by the NetBSD
22 * Foundation, Inc. and its contributors.
23 * 4. Neither the name of The NetBSD Foundation nor the names of its
24 * contributors may be used to endorse or promote products derived
25 * from this software without specific prior written permission.
26 *
27 * THIS SOFTWARE IS PROVIDED BY THE NETBSD FOUNDATION, INC. AND CONTRIBUTORS
28 * ``AS IS'' AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED
29 * TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR
30 * PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE FOUNDATION OR CONTRIBUTORS
31 * BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR
32 * CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF
33 * SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS
34 * INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN
35 * CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE)
36 * ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE
37 * POSSIBILITY OF SUCH DAMAGE.
38 */
39
40 /*
41 * Copyright (c) 1982, 1986, 1989, 1991, 1993
42 * The Regents of the University of California. All rights reserved.
43 *
44 * Redistribution and use in source and binary forms, with or without
45 * modification, are permitted provided that the following conditions
46 * are met:
47 * 1. Redistributions of source code must retain the above copyright
48 * notice, this list of conditions and the following disclaimer.
49 * 2. Redistributions in binary form must reproduce the above copyright
50 * notice, this list of conditions and the following disclaimer in the
51 * documentation and/or other materials provided with the distribution.
52 * 3. Neither the name of the University nor the names of its contributors
53 * may be used to endorse or promote products derived from this software
54 * without specific prior written permission.
55 *
56 * THIS SOFTWARE IS PROVIDED BY THE REGENTS AND CONTRIBUTORS ``AS IS'' AND
57 * ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
58 * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE
59 * ARE DISCLAIMED. IN NO EVENT SHALL THE REGENTS OR CONTRIBUTORS BE LIABLE
60 * FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL
61 * DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS
62 * OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION)
63 * HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT
64 * LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY
65 * OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF
66 * SUCH DAMAGE.
67 *
68 * @(#)uipc_usrreq.c 8.9 (Berkeley) 5/14/95
69 */
70
71 /*
72 * Copyright (c) 1997 Christopher G. Demetriou. All rights reserved.
73 *
74 * Redistribution and use in source and binary forms, with or without
75 * modification, are permitted provided that the following conditions
76 * are met:
77 * 1. Redistributions of source code must retain the above copyright
78 * notice, this list of conditions and the following disclaimer.
79 * 2. Redistributions in binary form must reproduce the above copyright
80 * notice, this list of conditions and the following disclaimer in the
81 * documentation and/or other materials provided with the distribution.
82 * 3. All advertising materials mentioning features or use of this software
83 * must display the following acknowledgement:
84 * This product includes software developed by the University of
85 * California, Berkeley and its contributors.
86 * 4. Neither the name of the University nor the names of its contributors
87 * may be used to endorse or promote products derived from this software
88 * without specific prior written permission.
89 *
90 * THIS SOFTWARE IS PROVIDED BY THE REGENTS AND CONTRIBUTORS ``AS IS'' AND
91 * ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
92 * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE
93 * ARE DISCLAIMED. IN NO EVENT SHALL THE REGENTS OR CONTRIBUTORS BE LIABLE
94 * FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL
95 * DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS
96 * OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION)
97 * HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT
98 * LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY
99 * OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF
100 * SUCH DAMAGE.
101 *
102 * @(#)uipc_usrreq.c 8.9 (Berkeley) 5/14/95
103 */
104
105 #include <sys/cdefs.h>
106 __KERNEL_RCSID(0, "$NetBSD: uipc_usrreq.c,v 1.97 2007/04/22 08:30:00 dsl Exp $");
107
108 #include <sys/param.h>
109 #include <sys/systm.h>
110 #include <sys/proc.h>
111 #include <sys/filedesc.h>
112 #include <sys/domain.h>
113 #include <sys/protosw.h>
114 #include <sys/socket.h>
115 #include <sys/socketvar.h>
116 #include <sys/unpcb.h>
117 #include <sys/un.h>
118 #include <sys/namei.h>
119 #include <sys/vnode.h>
120 #include <sys/file.h>
121 #include <sys/stat.h>
122 #include <sys/mbuf.h>
123 #include <sys/kauth.h>
124
125 /*
126 * Unix communications domain.
127 *
128 * TODO:
129 * SEQPACKET, RDM
130 * rethink name space problems
131 * need a proper out-of-band
132 */
133 const struct sockaddr_un sun_noname = {
134 .sun_len = sizeof(sun_noname),
135 .sun_family = AF_LOCAL,
136 };
137 ino_t unp_ino; /* prototype for fake inode numbers */
138
139 struct mbuf *unp_addsockcred(struct lwp *, struct mbuf *);
140
141 int
142 unp_output(struct mbuf *m, struct mbuf *control, struct unpcb *unp,
143 struct lwp *l)
144 {
145 struct socket *so2;
146 const struct sockaddr_un *sun;
147
148 so2 = unp->unp_conn->unp_socket;
149 if (unp->unp_addr)
150 sun = unp->unp_addr;
151 else
152 sun = &sun_noname;
153 if (unp->unp_conn->unp_flags & UNP_WANTCRED)
154 control = unp_addsockcred(l, control);
155 if (sbappendaddr(&so2->so_rcv, (const struct sockaddr *)sun, m,
156 control) == 0) {
157 m_freem(control);
158 m_freem(m);
159 so2->so_rcv.sb_overflowed++;
160 return (ENOBUFS);
161 } else {
162 sorwakeup(so2);
163 return (0);
164 }
165 }
166
167 void
168 unp_setsockaddr(struct unpcb *unp, struct mbuf *nam)
169 {
170 const struct sockaddr_un *sun;
171
172 if (unp->unp_addr)
173 sun = unp->unp_addr;
174 else
175 sun = &sun_noname;
176 nam->m_len = sun->sun_len;
177 if (nam->m_len > MLEN)
178 MEXTMALLOC(nam, nam->m_len, M_WAITOK);
179 memcpy(mtod(nam, void *), sun, (size_t)nam->m_len);
180 }
181
182 void
183 unp_setpeeraddr(struct unpcb *unp, struct mbuf *nam)
184 {
185 const struct sockaddr_un *sun;
186
187 if (unp->unp_conn && unp->unp_conn->unp_addr)
188 sun = unp->unp_conn->unp_addr;
189 else
190 sun = &sun_noname;
191 nam->m_len = sun->sun_len;
192 if (nam->m_len > MLEN)
193 MEXTMALLOC(nam, nam->m_len, M_WAITOK);
194 memcpy(mtod(nam, void *), sun, (size_t)nam->m_len);
195 }
196
197 /*ARGSUSED*/
198 int
199 uipc_usrreq(struct socket *so, int req, struct mbuf *m, struct mbuf *nam,
200 struct mbuf *control, struct lwp *l)
201 {
202 struct unpcb *unp = sotounpcb(so);
203 struct socket *so2;
204 struct proc *p;
205 u_int newhiwat;
206 int error = 0;
207
208 if (req == PRU_CONTROL)
209 return (EOPNOTSUPP);
210
211 #ifdef DIAGNOSTIC
212 if (req != PRU_SEND && req != PRU_SENDOOB && control)
213 panic("uipc_usrreq: unexpected control mbuf");
214 #endif
215 p = l ? l->l_proc : NULL;
216 if (unp == 0 && req != PRU_ATTACH) {
217 error = EINVAL;
218 goto release;
219 }
220
221 switch (req) {
222
223 case PRU_ATTACH:
224 if (unp != 0) {
225 error = EISCONN;
226 break;
227 }
228 error = unp_attach(so);
229 break;
230
231 case PRU_DETACH:
232 unp_detach(unp);
233 break;
234
235 case PRU_BIND:
236 KASSERT(l != NULL);
237 error = unp_bind(unp, nam, l);
238 break;
239
240 case PRU_LISTEN:
241 if (unp->unp_vnode == 0)
242 error = EINVAL;
243 break;
244
245 case PRU_CONNECT:
246 KASSERT(l != NULL);
247 error = unp_connect(so, nam, l);
248 break;
249
250 case PRU_CONNECT2:
251 error = unp_connect2(so, (struct socket *)nam, PRU_CONNECT2);
252 break;
253
254 case PRU_DISCONNECT:
255 unp_disconnect(unp);
256 break;
257
258 case PRU_ACCEPT:
259 unp_setpeeraddr(unp, nam);
260 /*
261 * Mark the initiating STREAM socket as connected *ONLY*
262 * after it's been accepted. This prevents a client from
263 * overrunning a server and receiving ECONNREFUSED.
264 */
265 if (unp->unp_conn != NULL &&
266 (unp->unp_conn->unp_socket->so_state & SS_ISCONNECTING))
267 soisconnected(unp->unp_conn->unp_socket);
268 break;
269
270 case PRU_SHUTDOWN:
271 socantsendmore(so);
272 unp_shutdown(unp);
273 break;
274
275 case PRU_RCVD:
276 switch (so->so_type) {
277
278 case SOCK_DGRAM:
279 panic("uipc 1");
280 /*NOTREACHED*/
281
282 case SOCK_STREAM:
283 #define rcv (&so->so_rcv)
284 #define snd (&so2->so_snd)
285 if (unp->unp_conn == 0)
286 break;
287 so2 = unp->unp_conn->unp_socket;
288 /*
289 * Adjust backpressure on sender
290 * and wakeup any waiting to write.
291 */
292 snd->sb_mbmax += unp->unp_mbcnt - rcv->sb_mbcnt;
293 unp->unp_mbcnt = rcv->sb_mbcnt;
294 newhiwat = snd->sb_hiwat + unp->unp_cc - rcv->sb_cc;
295 (void)chgsbsize(so2->so_uidinfo,
296 &snd->sb_hiwat, newhiwat, RLIM_INFINITY);
297 unp->unp_cc = rcv->sb_cc;
298 sowwakeup(so2);
299 #undef snd
300 #undef rcv
301 break;
302
303 default:
304 panic("uipc 2");
305 }
306 break;
307
308 case PRU_SEND:
309 /*
310 * Note: unp_internalize() rejects any control message
311 * other than SCM_RIGHTS, and only allows one. This
312 * has the side-effect of preventing a caller from
313 * forging SCM_CREDS.
314 */
315 if (control) {
316 KASSERT(l != NULL);
317 if ((error = unp_internalize(control, l)) != 0)
318 goto die;
319 }
320 switch (so->so_type) {
321
322 case SOCK_DGRAM: {
323 if (nam) {
324 if ((so->so_state & SS_ISCONNECTED) != 0) {
325 error = EISCONN;
326 goto die;
327 }
328 KASSERT(l != NULL);
329 error = unp_connect(so, nam, l);
330 if (error) {
331 die:
332 m_freem(control);
333 m_freem(m);
334 break;
335 }
336 } else {
337 if ((so->so_state & SS_ISCONNECTED) == 0) {
338 error = ENOTCONN;
339 goto die;
340 }
341 }
342 KASSERT(p != NULL);
343 error = unp_output(m, control, unp, l);
344 if (nam)
345 unp_disconnect(unp);
346 break;
347 }
348
349 case SOCK_STREAM:
350 #define rcv (&so2->so_rcv)
351 #define snd (&so->so_snd)
352 if (unp->unp_conn == NULL) {
353 error = ENOTCONN;
354 break;
355 }
356 so2 = unp->unp_conn->unp_socket;
357 if (unp->unp_conn->unp_flags & UNP_WANTCRED) {
358 /*
359 * Credentials are passed only once on
360 * SOCK_STREAM.
361 */
362 unp->unp_conn->unp_flags &= ~UNP_WANTCRED;
363 control = unp_addsockcred(l, control);
364 }
365 /*
366 * Send to paired receive port, and then reduce
367 * send buffer hiwater marks to maintain backpressure.
368 * Wake up readers.
369 */
370 if (control) {
371 if (sbappendcontrol(rcv, m, control) == 0)
372 m_freem(control);
373 } else
374 sbappend(rcv, m);
375 snd->sb_mbmax -=
376 rcv->sb_mbcnt - unp->unp_conn->unp_mbcnt;
377 unp->unp_conn->unp_mbcnt = rcv->sb_mbcnt;
378 newhiwat = snd->sb_hiwat -
379 (rcv->sb_cc - unp->unp_conn->unp_cc);
380 (void)chgsbsize(so->so_uidinfo,
381 &snd->sb_hiwat, newhiwat, RLIM_INFINITY);
382 unp->unp_conn->unp_cc = rcv->sb_cc;
383 sorwakeup(so2);
384 #undef snd
385 #undef rcv
386 break;
387
388 default:
389 panic("uipc 4");
390 }
391 break;
392
393 case PRU_ABORT:
394 unp_drop(unp, ECONNABORTED);
395
396 KASSERT(so->so_head == NULL);
397 #ifdef DIAGNOSTIC
398 if (so->so_pcb == 0)
399 panic("uipc 5: drop killed pcb");
400 #endif
401 unp_detach(unp);
402 break;
403
404 case PRU_SENSE:
405 ((struct stat *) m)->st_blksize = so->so_snd.sb_hiwat;
406 if (so->so_type == SOCK_STREAM && unp->unp_conn != 0) {
407 so2 = unp->unp_conn->unp_socket;
408 ((struct stat *) m)->st_blksize += so2->so_rcv.sb_cc;
409 }
410 ((struct stat *) m)->st_dev = NODEV;
411 if (unp->unp_ino == 0)
412 unp->unp_ino = unp_ino++;
413 ((struct stat *) m)->st_atimespec =
414 ((struct stat *) m)->st_mtimespec =
415 ((struct stat *) m)->st_ctimespec = unp->unp_ctime;
416 ((struct stat *) m)->st_ino = unp->unp_ino;
417 return (0);
418
419 case PRU_RCVOOB:
420 error = EOPNOTSUPP;
421 break;
422
423 case PRU_SENDOOB:
424 m_freem(control);
425 m_freem(m);
426 error = EOPNOTSUPP;
427 break;
428
429 case PRU_SOCKADDR:
430 unp_setsockaddr(unp, nam);
431 break;
432
433 case PRU_PEERADDR:
434 unp_setpeeraddr(unp, nam);
435 break;
436
437 default:
438 panic("piusrreq");
439 }
440
441 release:
442 return (error);
443 }
444
445 /*
446 * Unix domain socket option processing.
447 */
448 int
449 uipc_ctloutput(int op, struct socket *so, int level, int optname,
450 struct mbuf **mp)
451 {
452 struct unpcb *unp = sotounpcb(so);
453 struct mbuf *m = *mp;
454 int optval = 0, error = 0;
455
456 if (level != 0) {
457 error = EINVAL;
458 if (op == PRCO_SETOPT && m)
459 (void) m_free(m);
460 } else switch (op) {
461
462 case PRCO_SETOPT:
463 switch (optname) {
464 case LOCAL_CREDS:
465 case LOCAL_CONNWAIT:
466 if (m == NULL || m->m_len != sizeof(int))
467 error = EINVAL;
468 else {
469 optval = *mtod(m, int *);
470 switch (optname) {
471 #define OPTSET(bit) \
472 if (optval) \
473 unp->unp_flags |= (bit); \
474 else \
475 unp->unp_flags &= ~(bit);
476
477 case LOCAL_CREDS:
478 OPTSET(UNP_WANTCRED);
479 break;
480 case LOCAL_CONNWAIT:
481 OPTSET(UNP_CONNWAIT);
482 break;
483 }
484 }
485 break;
486 #undef OPTSET
487
488 default:
489 error = ENOPROTOOPT;
490 break;
491 }
492 if (m)
493 (void) m_free(m);
494 break;
495
496 case PRCO_GETOPT:
497 switch (optname) {
498 case LOCAL_CREDS:
499 *mp = m = m_get(M_WAIT, MT_SOOPTS);
500 m->m_len = sizeof(int);
501 switch (optname) {
502
503 #define OPTBIT(bit) (unp->unp_flags & (bit) ? 1 : 0)
504
505 case LOCAL_CREDS:
506 optval = OPTBIT(UNP_WANTCRED);
507 break;
508 }
509 *mtod(m, int *) = optval;
510 break;
511 #undef OPTBIT
512
513 default:
514 error = ENOPROTOOPT;
515 break;
516 }
517 break;
518 }
519 return (error);
520 }
521
522 /*
523 * Both send and receive buffers are allocated PIPSIZ bytes of buffering
524 * for stream sockets, although the total for sender and receiver is
525 * actually only PIPSIZ.
526 * Datagram sockets really use the sendspace as the maximum datagram size,
527 * and don't really want to reserve the sendspace. Their recvspace should
528 * be large enough for at least one max-size datagram plus address.
529 */
530 #define PIPSIZ 4096
531 u_long unpst_sendspace = PIPSIZ;
532 u_long unpst_recvspace = PIPSIZ;
533 u_long unpdg_sendspace = 2*1024; /* really max datagram size */
534 u_long unpdg_recvspace = 4*1024;
535
536 int unp_rights; /* file descriptors in flight */
537
538 int
539 unp_attach(struct socket *so)
540 {
541 struct unpcb *unp;
542 int error;
543
544 if (so->so_snd.sb_hiwat == 0 || so->so_rcv.sb_hiwat == 0) {
545 switch (so->so_type) {
546
547 case SOCK_STREAM:
548 error = soreserve(so, unpst_sendspace, unpst_recvspace);
549 break;
550
551 case SOCK_DGRAM:
552 error = soreserve(so, unpdg_sendspace, unpdg_recvspace);
553 break;
554
555 default:
556 panic("unp_attach");
557 }
558 if (error)
559 return (error);
560 }
561 unp = malloc(sizeof(*unp), M_PCB, M_NOWAIT);
562 if (unp == NULL)
563 return (ENOBUFS);
564 memset((void *)unp, 0, sizeof(*unp));
565 unp->unp_socket = so;
566 so->so_pcb = unp;
567 nanotime(&unp->unp_ctime);
568 return (0);
569 }
570
571 void
572 unp_detach(struct unpcb *unp)
573 {
574
575 if (unp->unp_vnode) {
576 unp->unp_vnode->v_socket = 0;
577 vrele(unp->unp_vnode);
578 unp->unp_vnode = 0;
579 }
580 if (unp->unp_conn)
581 unp_disconnect(unp);
582 while (unp->unp_refs)
583 unp_drop(unp->unp_refs, ECONNRESET);
584 soisdisconnected(unp->unp_socket);
585 unp->unp_socket->so_pcb = 0;
586 if (unp->unp_addr)
587 free(unp->unp_addr, M_SONAME);
588 if (unp_rights) {
589 /*
590 * Normally the receive buffer is flushed later,
591 * in sofree, but if our receive buffer holds references
592 * to descriptors that are now garbage, we will dispose
593 * of those descriptor references after the garbage collector
594 * gets them (resulting in a "panic: closef: count < 0").
595 */
596 sorflush(unp->unp_socket);
597 free(unp, M_PCB);
598 unp_gc();
599 } else
600 free(unp, M_PCB);
601 }
602
603 int
604 unp_bind(struct unpcb *unp, struct mbuf *nam, struct lwp *l)
605 {
606 struct sockaddr_un *sun;
607 struct vnode *vp;
608 struct vattr vattr;
609 size_t addrlen;
610 struct proc *p;
611 int error;
612 struct nameidata nd;
613
614 if (unp->unp_vnode != 0)
615 return (EINVAL);
616
617 p = l->l_proc;
618 /*
619 * Allocate the new sockaddr. We have to allocate one
620 * extra byte so that we can ensure that the pathname
621 * is nul-terminated.
622 */
623 addrlen = nam->m_len + 1;
624 sun = malloc(addrlen, M_SONAME, M_WAITOK);
625 m_copydata(nam, 0, nam->m_len, (void *)sun);
626 *(((char *)sun) + nam->m_len) = '\0';
627
628 NDINIT(&nd, CREATE, FOLLOW | LOCKPARENT | TRYEMULROOT, UIO_SYSSPACE,
629 sun->sun_path, l);
630
631 /* SHOULD BE ABLE TO ADOPT EXISTING AND wakeup() ALA FIFO's */
632 if ((error = namei(&nd)) != 0)
633 goto bad;
634 vp = nd.ni_vp;
635 if (vp != NULL) {
636 VOP_ABORTOP(nd.ni_dvp, &nd.ni_cnd);
637 if (nd.ni_dvp == vp)
638 vrele(nd.ni_dvp);
639 else
640 vput(nd.ni_dvp);
641 vrele(vp);
642 error = EADDRINUSE;
643 goto bad;
644 }
645 VATTR_NULL(&vattr);
646 vattr.va_type = VSOCK;
647 vattr.va_mode = ACCESSPERMS & ~(p->p_cwdi->cwdi_cmask);
648 VOP_LEASE(nd.ni_dvp, l, l->l_cred, LEASE_WRITE);
649 error = VOP_CREATE(nd.ni_dvp, &nd.ni_vp, &nd.ni_cnd, &vattr);
650 if (error)
651 goto bad;
652 vp = nd.ni_vp;
653 vp->v_socket = unp->unp_socket;
654 unp->unp_vnode = vp;
655 unp->unp_addrlen = addrlen;
656 unp->unp_addr = sun;
657 VOP_UNLOCK(vp, 0);
658 return (0);
659
660 bad:
661 free(sun, M_SONAME);
662 return (error);
663 }
664
665 int
666 unp_connect(struct socket *so, struct mbuf *nam, struct lwp *l)
667 {
668 struct sockaddr_un *sun;
669 struct vnode *vp;
670 struct socket *so2, *so3;
671 struct unpcb *unp2, *unp3;
672 size_t addrlen;
673 int error;
674 struct nameidata nd;
675
676 /*
677 * Allocate a temporary sockaddr. We have to allocate one extra
678 * byte so that we can ensure that the pathname is nul-terminated.
679 * When we establish the connection, we copy the other PCB's
680 * sockaddr to our own.
681 */
682 addrlen = nam->m_len + 1;
683 sun = malloc(addrlen, M_SONAME, M_WAITOK);
684 m_copydata(nam, 0, nam->m_len, (void *)sun);
685 *(((char *)sun) + nam->m_len) = '\0';
686
687 NDINIT(&nd, LOOKUP, FOLLOW | LOCKLEAF | TRYEMULROOT, UIO_SYSSPACE, sun->sun_path, l);
688
689 if ((error = namei(&nd)) != 0)
690 goto bad2;
691 vp = nd.ni_vp;
692 if (vp->v_type != VSOCK) {
693 error = ENOTSOCK;
694 goto bad;
695 }
696 if ((error = VOP_ACCESS(vp, VWRITE, l->l_cred, l)) != 0)
697 goto bad;
698 so2 = vp->v_socket;
699 if (so2 == 0) {
700 error = ECONNREFUSED;
701 goto bad;
702 }
703 if (so->so_type != so2->so_type) {
704 error = EPROTOTYPE;
705 goto bad;
706 }
707 if (so->so_proto->pr_flags & PR_CONNREQUIRED) {
708 if ((so2->so_options & SO_ACCEPTCONN) == 0 ||
709 (so3 = sonewconn(so2, 0)) == 0) {
710 error = ECONNREFUSED;
711 goto bad;
712 }
713 unp2 = sotounpcb(so2);
714 unp3 = sotounpcb(so3);
715 if (unp2->unp_addr) {
716 unp3->unp_addr = malloc(unp2->unp_addrlen,
717 M_SONAME, M_WAITOK);
718 memcpy(unp3->unp_addr, unp2->unp_addr,
719 unp2->unp_addrlen);
720 unp3->unp_addrlen = unp2->unp_addrlen;
721 }
722 unp3->unp_flags = unp2->unp_flags;
723 so2 = so3;
724 }
725 error = unp_connect2(so, so2, PRU_CONNECT);
726 bad:
727 vput(vp);
728 bad2:
729 free(sun, M_SONAME);
730 return (error);
731 }
732
733 int
734 unp_connect2(struct socket *so, struct socket *so2, int req)
735 {
736 struct unpcb *unp = sotounpcb(so);
737 struct unpcb *unp2;
738
739 if (so2->so_type != so->so_type)
740 return (EPROTOTYPE);
741 unp2 = sotounpcb(so2);
742 unp->unp_conn = unp2;
743 switch (so->so_type) {
744
745 case SOCK_DGRAM:
746 unp->unp_nextref = unp2->unp_refs;
747 unp2->unp_refs = unp;
748 soisconnected(so);
749 break;
750
751 case SOCK_STREAM:
752 unp2->unp_conn = unp;
753 if (req == PRU_CONNECT &&
754 ((unp->unp_flags | unp2->unp_flags) & UNP_CONNWAIT))
755 soisconnecting(so);
756 else
757 soisconnected(so);
758 soisconnected(so2);
759 break;
760
761 default:
762 panic("unp_connect2");
763 }
764 return (0);
765 }
766
767 void
768 unp_disconnect(struct unpcb *unp)
769 {
770 struct unpcb *unp2 = unp->unp_conn;
771
772 if (unp2 == 0)
773 return;
774 unp->unp_conn = 0;
775 switch (unp->unp_socket->so_type) {
776
777 case SOCK_DGRAM:
778 if (unp2->unp_refs == unp)
779 unp2->unp_refs = unp->unp_nextref;
780 else {
781 unp2 = unp2->unp_refs;
782 for (;;) {
783 if (unp2 == 0)
784 panic("unp_disconnect");
785 if (unp2->unp_nextref == unp)
786 break;
787 unp2 = unp2->unp_nextref;
788 }
789 unp2->unp_nextref = unp->unp_nextref;
790 }
791 unp->unp_nextref = 0;
792 unp->unp_socket->so_state &= ~SS_ISCONNECTED;
793 break;
794
795 case SOCK_STREAM:
796 soisdisconnected(unp->unp_socket);
797 unp2->unp_conn = 0;
798 soisdisconnected(unp2->unp_socket);
799 break;
800 }
801 }
802
803 #ifdef notdef
804 unp_abort(struct unpcb *unp)
805 {
806 unp_detach(unp);
807 }
808 #endif
809
810 void
811 unp_shutdown(struct unpcb *unp)
812 {
813 struct socket *so;
814
815 if (unp->unp_socket->so_type == SOCK_STREAM && unp->unp_conn &&
816 (so = unp->unp_conn->unp_socket))
817 socantrcvmore(so);
818 }
819
820 void
821 unp_drop(struct unpcb *unp, int errno)
822 {
823 struct socket *so = unp->unp_socket;
824
825 so->so_error = errno;
826 unp_disconnect(unp);
827 if (so->so_head) {
828 so->so_pcb = 0;
829 sofree(so);
830 if (unp->unp_addr)
831 free(unp->unp_addr, M_SONAME);
832 free(unp, M_PCB);
833 }
834 }
835
836 #ifdef notdef
837 unp_drain(void)
838 {
839
840 }
841 #endif
842
843 int
844 unp_externalize(struct mbuf *rights, struct lwp *l)
845 {
846 struct cmsghdr *cm = mtod(rights, struct cmsghdr *);
847 struct proc *p = l->l_proc;
848 int i, *fdp;
849 struct file **rp;
850 struct file *fp;
851 int nfds, error = 0;
852
853 nfds = (cm->cmsg_len - CMSG_ALIGN(sizeof(*cm))) /
854 sizeof(struct file *);
855 rp = (struct file **)CMSG_DATA(cm);
856
857 fdp = malloc(nfds * sizeof(int), M_TEMP, M_WAITOK);
858
859 /* Make sure the recipient should be able to see the descriptors.. */
860 if (p->p_cwdi->cwdi_rdir != NULL) {
861 rp = (struct file **)CMSG_DATA(cm);
862 for (i = 0; i < nfds; i++) {
863 fp = *rp++;
864 /*
865 * If we are in a chroot'ed directory, and
866 * someone wants to pass us a directory, make
867 * sure it's inside the subtree we're allowed
868 * to access.
869 */
870 if (fp->f_type == DTYPE_VNODE) {
871 struct vnode *vp = (struct vnode *)fp->f_data;
872 if ((vp->v_type == VDIR) &&
873 !vn_isunder(vp, p->p_cwdi->cwdi_rdir, l)) {
874 error = EPERM;
875 break;
876 }
877 }
878 }
879 }
880
881 restart:
882 rp = (struct file **)CMSG_DATA(cm);
883 if (error != 0) {
884 for (i = 0; i < nfds; i++) {
885 fp = *rp;
886 /*
887 * zero the pointer before calling unp_discard,
888 * since it may end up in unp_gc()..
889 */
890 *rp++ = 0;
891 unp_discard(fp);
892 }
893 goto out;
894 }
895
896 /*
897 * First loop -- allocate file descriptor table slots for the
898 * new descriptors.
899 */
900 for (i = 0; i < nfds; i++) {
901 fp = *rp++;
902 if ((error = fdalloc(p, 0, &fdp[i])) != 0) {
903 /*
904 * Back out what we've done so far.
905 */
906 for (--i; i >= 0; i--)
907 fdremove(p->p_fd, fdp[i]);
908
909 if (error == ENOSPC) {
910 fdexpand(p);
911 error = 0;
912 } else {
913 /*
914 * This is the error that has historically
915 * been returned, and some callers may
916 * expect it.
917 */
918 error = EMSGSIZE;
919 }
920 goto restart;
921 }
922
923 /*
924 * Make the slot reference the descriptor so that
925 * fdalloc() works properly.. We finalize it all
926 * in the loop below.
927 */
928 p->p_fd->fd_ofiles[fdp[i]] = fp;
929 }
930
931 /*
932 * Now that adding them has succeeded, update all of the
933 * descriptor passing state.
934 */
935 rp = (struct file **)CMSG_DATA(cm);
936 for (i = 0; i < nfds; i++) {
937 fp = *rp++;
938 fp->f_msgcount--;
939 unp_rights--;
940 }
941
942 /*
943 * Copy temporary array to message and adjust length, in case of
944 * transition from large struct file pointers to ints.
945 */
946 memcpy(CMSG_DATA(cm), fdp, nfds * sizeof(int));
947 cm->cmsg_len = CMSG_LEN(nfds * sizeof(int));
948 rights->m_len = CMSG_SPACE(nfds * sizeof(int));
949 out:
950 free(fdp, M_TEMP);
951 return (error);
952 }
953
954 int
955 unp_internalize(struct mbuf *control, struct lwp *l)
956 {
957 struct proc *p = l->l_proc;
958 struct filedesc *fdescp = p->p_fd;
959 struct cmsghdr *newcm, *cm = mtod(control, struct cmsghdr *);
960 struct file **rp, **files;
961 struct file *fp;
962 int i, fd, *fdp;
963 int nfds;
964 u_int neededspace;
965
966 /* Sanity check the control message header */
967 if (cm->cmsg_type != SCM_RIGHTS || cm->cmsg_level != SOL_SOCKET ||
968 cm->cmsg_len != control->m_len)
969 return (EINVAL);
970
971 /* Verify that the file descriptors are valid */
972 nfds = (cm->cmsg_len - CMSG_ALIGN(sizeof(*cm))) / sizeof(int);
973 fdp = (int *)CMSG_DATA(cm);
974 for (i = 0; i < nfds; i++) {
975 fd = *fdp++;
976 if ((fp = fd_getfile(fdescp, fd)) == NULL)
977 return (EBADF);
978 simple_unlock(&fp->f_slock);
979 }
980
981 /* Make sure we have room for the struct file pointers */
982 neededspace = CMSG_SPACE(nfds * sizeof(struct file *)) -
983 control->m_len;
984 if (neededspace > M_TRAILINGSPACE(control)) {
985
986 /* allocate new space and copy header into it */
987 newcm = malloc(
988 CMSG_SPACE(nfds * sizeof(struct file *)),
989 M_MBUF, M_WAITOK);
990 if (newcm == NULL)
991 return (E2BIG);
992 memcpy(newcm, cm, sizeof(struct cmsghdr));
993 files = (struct file **)CMSG_DATA(newcm);
994 } else {
995 /* we can convert in-place */
996 newcm = NULL;
997 files = (struct file **)CMSG_DATA(cm);
998 }
999
1000 /*
1001 * Transform the file descriptors into struct file pointers, in
1002 * reverse order so that if pointers are bigger than ints, the
1003 * int won't get until we're done.
1004 */
1005 fdp = (int *)CMSG_DATA(cm) + nfds;
1006 rp = files + nfds;
1007 for (i = 0; i < nfds; i++) {
1008 fp = fdescp->fd_ofiles[*--fdp];
1009 simple_lock(&fp->f_slock);
1010 #ifdef DIAGNOSTIC
1011 if (fp->f_iflags & FIF_WANTCLOSE)
1012 panic("unp_internalize: file already closed");
1013 #endif
1014 *--rp = fp;
1015 fp->f_count++;
1016 fp->f_msgcount++;
1017 simple_unlock(&fp->f_slock);
1018 unp_rights++;
1019 }
1020
1021 if (newcm) {
1022 if (control->m_flags & M_EXT)
1023 MEXTREMOVE(control);
1024 MEXTADD(control, newcm,
1025 CMSG_SPACE(nfds * sizeof(struct file *)),
1026 M_MBUF, NULL, NULL);
1027 cm = newcm;
1028 }
1029
1030 /* adjust message & mbuf to note amount of space actually used. */
1031 cm->cmsg_len = CMSG_LEN(nfds * sizeof(struct file *));
1032 control->m_len = CMSG_SPACE(nfds * sizeof(struct file *));
1033
1034 return (0);
1035 }
1036
1037 struct mbuf *
1038 unp_addsockcred(struct lwp *l, struct mbuf *control)
1039 {
1040 struct cmsghdr *cmp;
1041 struct sockcred *sc;
1042 struct mbuf *m, *n;
1043 int len, space, i;
1044
1045 len = CMSG_LEN(SOCKCREDSIZE(kauth_cred_ngroups(l->l_cred)));
1046 space = CMSG_SPACE(SOCKCREDSIZE(kauth_cred_ngroups(l->l_cred)));
1047
1048 m = m_get(M_WAIT, MT_CONTROL);
1049 if (space > MLEN) {
1050 if (space > MCLBYTES)
1051 MEXTMALLOC(m, space, M_WAITOK);
1052 else
1053 m_clget(m, M_WAIT);
1054 if ((m->m_flags & M_EXT) == 0) {
1055 m_free(m);
1056 return (control);
1057 }
1058 }
1059
1060 m->m_len = space;
1061 m->m_next = NULL;
1062 cmp = mtod(m, struct cmsghdr *);
1063 sc = (struct sockcred *)CMSG_DATA(cmp);
1064 cmp->cmsg_len = len;
1065 cmp->cmsg_level = SOL_SOCKET;
1066 cmp->cmsg_type = SCM_CREDS;
1067 sc->sc_uid = kauth_cred_getuid(l->l_cred);
1068 sc->sc_euid = kauth_cred_geteuid(l->l_cred);
1069 sc->sc_gid = kauth_cred_getgid(l->l_cred);
1070 sc->sc_egid = kauth_cred_getegid(l->l_cred);
1071 sc->sc_ngroups = kauth_cred_ngroups(l->l_cred);
1072 for (i = 0; i < sc->sc_ngroups; i++)
1073 sc->sc_groups[i] = kauth_cred_group(l->l_cred, i);
1074
1075 /*
1076 * If a control message already exists, append us to the end.
1077 */
1078 if (control != NULL) {
1079 for (n = control; n->m_next != NULL; n = n->m_next)
1080 ;
1081 n->m_next = m;
1082 } else
1083 control = m;
1084
1085 return (control);
1086 }
1087
1088 int unp_defer, unp_gcing;
1089 extern struct domain unixdomain;
1090
1091 /*
1092 * Comment added long after the fact explaining what's going on here.
1093 * Do a mark-sweep GC of file descriptors on the system, to free up
1094 * any which are caught in flight to an about-to-be-closed socket.
1095 *
1096 * Traditional mark-sweep gc's start at the "root", and mark
1097 * everything reachable from the root (which, in our case would be the
1098 * process table). The mark bits are cleared during the sweep.
1099 *
1100 * XXX For some inexplicable reason (perhaps because the file
1101 * descriptor tables used to live in the u area which could be swapped
1102 * out and thus hard to reach), we do multiple scans over the set of
1103 * descriptors, using use *two* mark bits per object (DEFER and MARK).
1104 * Whenever we find a descriptor which references other descriptors,
1105 * the ones it references are marked with both bits, and we iterate
1106 * over the whole file table until there are no more DEFER bits set.
1107 * We also make an extra pass *before* the GC to clear the mark bits,
1108 * which could have been cleared at almost no cost during the previous
1109 * sweep.
1110 *
1111 * XXX MP: this needs to run with locks such that no other thread of
1112 * control can create or destroy references to file descriptors. it
1113 * may be necessary to defer the GC until later (when the locking
1114 * situation is more hospitable); it may be necessary to push this
1115 * into a separate thread.
1116 */
1117 void
1118 unp_gc(void)
1119 {
1120 struct file *fp, *nextfp;
1121 struct socket *so, *so1;
1122 struct file **extra_ref, **fpp;
1123 int nunref, i;
1124
1125 if (unp_gcing)
1126 return;
1127 unp_gcing = 1;
1128 unp_defer = 0;
1129
1130 /* Clear mark bits */
1131 LIST_FOREACH(fp, &filehead, f_list)
1132 fp->f_flag &= ~(FMARK|FDEFER);
1133
1134 /*
1135 * Iterate over the set of descriptors, marking ones believed
1136 * (based on refcount) to be referenced from a process, and
1137 * marking for rescan descriptors which are queued on a socket.
1138 */
1139 do {
1140 LIST_FOREACH(fp, &filehead, f_list) {
1141 if (fp->f_flag & FDEFER) {
1142 fp->f_flag &= ~FDEFER;
1143 unp_defer--;
1144 #ifdef DIAGNOSTIC
1145 if (fp->f_count == 0)
1146 panic("unp_gc: deferred unreferenced socket");
1147 #endif
1148 } else {
1149 if (fp->f_count == 0)
1150 continue;
1151 if (fp->f_flag & FMARK)
1152 continue;
1153 if (fp->f_count == fp->f_msgcount)
1154 continue;
1155 }
1156 fp->f_flag |= FMARK;
1157
1158 if (fp->f_type != DTYPE_SOCKET ||
1159 (so = (struct socket *)fp->f_data) == 0)
1160 continue;
1161 if (so->so_proto->pr_domain != &unixdomain ||
1162 (so->so_proto->pr_flags&PR_RIGHTS) == 0)
1163 continue;
1164 #ifdef notdef
1165 if (so->so_rcv.sb_flags & SB_LOCK) {
1166 /*
1167 * This is problematical; it's not clear
1168 * we need to wait for the sockbuf to be
1169 * unlocked (on a uniprocessor, at least),
1170 * and it's also not clear what to do
1171 * if sbwait returns an error due to receipt
1172 * of a signal. If sbwait does return
1173 * an error, we'll go into an infinite
1174 * loop. Delete all of this for now.
1175 */
1176 (void) sbwait(&so->so_rcv);
1177 goto restart;
1178 }
1179 #endif
1180 unp_scan(so->so_rcv.sb_mb, unp_mark, 0);
1181 /*
1182 * mark descriptors referenced from sockets queued on the accept queue as well.
1183 */
1184 if (so->so_options & SO_ACCEPTCONN) {
1185 TAILQ_FOREACH(so1, &so->so_q0, so_qe) {
1186 unp_scan(so1->so_rcv.sb_mb, unp_mark, 0);
1187 }
1188 TAILQ_FOREACH(so1, &so->so_q, so_qe) {
1189 unp_scan(so1->so_rcv.sb_mb, unp_mark, 0);
1190 }
1191 }
1192
1193 }
1194 } while (unp_defer);
1195 /*
1196 * Sweep pass. Find unmarked descriptors, and free them.
1197 *
1198 * We grab an extra reference to each of the file table entries
1199 * that are not otherwise accessible and then free the rights
1200 * that are stored in messages on them.
1201 *
1202 * The bug in the original code is a little tricky, so I'll describe
1203 * what's wrong with it here.
1204 *
1205 * It is incorrect to simply unp_discard each entry for f_msgcount
1206 * times -- consider the case of sockets A and B that contain
1207 * references to each other. On a last close of some other socket,
1208 * we trigger a gc since the number of outstanding rights (unp_rights)
1209 * is non-zero. If during the sweep phase the gc code un_discards,
1210 * we end up doing a (full) closef on the descriptor. A closef on A
1211 * results in the following chain. Closef calls soo_close, which
1212 * calls soclose. Soclose calls first (through the switch
1213 * uipc_usrreq) unp_detach, which re-invokes unp_gc. Unp_gc simply
1214 * returns because the previous instance had set unp_gcing, and
1215 * we return all the way back to soclose, which marks the socket
1216 * with SS_NOFDREF, and then calls sofree. Sofree calls sorflush
1217 * to free up the rights that are queued in messages on the socket A,
1218 * i.e., the reference on B. The sorflush calls via the dom_dispose
1219 * switch unp_dispose, which unp_scans with unp_discard. This second
1220 * instance of unp_discard just calls closef on B.
1221 *
1222 * Well, a similar chain occurs on B, resulting in a sorflush on B,
1223 * which results in another closef on A. Unfortunately, A is already
1224 * being closed, and the descriptor has already been marked with
1225 * SS_NOFDREF, and soclose panics at this point.
1226 *
1227 * Here, we first take an extra reference to each inaccessible
1228 * descriptor. Then, if the inaccessible descriptor is a
1229 * socket, we call sorflush in case it is a Unix domain
1230 * socket. After we destroy all the rights carried in
1231 * messages, we do a last closef to get rid of our extra
1232 * reference. This is the last close, and the unp_detach etc
1233 * will shut down the socket.
1234 *
1235 * 91/09/19, bsy (at) cs.cmu.edu
1236 */
1237 extra_ref = malloc(nfiles * sizeof(struct file *), M_FILE, M_WAITOK);
1238 for (nunref = 0, fp = LIST_FIRST(&filehead), fpp = extra_ref; fp != 0;
1239 fp = nextfp) {
1240 nextfp = LIST_NEXT(fp, f_list);
1241 simple_lock(&fp->f_slock);
1242 if (fp->f_count != 0 &&
1243 fp->f_count == fp->f_msgcount && !(fp->f_flag & FMARK)) {
1244 *fpp++ = fp;
1245 nunref++;
1246 fp->f_count++;
1247 }
1248 simple_unlock(&fp->f_slock);
1249 }
1250 for (i = nunref, fpp = extra_ref; --i >= 0; ++fpp) {
1251 fp = *fpp;
1252 simple_lock(&fp->f_slock);
1253 FILE_USE(fp);
1254 if (fp->f_type == DTYPE_SOCKET)
1255 sorflush((struct socket *)fp->f_data);
1256 FILE_UNUSE(fp, NULL);
1257 }
1258 for (i = nunref, fpp = extra_ref; --i >= 0; ++fpp) {
1259 fp = *fpp;
1260 simple_lock(&fp->f_slock);
1261 FILE_USE(fp);
1262 (void) closef(fp, (struct lwp *)0);
1263 }
1264 free((void *)extra_ref, M_FILE);
1265 unp_gcing = 0;
1266 }
1267
1268 void
1269 unp_dispose(struct mbuf *m)
1270 {
1271
1272 if (m)
1273 unp_scan(m, unp_discard, 1);
1274 }
1275
1276 void
1277 unp_scan(struct mbuf *m0, void (*op)(struct file *), int discard)
1278 {
1279 struct mbuf *m;
1280 struct file **rp;
1281 struct cmsghdr *cm;
1282 int i;
1283 int qfds;
1284
1285 while (m0) {
1286 for (m = m0; m; m = m->m_next) {
1287 if (m->m_type == MT_CONTROL &&
1288 m->m_len >= sizeof(*cm)) {
1289 cm = mtod(m, struct cmsghdr *);
1290 if (cm->cmsg_level != SOL_SOCKET ||
1291 cm->cmsg_type != SCM_RIGHTS)
1292 continue;
1293 qfds = (cm->cmsg_len - CMSG_ALIGN(sizeof(*cm)))
1294 / sizeof(struct file *);
1295 rp = (struct file **)CMSG_DATA(cm);
1296 for (i = 0; i < qfds; i++) {
1297 struct file *fp = *rp;
1298 if (discard)
1299 *rp = 0;
1300 (*op)(fp);
1301 rp++;
1302 }
1303 break; /* XXX, but saves time */
1304 }
1305 }
1306 m0 = m0->m_nextpkt;
1307 }
1308 }
1309
1310 void
1311 unp_mark(struct file *fp)
1312 {
1313 if (fp == NULL)
1314 return;
1315
1316 if (fp->f_flag & FMARK)
1317 return;
1318
1319 /* If we're already deferred, don't screw up the defer count */
1320 if (fp->f_flag & FDEFER)
1321 return;
1322
1323 /*
1324 * Minimize the number of deferrals... Sockets are the only
1325 * type of descriptor which can hold references to another
1326 * descriptor, so just mark other descriptors, and defer
1327 * unmarked sockets for the next pass.
1328 */
1329 if (fp->f_type == DTYPE_SOCKET) {
1330 unp_defer++;
1331 if (fp->f_count == 0)
1332 panic("unp_mark: queued unref");
1333 fp->f_flag |= FDEFER;
1334 } else {
1335 fp->f_flag |= FMARK;
1336 }
1337 return;
1338 }
1339
1340 void
1341 unp_discard(struct file *fp)
1342 {
1343 if (fp == NULL)
1344 return;
1345 simple_lock(&fp->f_slock);
1346 fp->f_usecount++; /* i.e. FILE_USE(fp) sans locking */
1347 fp->f_msgcount--;
1348 simple_unlock(&fp->f_slock);
1349 unp_rights--;
1350 (void) closef(fp, (struct lwp *)0);
1351 }
1352