uipc_usrreq.c revision 1.70 1 /* $NetBSD: uipc_usrreq.c,v 1.70 2003/10/15 11:29:01 hannken 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.70 2003/10/15 11:29:01 hannken 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 if (m == NULL || m->m_len != sizeof(int))
455 error = EINVAL;
456 else {
457 optval = *mtod(m, int *);
458 switch (optname) {
459 #define OPTSET(bit) \
460 if (optval) \
461 unp->unp_flags |= (bit); \
462 else \
463 unp->unp_flags &= ~(bit);
464
465 case LOCAL_CREDS:
466 OPTSET(UNP_WANTCRED);
467 break;
468 }
469 }
470 break;
471 #undef OPTSET
472
473 default:
474 error = ENOPROTOOPT;
475 break;
476 }
477 if (m)
478 (void) m_free(m);
479 break;
480
481 case PRCO_GETOPT:
482 switch (optname) {
483 case LOCAL_CREDS:
484 *mp = m = m_get(M_WAIT, MT_SOOPTS);
485 m->m_len = sizeof(int);
486 switch (optname) {
487
488 #define OPTBIT(bit) (unp->unp_flags & (bit) ? 1 : 0)
489
490 case LOCAL_CREDS:
491 optval = OPTBIT(UNP_WANTCRED);
492 break;
493 }
494 *mtod(m, int *) = optval;
495 break;
496 #undef OPTBIT
497
498 default:
499 error = ENOPROTOOPT;
500 break;
501 }
502 break;
503 }
504 return (error);
505 }
506
507 /*
508 * Both send and receive buffers are allocated PIPSIZ bytes of buffering
509 * for stream sockets, although the total for sender and receiver is
510 * actually only PIPSIZ.
511 * Datagram sockets really use the sendspace as the maximum datagram size,
512 * and don't really want to reserve the sendspace. Their recvspace should
513 * be large enough for at least one max-size datagram plus address.
514 */
515 #define PIPSIZ 4096
516 u_long unpst_sendspace = PIPSIZ;
517 u_long unpst_recvspace = PIPSIZ;
518 u_long unpdg_sendspace = 2*1024; /* really max datagram size */
519 u_long unpdg_recvspace = 4*1024;
520
521 int unp_rights; /* file descriptors in flight */
522
523 int
524 unp_attach(so)
525 struct socket *so;
526 {
527 struct unpcb *unp;
528 struct timeval tv;
529 int error;
530
531 if (so->so_snd.sb_hiwat == 0 || so->so_rcv.sb_hiwat == 0) {
532 switch (so->so_type) {
533
534 case SOCK_STREAM:
535 error = soreserve(so, unpst_sendspace, unpst_recvspace);
536 break;
537
538 case SOCK_DGRAM:
539 error = soreserve(so, unpdg_sendspace, unpdg_recvspace);
540 break;
541
542 default:
543 panic("unp_attach");
544 }
545 if (error)
546 return (error);
547 }
548 unp = malloc(sizeof(*unp), M_PCB, M_NOWAIT);
549 if (unp == NULL)
550 return (ENOBUFS);
551 memset((caddr_t)unp, 0, sizeof(*unp));
552 unp->unp_socket = so;
553 so->so_pcb = unp;
554 microtime(&tv);
555 TIMEVAL_TO_TIMESPEC(&tv, &unp->unp_ctime);
556 return (0);
557 }
558
559 void
560 unp_detach(unp)
561 struct unpcb *unp;
562 {
563
564 if (unp->unp_vnode) {
565 unp->unp_vnode->v_socket = 0;
566 vrele(unp->unp_vnode);
567 unp->unp_vnode = 0;
568 }
569 if (unp->unp_conn)
570 unp_disconnect(unp);
571 while (unp->unp_refs)
572 unp_drop(unp->unp_refs, ECONNRESET);
573 soisdisconnected(unp->unp_socket);
574 unp->unp_socket->so_pcb = 0;
575 if (unp->unp_addr)
576 free(unp->unp_addr, M_SONAME);
577 if (unp_rights) {
578 /*
579 * Normally the receive buffer is flushed later,
580 * in sofree, but if our receive buffer holds references
581 * to descriptors that are now garbage, we will dispose
582 * of those descriptor references after the garbage collector
583 * gets them (resulting in a "panic: closef: count < 0").
584 */
585 sorflush(unp->unp_socket);
586 free(unp, M_PCB);
587 unp_gc();
588 } else
589 free(unp, M_PCB);
590 }
591
592 int
593 unp_bind(unp, nam, p)
594 struct unpcb *unp;
595 struct mbuf *nam;
596 struct proc *p;
597 {
598 struct sockaddr_un *sun;
599 struct vnode *vp;
600 struct mount *mp;
601 struct vattr vattr;
602 size_t addrlen;
603 int error;
604 struct nameidata nd;
605
606 if (unp->unp_vnode != 0)
607 return (EINVAL);
608
609 /*
610 * Allocate the new sockaddr. We have to allocate one
611 * extra byte so that we can ensure that the pathname
612 * is nul-terminated.
613 */
614 addrlen = nam->m_len + 1;
615 sun = malloc(addrlen, M_SONAME, M_WAITOK);
616 m_copydata(nam, 0, nam->m_len, (caddr_t)sun);
617 *(((char *)sun) + nam->m_len) = '\0';
618
619 restart:
620 NDINIT(&nd, CREATE, FOLLOW | LOCKPARENT, UIO_SYSSPACE,
621 sun->sun_path, p);
622
623 /* SHOULD BE ABLE TO ADOPT EXISTING AND wakeup() ALA FIFO's */
624 if ((error = namei(&nd)) != 0)
625 goto bad;
626 vp = nd.ni_vp;
627 if (vp != NULL || vn_start_write(nd.ni_dvp, &mp, V_NOWAIT) != 0) {
628 VOP_ABORTOP(nd.ni_dvp, &nd.ni_cnd);
629 if (nd.ni_dvp == vp)
630 vrele(nd.ni_dvp);
631 else
632 vput(nd.ni_dvp);
633 vrele(vp);
634 if (vp != NULL) {
635 error = EADDRINUSE;
636 goto bad;
637 }
638 error = vn_start_write(NULL, &mp,
639 V_WAIT | V_SLEEPONLY | V_PCATCH);
640 if (error)
641 goto bad;
642 goto restart;
643 }
644 VATTR_NULL(&vattr);
645 vattr.va_type = VSOCK;
646 vattr.va_mode = ACCESSPERMS;
647 VOP_LEASE(nd.ni_dvp, p, p->p_ucred, LEASE_WRITE);
648 error = VOP_CREATE(nd.ni_dvp, &nd.ni_vp, &nd.ni_cnd, &vattr);
649 vn_finished_write(mp, 0);
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(so, nam, p)
667 struct socket *so;
668 struct mbuf *nam;
669 struct proc *p;
670 {
671 struct sockaddr_un *sun;
672 struct vnode *vp;
673 struct socket *so2, *so3;
674 struct unpcb *unp2, *unp3;
675 size_t addrlen;
676 int error;
677 struct nameidata nd;
678
679 /*
680 * Allocate a temporary sockaddr. We have to allocate one extra
681 * byte so that we can ensure that the pathname is nul-terminated.
682 * When we establish the connection, we copy the other PCB's
683 * sockaddr to our own.
684 */
685 addrlen = nam->m_len + 1;
686 sun = malloc(addrlen, M_SONAME, M_WAITOK);
687 m_copydata(nam, 0, nam->m_len, (caddr_t)sun);
688 *(((char *)sun) + nam->m_len) = '\0';
689
690 NDINIT(&nd, LOOKUP, FOLLOW | LOCKLEAF, UIO_SYSSPACE, sun->sun_path, p);
691
692 if ((error = namei(&nd)) != 0)
693 goto bad2;
694 vp = nd.ni_vp;
695 if (vp->v_type != VSOCK) {
696 error = ENOTSOCK;
697 goto bad;
698 }
699 if ((error = VOP_ACCESS(vp, VWRITE, p->p_ucred, p)) != 0)
700 goto bad;
701 so2 = vp->v_socket;
702 if (so2 == 0) {
703 error = ECONNREFUSED;
704 goto bad;
705 }
706 if (so->so_type != so2->so_type) {
707 error = EPROTOTYPE;
708 goto bad;
709 }
710 if (so->so_proto->pr_flags & PR_CONNREQUIRED) {
711 if ((so2->so_options & SO_ACCEPTCONN) == 0 ||
712 (so3 = sonewconn(so2, 0)) == 0) {
713 error = ECONNREFUSED;
714 goto bad;
715 }
716 unp2 = sotounpcb(so2);
717 unp3 = sotounpcb(so3);
718 if (unp2->unp_addr) {
719 unp3->unp_addr = malloc(unp2->unp_addrlen,
720 M_SONAME, M_WAITOK);
721 memcpy(unp3->unp_addr, unp2->unp_addr,
722 unp2->unp_addrlen);
723 unp3->unp_addrlen = unp2->unp_addrlen;
724 }
725 unp3->unp_flags = unp2->unp_flags;
726 so2 = so3;
727 }
728 error = unp_connect2(so, so2, PRU_CONNECT);
729 bad:
730 vput(vp);
731 bad2:
732 free(sun, M_SONAME);
733 return (error);
734 }
735
736 int
737 unp_connect2(so, so2, req)
738 struct socket *so;
739 struct socket *so2;
740 int req;
741 {
742 struct unpcb *unp = sotounpcb(so);
743 struct unpcb *unp2;
744
745 if (so2->so_type != so->so_type)
746 return (EPROTOTYPE);
747 unp2 = sotounpcb(so2);
748 unp->unp_conn = unp2;
749 switch (so->so_type) {
750
751 case SOCK_DGRAM:
752 unp->unp_nextref = unp2->unp_refs;
753 unp2->unp_refs = unp;
754 soisconnected(so);
755 break;
756
757 case SOCK_STREAM:
758 unp2->unp_conn = unp;
759 if (req == PRU_CONNECT)
760 soisconnecting(so);
761 else
762 soisconnected(so);
763 soisconnected(so2);
764 break;
765
766 default:
767 panic("unp_connect2");
768 }
769 return (0);
770 }
771
772 void
773 unp_disconnect(unp)
774 struct unpcb *unp;
775 {
776 struct unpcb *unp2 = unp->unp_conn;
777
778 if (unp2 == 0)
779 return;
780 unp->unp_conn = 0;
781 switch (unp->unp_socket->so_type) {
782
783 case SOCK_DGRAM:
784 if (unp2->unp_refs == unp)
785 unp2->unp_refs = unp->unp_nextref;
786 else {
787 unp2 = unp2->unp_refs;
788 for (;;) {
789 if (unp2 == 0)
790 panic("unp_disconnect");
791 if (unp2->unp_nextref == unp)
792 break;
793 unp2 = unp2->unp_nextref;
794 }
795 unp2->unp_nextref = unp->unp_nextref;
796 }
797 unp->unp_nextref = 0;
798 unp->unp_socket->so_state &= ~SS_ISCONNECTED;
799 break;
800
801 case SOCK_STREAM:
802 soisdisconnected(unp->unp_socket);
803 unp2->unp_conn = 0;
804 soisdisconnected(unp2->unp_socket);
805 break;
806 }
807 }
808
809 #ifdef notdef
810 unp_abort(unp)
811 struct unpcb *unp;
812 {
813
814 unp_detach(unp);
815 }
816 #endif
817
818 void
819 unp_shutdown(unp)
820 struct unpcb *unp;
821 {
822 struct socket *so;
823
824 if (unp->unp_socket->so_type == SOCK_STREAM && unp->unp_conn &&
825 (so = unp->unp_conn->unp_socket))
826 socantrcvmore(so);
827 }
828
829 void
830 unp_drop(unp, errno)
831 struct unpcb *unp;
832 int errno;
833 {
834 struct socket *so = unp->unp_socket;
835
836 so->so_error = errno;
837 unp_disconnect(unp);
838 if (so->so_head) {
839 so->so_pcb = 0;
840 sofree(so);
841 if (unp->unp_addr)
842 free(unp->unp_addr, M_SONAME);
843 free(unp, M_PCB);
844 }
845 }
846
847 #ifdef notdef
848 unp_drain()
849 {
850
851 }
852 #endif
853
854 int
855 unp_externalize(rights)
856 struct mbuf *rights;
857 {
858 struct proc *p = curproc; /* XXX */
859 struct cmsghdr *cm = mtod(rights, struct cmsghdr *);
860 int i, *fdp;
861 struct file **rp;
862 struct file *fp;
863 int nfds, error = 0;
864
865 nfds = (cm->cmsg_len - CMSG_ALIGN(sizeof(*cm))) /
866 sizeof(struct file *);
867 rp = (struct file **)CMSG_DATA(cm);
868
869 fdp = malloc(nfds * sizeof(int), M_TEMP, M_WAITOK);
870
871 /* Make sure the recipient should be able to see the descriptors.. */
872 if (p->p_cwdi->cwdi_rdir != NULL) {
873 rp = (struct file **)CMSG_DATA(cm);
874 for (i = 0; i < nfds; i++) {
875 fp = *rp++;
876 /*
877 * If we are in a chroot'ed directory, and
878 * someone wants to pass us a directory, make
879 * sure it's inside the subtree we're allowed
880 * to access.
881 */
882 if (fp->f_type == DTYPE_VNODE) {
883 struct vnode *vp = (struct vnode *)fp->f_data;
884 if ((vp->v_type == VDIR) &&
885 !vn_isunder(vp, p->p_cwdi->cwdi_rdir, p)) {
886 error = EPERM;
887 break;
888 }
889 }
890 }
891 }
892
893 restart:
894 rp = (struct file **)CMSG_DATA(cm);
895 if (error != 0) {
896 for (i = 0; i < nfds; i++) {
897 fp = *rp;
898 /*
899 * zero the pointer before calling unp_discard,
900 * since it may end up in unp_gc()..
901 */
902 *rp++ = 0;
903 unp_discard(fp);
904 }
905 goto out;
906 }
907
908 /*
909 * First loop -- allocate file descriptor table slots for the
910 * new descriptors.
911 */
912 for (i = 0; i < nfds; i++) {
913 fp = *rp++;
914 if ((error = fdalloc(p, 0, &fdp[i])) != 0) {
915 /*
916 * Back out what we've done so far.
917 */
918 for (--i; i >= 0; i--)
919 fdremove(p->p_fd, fdp[i]);
920
921 if (error == ENOSPC) {
922 fdexpand(p);
923 error = 0;
924 } else {
925 /*
926 * This is the error that has historically
927 * been returned, and some callers may
928 * expect it.
929 */
930 error = EMSGSIZE;
931 }
932 goto restart;
933 }
934
935 /*
936 * Make the slot reference the descriptor so that
937 * fdalloc() works properly.. We finalize it all
938 * in the loop below.
939 */
940 p->p_fd->fd_ofiles[fdp[i]] = fp;
941 }
942
943 /*
944 * Now that adding them has succeeded, update all of the
945 * descriptor passing state.
946 */
947 rp = (struct file **)CMSG_DATA(cm);
948 for (i = 0; i < nfds; i++) {
949 fp = *rp++;
950 fp->f_msgcount--;
951 unp_rights--;
952 }
953
954 /*
955 * Copy temporary array to message and adjust length, in case of
956 * transition from large struct file pointers to ints.
957 */
958 memcpy(CMSG_DATA(cm), fdp, nfds * sizeof(int));
959 cm->cmsg_len = CMSG_LEN(nfds * sizeof(int));
960 rights->m_len = CMSG_SPACE(nfds * sizeof(int));
961 out:
962 free(fdp, M_TEMP);
963 return (error);
964 }
965
966 int
967 unp_internalize(control, p)
968 struct mbuf *control;
969 struct proc *p;
970 {
971 struct filedesc *fdescp = p->p_fd;
972 struct cmsghdr *cm = mtod(control, struct cmsghdr *);
973 struct file **rp;
974 struct file *fp;
975 int i, fd, *fdp;
976 int nfds;
977 u_int neededspace;
978
979 /* Sanity check the control message header */
980 if (cm->cmsg_type != SCM_RIGHTS || cm->cmsg_level != SOL_SOCKET ||
981 cm->cmsg_len != control->m_len)
982 return (EINVAL);
983
984 /* Verify that the file descriptors are valid */
985 nfds = (cm->cmsg_len - CMSG_ALIGN(sizeof(*cm))) / sizeof(int);
986 fdp = (int *)CMSG_DATA(cm);
987 for (i = 0; i < nfds; i++) {
988 fd = *fdp++;
989 if ((fp = fd_getfile(fdescp, fd)) == NULL)
990 return (EBADF);
991 simple_unlock(&fp->f_slock);
992 }
993
994 /* Make sure we have room for the struct file pointers */
995 morespace:
996 neededspace = CMSG_SPACE(nfds * sizeof(struct file *)) -
997 control->m_len;
998 if (neededspace > M_TRAILINGSPACE(control)) {
999
1000 /* if we already have a cluster, the message is just too big */
1001 if (control->m_flags & M_EXT)
1002 return (E2BIG);
1003
1004 /* allocate a cluster and try again */
1005 m_clget(control, M_WAIT);
1006 if ((control->m_flags & M_EXT) == 0)
1007 return (ENOBUFS); /* allocation failed */
1008
1009 /* copy the data to the cluster */
1010 memcpy(mtod(control, char *), cm, cm->cmsg_len);
1011 cm = mtod(control, struct cmsghdr *);
1012 goto morespace;
1013 }
1014
1015 /* adjust message & mbuf to note amount of space actually used. */
1016 cm->cmsg_len = CMSG_LEN(nfds * sizeof(struct file *));
1017 control->m_len = CMSG_SPACE(nfds * sizeof(struct file *));
1018
1019 /*
1020 * Transform the file descriptors into struct file pointers, in
1021 * reverse order so that if pointers are bigger than ints, the
1022 * int won't get until we're done.
1023 */
1024 fdp = ((int *)CMSG_DATA(cm)) + nfds - 1;
1025 rp = ((struct file **)CMSG_DATA(cm)) + nfds - 1;
1026 for (i = 0; i < nfds; i++) {
1027 fp = fdescp->fd_ofiles[*fdp--];
1028 simple_lock(&fp->f_slock);
1029 #ifdef DIAGNOSTIC
1030 if (fp->f_iflags & FIF_WANTCLOSE)
1031 panic("unp_internalize: file already closed");
1032 #endif
1033 *rp-- = fp;
1034 fp->f_count++;
1035 fp->f_msgcount++;
1036 simple_unlock(&fp->f_slock);
1037 unp_rights++;
1038 }
1039 return (0);
1040 }
1041
1042 struct mbuf *
1043 unp_addsockcred(p, control)
1044 struct proc *p;
1045 struct mbuf *control;
1046 {
1047 struct cmsghdr *cmp;
1048 struct sockcred *sc;
1049 struct mbuf *m, *n;
1050 int len, space, i;
1051
1052 len = CMSG_LEN(SOCKCREDSIZE(p->p_ucred->cr_ngroups));
1053 space = CMSG_SPACE(SOCKCREDSIZE(p->p_ucred->cr_ngroups));
1054
1055 m = m_get(M_WAIT, MT_CONTROL);
1056 if (space > MLEN) {
1057 if (space > MCLBYTES)
1058 MEXTMALLOC(m, space, M_WAITOK);
1059 else
1060 m_clget(m, M_WAIT);
1061 if ((m->m_flags & M_EXT) == 0) {
1062 m_free(m);
1063 return (control);
1064 }
1065 }
1066
1067 m->m_len = space;
1068 m->m_next = NULL;
1069 cmp = mtod(m, struct cmsghdr *);
1070 sc = (struct sockcred *)CMSG_DATA(cmp);
1071 cmp->cmsg_len = len;
1072 cmp->cmsg_level = SOL_SOCKET;
1073 cmp->cmsg_type = SCM_CREDS;
1074 sc->sc_uid = p->p_cred->p_ruid;
1075 sc->sc_euid = p->p_ucred->cr_uid;
1076 sc->sc_gid = p->p_cred->p_rgid;
1077 sc->sc_egid = p->p_ucred->cr_gid;
1078 sc->sc_ngroups = p->p_ucred->cr_ngroups;
1079 for (i = 0; i < sc->sc_ngroups; i++)
1080 sc->sc_groups[i] = p->p_ucred->cr_groups[i];
1081
1082 /*
1083 * If a control message already exists, append us to the end.
1084 */
1085 if (control != NULL) {
1086 for (n = control; n->m_next != NULL; n = n->m_next)
1087 ;
1088 n->m_next = m;
1089 } else
1090 control = m;
1091
1092 return (control);
1093 }
1094
1095 int unp_defer, unp_gcing;
1096 extern struct domain unixdomain;
1097
1098 /*
1099 * Comment added long after the fact explaining what's going on here.
1100 * Do a mark-sweep GC of file descriptors on the system, to free up
1101 * any which are caught in flight to an about-to-be-closed socket.
1102 *
1103 * Traditional mark-sweep gc's start at the "root", and mark
1104 * everything reachable from the root (which, in our case would be the
1105 * process table). The mark bits are cleared during the sweep.
1106 *
1107 * XXX For some inexplicable reason (perhaps because the file
1108 * descriptor tables used to live in the u area which could be swapped
1109 * out and thus hard to reach), we do multiple scans over the set of
1110 * descriptors, using use *two* mark bits per object (DEFER and MARK).
1111 * Whenever we find a descriptor which references other descriptors,
1112 * the ones it references are marked with both bits, and we iterate
1113 * over the whole file table until there are no more DEFER bits set.
1114 * We also make an extra pass *before* the GC to clear the mark bits,
1115 * which could have been cleared at almost no cost during the previous
1116 * sweep.
1117 *
1118 * XXX MP: this needs to run with locks such that no other thread of
1119 * control can create or destroy references to file descriptors. it
1120 * may be necessary to defer the GC until later (when the locking
1121 * situation is more hospitable); it may be necessary to push this
1122 * into a separate thread.
1123 */
1124 void
1125 unp_gc()
1126 {
1127 struct file *fp, *nextfp;
1128 struct socket *so, *so1;
1129 struct file **extra_ref, **fpp;
1130 int nunref, i;
1131
1132 if (unp_gcing)
1133 return;
1134 unp_gcing = 1;
1135 unp_defer = 0;
1136
1137 /* Clear mark bits */
1138 LIST_FOREACH(fp, &filehead, f_list)
1139 fp->f_flag &= ~(FMARK|FDEFER);
1140
1141 /*
1142 * Iterate over the set of descriptors, marking ones believed
1143 * (based on refcount) to be referenced from a process, and
1144 * marking for rescan descriptors which are queued on a socket.
1145 */
1146 do {
1147 LIST_FOREACH(fp, &filehead, f_list) {
1148 if (fp->f_flag & FDEFER) {
1149 fp->f_flag &= ~FDEFER;
1150 unp_defer--;
1151 #ifdef DIAGNOSTIC
1152 if (fp->f_count == 0)
1153 panic("unp_gc: deferred unreferenced socket");
1154 #endif
1155 } else {
1156 if (fp->f_count == 0)
1157 continue;
1158 if (fp->f_flag & FMARK)
1159 continue;
1160 if (fp->f_count == fp->f_msgcount)
1161 continue;
1162 }
1163 fp->f_flag |= FMARK;
1164
1165 if (fp->f_type != DTYPE_SOCKET ||
1166 (so = (struct socket *)fp->f_data) == 0)
1167 continue;
1168 if (so->so_proto->pr_domain != &unixdomain ||
1169 (so->so_proto->pr_flags&PR_RIGHTS) == 0)
1170 continue;
1171 #ifdef notdef
1172 if (so->so_rcv.sb_flags & SB_LOCK) {
1173 /*
1174 * This is problematical; it's not clear
1175 * we need to wait for the sockbuf to be
1176 * unlocked (on a uniprocessor, at least),
1177 * and it's also not clear what to do
1178 * if sbwait returns an error due to receipt
1179 * of a signal. If sbwait does return
1180 * an error, we'll go into an infinite
1181 * loop. Delete all of this for now.
1182 */
1183 (void) sbwait(&so->so_rcv);
1184 goto restart;
1185 }
1186 #endif
1187 unp_scan(so->so_rcv.sb_mb, unp_mark, 0);
1188 /*
1189 * mark descriptors referenced from sockets queued on the accept queue as well.
1190 */
1191 if (so->so_options & SO_ACCEPTCONN) {
1192 TAILQ_FOREACH(so1, &so->so_q0, so_qe) {
1193 unp_scan(so1->so_rcv.sb_mb, unp_mark, 0);
1194 }
1195 TAILQ_FOREACH(so1, &so->so_q, so_qe) {
1196 unp_scan(so1->so_rcv.sb_mb, unp_mark, 0);
1197 }
1198 }
1199
1200 }
1201 } while (unp_defer);
1202 /*
1203 * Sweep pass. Find unmarked descriptors, and free them.
1204 *
1205 * We grab an extra reference to each of the file table entries
1206 * that are not otherwise accessible and then free the rights
1207 * that are stored in messages on them.
1208 *
1209 * The bug in the original code is a little tricky, so I'll describe
1210 * what's wrong with it here.
1211 *
1212 * It is incorrect to simply unp_discard each entry for f_msgcount
1213 * times -- consider the case of sockets A and B that contain
1214 * references to each other. On a last close of some other socket,
1215 * we trigger a gc since the number of outstanding rights (unp_rights)
1216 * is non-zero. If during the sweep phase the gc code un_discards,
1217 * we end up doing a (full) closef on the descriptor. A closef on A
1218 * results in the following chain. Closef calls soo_close, which
1219 * calls soclose. Soclose calls first (through the switch
1220 * uipc_usrreq) unp_detach, which re-invokes unp_gc. Unp_gc simply
1221 * returns because the previous instance had set unp_gcing, and
1222 * we return all the way back to soclose, which marks the socket
1223 * with SS_NOFDREF, and then calls sofree. Sofree calls sorflush
1224 * to free up the rights that are queued in messages on the socket A,
1225 * i.e., the reference on B. The sorflush calls via the dom_dispose
1226 * switch unp_dispose, which unp_scans with unp_discard. This second
1227 * instance of unp_discard just calls closef on B.
1228 *
1229 * Well, a similar chain occurs on B, resulting in a sorflush on B,
1230 * which results in another closef on A. Unfortunately, A is already
1231 * being closed, and the descriptor has already been marked with
1232 * SS_NOFDREF, and soclose panics at this point.
1233 *
1234 * Here, we first take an extra reference to each inaccessible
1235 * descriptor. Then, if the inaccessible descriptor is a
1236 * socket, we call sorflush in case it is a Unix domain
1237 * socket. After we destroy all the rights carried in
1238 * messages, we do a last closef to get rid of our extra
1239 * reference. This is the last close, and the unp_detach etc
1240 * will shut down the socket.
1241 *
1242 * 91/09/19, bsy (at) cs.cmu.edu
1243 */
1244 extra_ref = malloc(nfiles * sizeof(struct file *), M_FILE, M_WAITOK);
1245 for (nunref = 0, fp = LIST_FIRST(&filehead), fpp = extra_ref; fp != 0;
1246 fp = nextfp) {
1247 nextfp = LIST_NEXT(fp, f_list);
1248 simple_lock(&fp->f_slock);
1249 if (fp->f_count != 0 &&
1250 fp->f_count == fp->f_msgcount && !(fp->f_flag & FMARK)) {
1251 *fpp++ = fp;
1252 nunref++;
1253 fp->f_count++;
1254 }
1255 simple_unlock(&fp->f_slock);
1256 }
1257 for (i = nunref, fpp = extra_ref; --i >= 0; ++fpp) {
1258 fp = *fpp;
1259 simple_lock(&fp->f_slock);
1260 FILE_USE(fp);
1261 if (fp->f_type == DTYPE_SOCKET)
1262 sorflush((struct socket *)fp->f_data);
1263 FILE_UNUSE(fp, NULL);
1264 }
1265 for (i = nunref, fpp = extra_ref; --i >= 0; ++fpp) {
1266 fp = *fpp;
1267 simple_lock(&fp->f_slock);
1268 FILE_USE(fp);
1269 (void) closef(fp, (struct proc *)0);
1270 }
1271 free((caddr_t)extra_ref, M_FILE);
1272 unp_gcing = 0;
1273 }
1274
1275 void
1276 unp_dispose(m)
1277 struct mbuf *m;
1278 {
1279
1280 if (m)
1281 unp_scan(m, unp_discard, 1);
1282 }
1283
1284 void
1285 unp_scan(m0, op, discard)
1286 struct mbuf *m0;
1287 void (*op) __P((struct file *));
1288 int discard;
1289 {
1290 struct mbuf *m;
1291 struct file **rp;
1292 struct cmsghdr *cm;
1293 int i;
1294 int qfds;
1295
1296 while (m0) {
1297 for (m = m0; m; m = m->m_next) {
1298 if (m->m_type == MT_CONTROL &&
1299 m->m_len >= sizeof(*cm)) {
1300 cm = mtod(m, struct cmsghdr *);
1301 if (cm->cmsg_level != SOL_SOCKET ||
1302 cm->cmsg_type != SCM_RIGHTS)
1303 continue;
1304 qfds = (cm->cmsg_len - CMSG_ALIGN(sizeof(*cm)))
1305 / sizeof(struct file *);
1306 rp = (struct file **)CMSG_DATA(cm);
1307 for (i = 0; i < qfds; i++) {
1308 struct file *fp = *rp;
1309 if (discard)
1310 *rp = 0;
1311 (*op)(fp);
1312 rp++;
1313 }
1314 break; /* XXX, but saves time */
1315 }
1316 }
1317 m0 = m0->m_nextpkt;
1318 }
1319 }
1320
1321 void
1322 unp_mark(fp)
1323 struct file *fp;
1324 {
1325 if (fp == NULL)
1326 return;
1327
1328 if (fp->f_flag & FMARK)
1329 return;
1330
1331 /* If we're already deferred, don't screw up the defer count */
1332 if (fp->f_flag & FDEFER)
1333 return;
1334
1335 /*
1336 * Minimize the number of deferrals... Sockets are the only
1337 * type of descriptor which can hold references to another
1338 * descriptor, so just mark other descriptors, and defer
1339 * unmarked sockets for the next pass.
1340 */
1341 if (fp->f_type == DTYPE_SOCKET) {
1342 unp_defer++;
1343 if (fp->f_count == 0)
1344 panic("unp_mark: queued unref");
1345 fp->f_flag |= FDEFER;
1346 } else {
1347 fp->f_flag |= FMARK;
1348 }
1349 return;
1350 }
1351
1352 void
1353 unp_discard(fp)
1354 struct file *fp;
1355 {
1356 if (fp == NULL)
1357 return;
1358 simple_lock(&fp->f_slock);
1359 fp->f_usecount++; /* i.e. FILE_USE(fp) sans locking */
1360 fp->f_msgcount--;
1361 simple_unlock(&fp->f_slock);
1362 unp_rights--;
1363 (void) closef(fp, (struct proc *)0);
1364 }
1365