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