uipc_usrreq.c revision 51801
1/*
2 * Copyright (c) 1982, 1986, 1989, 1991, 1993
3 *	The Regents of the University of California.  All rights reserved.
4 *
5 * Redistribution and use in source and binary forms, with or without
6 * modification, are permitted provided that the following conditions
7 * are met:
8 * 1. Redistributions of source code must retain the above copyright
9 *    notice, this list of conditions and the following disclaimer.
10 * 2. Redistributions in binary form must reproduce the above copyright
11 *    notice, this list of conditions and the following disclaimer in the
12 *    documentation and/or other materials provided with the distribution.
13 * 3. All advertising materials mentioning features or use of this software
14 *    must display the following acknowledgement:
15 *	This product includes software developed by the University of
16 *	California, Berkeley and its contributors.
17 * 4. Neither the name of the University nor the names of its contributors
18 *    may be used to endorse or promote products derived from this software
19 *    without specific prior written permission.
20 *
21 * THIS SOFTWARE IS PROVIDED BY THE REGENTS AND CONTRIBUTORS ``AS IS'' AND
22 * ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
23 * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE
24 * ARE DISCLAIMED.  IN NO EVENT SHALL THE REGENTS OR CONTRIBUTORS BE LIABLE
25 * FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL
26 * DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS
27 * OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION)
28 * HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT
29 * LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY
30 * OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF
31 * SUCH DAMAGE.
32 *
33 *	From: @(#)uipc_usrreq.c	8.3 (Berkeley) 1/4/94
34 * $FreeBSD: head/sys/kern/uipc_usrreq.c 51801 1999-09-29 21:09:41Z guido $
35 */
36
37#include <sys/param.h>
38#include <sys/systm.h>
39#include <sys/kernel.h>
40#include <sys/domain.h>
41#include <sys/fcntl.h>
42#include <sys/malloc.h>		/* XXX must be before <sys/file.h> */
43#include <sys/file.h>
44#include <sys/filedesc.h>
45#include <sys/lock.h>
46#include <sys/mbuf.h>
47#include <sys/namei.h>
48#include <sys/proc.h>
49#include <sys/protosw.h>
50#include <sys/socket.h>
51#include <sys/socketvar.h>
52#include <sys/stat.h>
53#include <sys/sysctl.h>
54#include <sys/un.h>
55#include <sys/unpcb.h>
56#include <sys/vnode.h>
57
58#include <vm/vm_zone.h>
59
60static	struct vm_zone *unp_zone;
61static	unp_gen_t unp_gencnt;
62static	u_int unp_count;
63
64static	struct unp_head unp_shead, unp_dhead;
65
66/*
67 * Unix communications domain.
68 *
69 * TODO:
70 *	SEQPACKET, RDM
71 *	rethink name space problems
72 *	need a proper out-of-band
73 *	lock pushdown
74 */
75static struct	sockaddr sun_noname = { sizeof(sun_noname), AF_LOCAL };
76static ino_t	unp_ino;		/* prototype for fake inode numbers */
77
78static int     unp_attach __P((struct socket *));
79static void    unp_detach __P((struct unpcb *));
80static int     unp_bind __P((struct unpcb *,struct sockaddr *, struct proc *));
81static int     unp_connect __P((struct socket *,struct sockaddr *,
82				struct proc *));
83static void    unp_disconnect __P((struct unpcb *));
84static void    unp_shutdown __P((struct unpcb *));
85static void    unp_drop __P((struct unpcb *, int));
86static void    unp_gc __P((void));
87static void    unp_scan __P((struct mbuf *, void (*)(struct file *)));
88static void    unp_mark __P((struct file *));
89static void    unp_discard __P((struct file *));
90static int     unp_internalize __P((struct mbuf *, struct proc *));
91
92static int
93uipc_abort(struct socket *so)
94{
95	struct unpcb *unp = sotounpcb(so);
96
97	if (unp == 0)
98		return EINVAL;
99	unp_drop(unp, ECONNABORTED);
100	return 0;
101}
102
103static int
104uipc_accept(struct socket *so, struct sockaddr **nam)
105{
106	struct unpcb *unp = sotounpcb(so);
107
108	if (unp == 0)
109		return EINVAL;
110
111	/*
112	 * Pass back name of connected socket,
113	 * if it was bound and we are still connected
114	 * (our peer may have closed already!).
115	 */
116	if (unp->unp_conn && unp->unp_conn->unp_addr) {
117		*nam = dup_sockaddr((struct sockaddr *)unp->unp_conn->unp_addr,
118				    1);
119	} else {
120		*nam = dup_sockaddr((struct sockaddr *)&sun_noname, 1);
121	}
122	return 0;
123}
124
125static int
126uipc_attach(struct socket *so, int proto, struct proc *p)
127{
128	struct unpcb *unp = sotounpcb(so);
129
130	if (unp != 0)
131		return EISCONN;
132	return unp_attach(so);
133}
134
135static int
136uipc_bind(struct socket *so, struct sockaddr *nam, struct proc *p)
137{
138	struct unpcb *unp = sotounpcb(so);
139
140	if (unp == 0)
141		return EINVAL;
142
143	return unp_bind(unp, nam, p);
144}
145
146static int
147uipc_connect(struct socket *so, struct sockaddr *nam, struct proc *p)
148{
149	struct unpcb *unp = sotounpcb(so);
150
151	if (unp == 0)
152		return EINVAL;
153	return unp_connect(so, nam, curproc);
154}
155
156static int
157uipc_connect2(struct socket *so1, struct socket *so2)
158{
159	struct unpcb *unp = sotounpcb(so1);
160
161	if (unp == 0)
162		return EINVAL;
163
164	return unp_connect2(so1, so2);
165}
166
167/* control is EOPNOTSUPP */
168
169static int
170uipc_detach(struct socket *so)
171{
172	struct unpcb *unp = sotounpcb(so);
173
174	if (unp == 0)
175		return EINVAL;
176
177	unp_detach(unp);
178	return 0;
179}
180
181static int
182uipc_disconnect(struct socket *so)
183{
184	struct unpcb *unp = sotounpcb(so);
185
186	if (unp == 0)
187		return EINVAL;
188	unp_disconnect(unp);
189	return 0;
190}
191
192static int
193uipc_listen(struct socket *so, struct proc *p)
194{
195	struct unpcb *unp = sotounpcb(so);
196
197	if (unp == 0 || unp->unp_vnode == 0)
198		return EINVAL;
199	return 0;
200}
201
202static int
203uipc_peeraddr(struct socket *so, struct sockaddr **nam)
204{
205	struct unpcb *unp = sotounpcb(so);
206
207	if (unp == 0)
208		return EINVAL;
209	if (unp->unp_conn && unp->unp_conn->unp_addr)
210		*nam = dup_sockaddr((struct sockaddr *)unp->unp_conn->unp_addr,
211				    1);
212	return 0;
213}
214
215static int
216uipc_rcvd(struct socket *so, int flags)
217{
218	struct unpcb *unp = sotounpcb(so);
219	struct socket *so2;
220
221	if (unp == 0)
222		return EINVAL;
223	switch (so->so_type) {
224	case SOCK_DGRAM:
225		panic("uipc_rcvd DGRAM?");
226		/*NOTREACHED*/
227
228	case SOCK_STREAM:
229		if (unp->unp_conn == 0)
230			break;
231		so2 = unp->unp_conn->unp_socket;
232		/*
233		 * Adjust backpressure on sender
234		 * and wakeup any waiting to write.
235		 */
236		so2->so_snd.sb_mbmax += unp->unp_mbcnt - so->so_rcv.sb_mbcnt;
237		unp->unp_mbcnt = so->so_rcv.sb_mbcnt;
238		so2->so_snd.sb_hiwat += unp->unp_cc - so->so_rcv.sb_cc;
239		unp->unp_cc = so->so_rcv.sb_cc;
240		sowwakeup(so2);
241		break;
242
243	default:
244		panic("uipc_rcvd unknown socktype");
245	}
246	return 0;
247}
248
249/* pru_rcvoob is EOPNOTSUPP */
250
251static int
252uipc_send(struct socket *so, int flags, struct mbuf *m, struct sockaddr *nam,
253	  struct mbuf *control, struct proc *p)
254{
255	int error = 0;
256	struct unpcb *unp = sotounpcb(so);
257	struct socket *so2;
258
259	if (unp == 0) {
260		error = EINVAL;
261		goto release;
262	}
263	if (flags & PRUS_OOB) {
264		error = EOPNOTSUPP;
265		goto release;
266	}
267
268	if (control && (error = unp_internalize(control, p)))
269		goto release;
270
271	switch (so->so_type) {
272	case SOCK_DGRAM:
273	{
274		struct sockaddr *from;
275
276		if (nam) {
277			if (unp->unp_conn) {
278				error = EISCONN;
279				break;
280			}
281			error = unp_connect(so, nam, p);
282			if (error)
283				break;
284		} else {
285			if (unp->unp_conn == 0) {
286				error = ENOTCONN;
287				break;
288			}
289		}
290		so2 = unp->unp_conn->unp_socket;
291		if (unp->unp_addr)
292			from = (struct sockaddr *)unp->unp_addr;
293		else
294			from = &sun_noname;
295		if (sbappendaddr(&so2->so_rcv, from, m, control)) {
296			sorwakeup(so2);
297			m = 0;
298			control = 0;
299		} else
300			error = ENOBUFS;
301		if (nam)
302			unp_disconnect(unp);
303		break;
304	}
305
306	case SOCK_STREAM:
307		/* Connect if not connected yet. */
308		/*
309		 * Note: A better implementation would complain
310		 * if not equal to the peer's address.
311		 */
312		if ((so->so_state & SS_ISCONNECTED) == 0) {
313			if (nam) {
314				error = unp_connect(so, nam, p);
315				if (error)
316					break;	/* XXX */
317			} else {
318				error = ENOTCONN;
319				break;
320			}
321		}
322
323		if (so->so_state & SS_CANTSENDMORE) {
324			error = EPIPE;
325			break;
326		}
327		if (unp->unp_conn == 0)
328			panic("uipc_send connected but no connection?");
329		so2 = unp->unp_conn->unp_socket;
330		/*
331		 * Send to paired receive port, and then reduce
332		 * send buffer hiwater marks to maintain backpressure.
333		 * Wake up readers.
334		 */
335		if (control) {
336			if (sbappendcontrol(&so2->so_rcv, m, control))
337				control = 0;
338		} else
339			sbappend(&so2->so_rcv, m);
340		so->so_snd.sb_mbmax -=
341			so2->so_rcv.sb_mbcnt - unp->unp_conn->unp_mbcnt;
342		unp->unp_conn->unp_mbcnt = so2->so_rcv.sb_mbcnt;
343		so->so_snd.sb_hiwat -=
344		    so2->so_rcv.sb_cc - unp->unp_conn->unp_cc;
345		unp->unp_conn->unp_cc = so2->so_rcv.sb_cc;
346		sorwakeup(so2);
347		m = 0;
348		break;
349
350	default:
351		panic("uipc_send unknown socktype");
352	}
353
354	/*
355	 * SEND_EOF is equivalent to a SEND followed by
356	 * a SHUTDOWN.
357	 */
358	if (flags & PRUS_EOF) {
359		socantsendmore(so);
360		unp_shutdown(unp);
361	}
362
363	if (control && error != 0)
364		unp_dispose(control);
365
366release:
367	if (control)
368		m_freem(control);
369	if (m)
370		m_freem(m);
371	return error;
372}
373
374static int
375uipc_sense(struct socket *so, struct stat *sb)
376{
377	struct unpcb *unp = sotounpcb(so);
378	struct socket *so2;
379
380	if (unp == 0)
381		return EINVAL;
382	sb->st_blksize = so->so_snd.sb_hiwat;
383	if (so->so_type == SOCK_STREAM && unp->unp_conn != 0) {
384		so2 = unp->unp_conn->unp_socket;
385		sb->st_blksize += so2->so_rcv.sb_cc;
386	}
387	sb->st_dev = NOUDEV;
388	if (unp->unp_ino == 0)
389		unp->unp_ino = unp_ino++;
390	sb->st_ino = unp->unp_ino;
391	return (0);
392}
393
394static int
395uipc_shutdown(struct socket *so)
396{
397	struct unpcb *unp = sotounpcb(so);
398
399	if (unp == 0)
400		return EINVAL;
401	socantsendmore(so);
402	unp_shutdown(unp);
403	return 0;
404}
405
406static int
407uipc_sockaddr(struct socket *so, struct sockaddr **nam)
408{
409	struct unpcb *unp = sotounpcb(so);
410
411	if (unp == 0)
412		return EINVAL;
413	if (unp->unp_addr)
414		*nam = dup_sockaddr((struct sockaddr *)unp->unp_addr, 1);
415	return 0;
416}
417
418struct pr_usrreqs uipc_usrreqs = {
419	uipc_abort, uipc_accept, uipc_attach, uipc_bind, uipc_connect,
420	uipc_connect2, pru_control_notsupp, uipc_detach, uipc_disconnect,
421	uipc_listen, uipc_peeraddr, uipc_rcvd, pru_rcvoob_notsupp,
422	uipc_send, uipc_sense, uipc_shutdown, uipc_sockaddr,
423	sosend, soreceive, sopoll
424};
425
426/*
427 * Both send and receive buffers are allocated PIPSIZ bytes of buffering
428 * for stream sockets, although the total for sender and receiver is
429 * actually only PIPSIZ.
430 * Datagram sockets really use the sendspace as the maximum datagram size,
431 * and don't really want to reserve the sendspace.  Their recvspace should
432 * be large enough for at least one max-size datagram plus address.
433 */
434#ifndef PIPSIZ
435#define	PIPSIZ	8192
436#endif
437static u_long	unpst_sendspace = PIPSIZ;
438static u_long	unpst_recvspace = PIPSIZ;
439static u_long	unpdg_sendspace = 2*1024;	/* really max datagram size */
440static u_long	unpdg_recvspace = 4*1024;
441
442static int	unp_rights;			/* file descriptors in flight */
443
444SYSCTL_DECL(_net_local_stream);
445SYSCTL_INT(_net_local_stream, OID_AUTO, sendspace, CTLFLAG_RW,
446	   &unpst_sendspace, 0, "");
447SYSCTL_INT(_net_local_stream, OID_AUTO, recvspace, CTLFLAG_RW,
448	   &unpst_recvspace, 0, "");
449SYSCTL_DECL(_net_local_dgram);
450SYSCTL_INT(_net_local_dgram, OID_AUTO, maxdgram, CTLFLAG_RW,
451	   &unpdg_sendspace, 0, "");
452SYSCTL_INT(_net_local_dgram, OID_AUTO, recvspace, CTLFLAG_RW,
453	   &unpdg_recvspace, 0, "");
454SYSCTL_DECL(_net_local);
455SYSCTL_INT(_net_local, OID_AUTO, inflight, CTLFLAG_RD, &unp_rights, 0, "");
456
457static int
458unp_attach(so)
459	struct socket *so;
460{
461	register struct unpcb *unp;
462	int error;
463
464	if (so->so_snd.sb_hiwat == 0 || so->so_rcv.sb_hiwat == 0) {
465		switch (so->so_type) {
466
467		case SOCK_STREAM:
468			error = soreserve(so, unpst_sendspace, unpst_recvspace);
469			break;
470
471		case SOCK_DGRAM:
472			error = soreserve(so, unpdg_sendspace, unpdg_recvspace);
473			break;
474
475		default:
476			panic("unp_attach");
477		}
478		if (error)
479			return (error);
480	}
481	unp = zalloc(unp_zone);
482	if (unp == NULL)
483		return (ENOBUFS);
484	bzero(unp, sizeof *unp);
485	unp->unp_gencnt = ++unp_gencnt;
486	unp_count++;
487	LIST_INIT(&unp->unp_refs);
488	unp->unp_socket = so;
489	unp->unp_rvnode = curproc->p_fd->fd_rdir;
490	LIST_INSERT_HEAD(so->so_type == SOCK_DGRAM ? &unp_dhead
491			 : &unp_shead, unp, unp_link);
492	so->so_pcb = (caddr_t)unp;
493	return (0);
494}
495
496static void
497unp_detach(unp)
498	register struct unpcb *unp;
499{
500	LIST_REMOVE(unp, unp_link);
501	unp->unp_gencnt = ++unp_gencnt;
502	--unp_count;
503	if (unp->unp_vnode) {
504		unp->unp_vnode->v_socket = 0;
505		vrele(unp->unp_vnode);
506		unp->unp_vnode = 0;
507	}
508	if (unp->unp_conn)
509		unp_disconnect(unp);
510	while (unp->unp_refs.lh_first)
511		unp_drop(unp->unp_refs.lh_first, ECONNRESET);
512	soisdisconnected(unp->unp_socket);
513	unp->unp_socket->so_pcb = 0;
514	if (unp_rights) {
515		/*
516		 * Normally the receive buffer is flushed later,
517		 * in sofree, but if our receive buffer holds references
518		 * to descriptors that are now garbage, we will dispose
519		 * of those descriptor references after the garbage collector
520		 * gets them (resulting in a "panic: closef: count < 0").
521		 */
522		sorflush(unp->unp_socket);
523		unp_gc();
524	}
525	if (unp->unp_addr)
526		FREE(unp->unp_addr, M_SONAME);
527	zfree(unp_zone, unp);
528}
529
530static int
531unp_bind(unp, nam, p)
532	struct unpcb *unp;
533	struct sockaddr *nam;
534	struct proc *p;
535{
536	struct sockaddr_un *soun = (struct sockaddr_un *)nam;
537	register struct vnode *vp;
538	struct vattr vattr;
539	int error, namelen;
540	struct nameidata nd;
541	char buf[SOCK_MAXADDRLEN];
542
543	if (unp->unp_vnode != NULL)
544		return (EINVAL);
545#define offsetof(s, e) ((char *)&((s *)0)->e - (char *)((s *)0))
546	namelen = soun->sun_len - offsetof(struct sockaddr_un, sun_path);
547	if (namelen <= 0)
548		return EINVAL;
549	strncpy(buf, soun->sun_path, namelen);
550	buf[namelen] = 0;	/* null-terminate the string */
551	NDINIT(&nd, CREATE, NOFOLLOW | LOCKPARENT, UIO_SYSSPACE,
552	    buf, p);
553/* SHOULD BE ABLE TO ADOPT EXISTING AND wakeup() ALA FIFO's */
554	error = namei(&nd);
555	if (error)
556		return (error);
557	vp = nd.ni_vp;
558	if (vp != NULL) {
559		VOP_ABORTOP(nd.ni_dvp, &nd.ni_cnd);
560		if (nd.ni_dvp == vp)
561			vrele(nd.ni_dvp);
562		else
563			vput(nd.ni_dvp);
564		vrele(vp);
565		return (EADDRINUSE);
566	}
567	VATTR_NULL(&vattr);
568	vattr.va_type = VSOCK;
569	vattr.va_mode = (ACCESSPERMS & ~p->p_fd->fd_cmask);
570	VOP_LEASE(nd.ni_dvp, p, p->p_ucred, LEASE_WRITE);
571	error = VOP_CREATE(nd.ni_dvp, &nd.ni_vp, &nd.ni_cnd, &vattr);
572	vput(nd.ni_dvp);
573	if (error)
574		return (error);
575	vp = nd.ni_vp;
576	vp->v_socket = unp->unp_socket;
577	unp->unp_vnode = vp;
578	unp->unp_addr = (struct sockaddr_un *)dup_sockaddr(nam, 1);
579	VOP_UNLOCK(vp, 0, p);
580	return (0);
581}
582
583static int
584unp_connect(so, nam, p)
585	struct socket *so;
586	struct sockaddr *nam;
587	struct proc *p;
588{
589	register struct sockaddr_un *soun = (struct sockaddr_un *)nam;
590	register struct vnode *vp;
591	register struct socket *so2, *so3;
592	struct unpcb *unp2, *unp3;
593	int error, len;
594	struct nameidata nd;
595	char buf[SOCK_MAXADDRLEN];
596
597	len = nam->sa_len - offsetof(struct sockaddr_un, sun_path);
598	if (len <= 0)
599		return EINVAL;
600	strncpy(buf, soun->sun_path, len);
601	buf[len] = 0;
602
603	NDINIT(&nd, LOOKUP, FOLLOW | LOCKLEAF, UIO_SYSSPACE, buf, p);
604	error = namei(&nd);
605	if (error)
606		return (error);
607	vp = nd.ni_vp;
608	if (vp->v_type != VSOCK) {
609		error = ENOTSOCK;
610		goto bad;
611	}
612	error = VOP_ACCESS(vp, VWRITE, p->p_ucred, p);
613	if (error)
614		goto bad;
615	so2 = vp->v_socket;
616	if (so2 == 0) {
617		error = ECONNREFUSED;
618		goto bad;
619	}
620	if (so->so_type != so2->so_type) {
621		error = EPROTOTYPE;
622		goto bad;
623	}
624	if (so->so_proto->pr_flags & PR_CONNREQUIRED) {
625		if ((so2->so_options & SO_ACCEPTCONN) == 0 ||
626		    (so3 = sonewconn3(so2, 0, p)) == 0) {
627			error = ECONNREFUSED;
628			goto bad;
629		}
630		unp2 = sotounpcb(so2);
631		unp3 = sotounpcb(so3);
632		if (unp2->unp_addr)
633			unp3->unp_addr = (struct sockaddr_un *)
634				dup_sockaddr((struct sockaddr *)
635					     unp2->unp_addr, 1);
636		so2 = so3;
637	}
638	error = unp_connect2(so, so2);
639bad:
640	vput(vp);
641	return (error);
642}
643
644int
645unp_connect2(so, so2)
646	register struct socket *so;
647	register struct socket *so2;
648{
649	register struct unpcb *unp = sotounpcb(so);
650	register struct unpcb *unp2;
651
652	if (so2->so_type != so->so_type)
653		return (EPROTOTYPE);
654	unp2 = sotounpcb(so2);
655	unp->unp_conn = unp2;
656	switch (so->so_type) {
657
658	case SOCK_DGRAM:
659		LIST_INSERT_HEAD(&unp2->unp_refs, unp, unp_reflink);
660		soisconnected(so);
661		break;
662
663	case SOCK_STREAM:
664		unp2->unp_conn = unp;
665		soisconnected(so);
666		soisconnected(so2);
667		break;
668
669	default:
670		panic("unp_connect2");
671	}
672	return (0);
673}
674
675static void
676unp_disconnect(unp)
677	struct unpcb *unp;
678{
679	register struct unpcb *unp2 = unp->unp_conn;
680
681	if (unp2 == 0)
682		return;
683	unp->unp_conn = 0;
684	switch (unp->unp_socket->so_type) {
685
686	case SOCK_DGRAM:
687		LIST_REMOVE(unp, unp_reflink);
688		unp->unp_socket->so_state &= ~SS_ISCONNECTED;
689		break;
690
691	case SOCK_STREAM:
692		soisdisconnected(unp->unp_socket);
693		unp2->unp_conn = 0;
694		soisdisconnected(unp2->unp_socket);
695		break;
696	}
697}
698
699#ifdef notdef
700void
701unp_abort(unp)
702	struct unpcb *unp;
703{
704
705	unp_detach(unp);
706}
707#endif
708
709static int
710prison_unpcb(struct proc *p, struct unpcb *unp)
711{
712	if (!p->p_prison)
713		return (0);
714	if (p->p_fd->fd_rdir == unp->unp_rvnode)
715		return (0);
716	return (1);
717}
718
719static int
720unp_pcblist SYSCTL_HANDLER_ARGS
721{
722	int error, i, n;
723	struct unpcb *unp, **unp_list;
724	unp_gen_t gencnt;
725	struct xunpgen xug;
726	struct unp_head *head;
727
728	head = ((intptr_t)arg1 == SOCK_DGRAM ? &unp_dhead : &unp_shead);
729
730	/*
731	 * The process of preparing the PCB list is too time-consuming and
732	 * resource-intensive to repeat twice on every request.
733	 */
734	if (req->oldptr == 0) {
735		n = unp_count;
736		req->oldidx = 2 * (sizeof xug)
737			+ (n + n/8) * sizeof(struct xunpcb);
738		return 0;
739	}
740
741	if (req->newptr != 0)
742		return EPERM;
743
744	/*
745	 * OK, now we're committed to doing something.
746	 */
747	gencnt = unp_gencnt;
748	n = unp_count;
749
750	xug.xug_len = sizeof xug;
751	xug.xug_count = n;
752	xug.xug_gen = gencnt;
753	xug.xug_sogen = so_gencnt;
754	error = SYSCTL_OUT(req, &xug, sizeof xug);
755	if (error)
756		return error;
757
758	unp_list = malloc(n * sizeof *unp_list, M_TEMP, M_WAITOK);
759	if (unp_list == 0)
760		return ENOMEM;
761
762	for (unp = head->lh_first, i = 0; unp && i < n;
763	     unp = unp->unp_link.le_next) {
764		if (unp->unp_gencnt <= gencnt && !prison_unpcb(req->p, unp))
765			unp_list[i++] = unp;
766	}
767	n = i;			/* in case we lost some during malloc */
768
769	error = 0;
770	for (i = 0; i < n; i++) {
771		unp = unp_list[i];
772		if (unp->unp_gencnt <= gencnt) {
773			struct xunpcb xu;
774			xu.xu_len = sizeof xu;
775			xu.xu_unpp = unp;
776			/*
777			 * XXX - need more locking here to protect against
778			 * connect/disconnect races for SMP.
779			 */
780			if (unp->unp_addr)
781				bcopy(unp->unp_addr, &xu.xu_addr,
782				      unp->unp_addr->sun_len);
783			if (unp->unp_conn && unp->unp_conn->unp_addr)
784				bcopy(unp->unp_conn->unp_addr,
785				      &xu.xu_caddr,
786				      unp->unp_conn->unp_addr->sun_len);
787			bcopy(unp, &xu.xu_unp, sizeof *unp);
788			sotoxsocket(unp->unp_socket, &xu.xu_socket);
789			error = SYSCTL_OUT(req, &xu, sizeof xu);
790		}
791	}
792	if (!error) {
793		/*
794		 * Give the user an updated idea of our state.
795		 * If the generation differs from what we told
796		 * her before, she knows that something happened
797		 * while we were processing this request, and it
798		 * might be necessary to retry.
799		 */
800		xug.xug_gen = unp_gencnt;
801		xug.xug_sogen = so_gencnt;
802		xug.xug_count = unp_count;
803		error = SYSCTL_OUT(req, &xug, sizeof xug);
804	}
805	free(unp_list, M_TEMP);
806	return error;
807}
808
809SYSCTL_PROC(_net_local_dgram, OID_AUTO, pcblist, CTLFLAG_RD,
810	    (caddr_t)(long)SOCK_DGRAM, 0, unp_pcblist, "S,xunpcb",
811	    "List of active local datagram sockets");
812SYSCTL_PROC(_net_local_stream, OID_AUTO, pcblist, CTLFLAG_RD,
813	    (caddr_t)(long)SOCK_STREAM, 0, unp_pcblist, "S,xunpcb",
814	    "List of active local stream sockets");
815
816static void
817unp_shutdown(unp)
818	struct unpcb *unp;
819{
820	struct socket *so;
821
822	if (unp->unp_socket->so_type == SOCK_STREAM && unp->unp_conn &&
823	    (so = unp->unp_conn->unp_socket))
824		socantrcvmore(so);
825}
826
827static void
828unp_drop(unp, errno)
829	struct unpcb *unp;
830	int errno;
831{
832	struct socket *so = unp->unp_socket;
833
834	so->so_error = errno;
835	unp_disconnect(unp);
836	if (so->so_head) {
837		LIST_REMOVE(unp, unp_link);
838		unp->unp_gencnt = ++unp_gencnt;
839		unp_count--;
840		so->so_pcb = (caddr_t) 0;
841		if (unp->unp_addr)
842			FREE(unp->unp_addr, M_SONAME);
843		zfree(unp_zone, unp);
844		sofree(so);
845	}
846}
847
848#ifdef notdef
849void
850unp_drain()
851{
852
853}
854#endif
855
856int
857unp_externalize(rights)
858	struct mbuf *rights;
859{
860	struct proc *p = curproc;		/* XXX */
861	register int i;
862	register struct cmsghdr *cm = mtod(rights, struct cmsghdr *);
863	register struct file **rp = (struct file **)(cm + 1);
864	register struct file *fp;
865	int newfds = (cm->cmsg_len - sizeof(*cm)) / sizeof (int);
866	int f;
867
868	/*
869	 * if the new FD's will not fit, then we free them all
870	 */
871	if (!fdavail(p, newfds)) {
872		for (i = 0; i < newfds; i++) {
873			fp = *rp;
874			unp_discard(fp);
875			*rp++ = 0;
876		}
877		return (EMSGSIZE);
878	}
879	/*
880	 * now change each pointer to an fd in the global table to
881	 * an integer that is the index to the local fd table entry
882	 * that we set up to point to the global one we are transferring.
883	 * XXX this assumes a pointer and int are the same size...!
884	 */
885	for (i = 0; i < newfds; i++) {
886		if (fdalloc(p, 0, &f))
887			panic("unp_externalize");
888		fp = *rp;
889		p->p_fd->fd_ofiles[f] = fp;
890		fp->f_msgcount--;
891		unp_rights--;
892		*(int *)rp++ = f;
893	}
894	return (0);
895}
896
897void
898unp_init(void)
899{
900	unp_zone = zinit("unpcb", sizeof(struct unpcb), nmbclusters, 0, 0);
901	if (unp_zone == 0)
902		panic("unp_init");
903	LIST_INIT(&unp_dhead);
904	LIST_INIT(&unp_shead);
905}
906
907#ifndef MIN
908#define	MIN(a,b) (((a)<(b))?(a):(b))
909#endif
910
911static int
912unp_internalize(control, p)
913	struct mbuf *control;
914	struct proc *p;
915{
916	struct filedesc *fdp = p->p_fd;
917	register struct cmsghdr *cm = mtod(control, struct cmsghdr *);
918	register struct file **rp;
919	register struct file *fp;
920	register int i, fd;
921	register struct cmsgcred *cmcred;
922	int oldfds;
923
924	if ((cm->cmsg_type != SCM_RIGHTS && cm->cmsg_type != SCM_CREDS) ||
925	    cm->cmsg_level != SOL_SOCKET || cm->cmsg_len != control->m_len)
926		return (EINVAL);
927
928	/*
929	 * Fill in credential information.
930	 */
931	if (cm->cmsg_type == SCM_CREDS) {
932		cmcred = (struct cmsgcred *)(cm + 1);
933		cmcred->cmcred_pid = p->p_pid;
934		cmcred->cmcred_uid = p->p_cred->p_ruid;
935		cmcred->cmcred_gid = p->p_cred->p_rgid;
936		cmcred->cmcred_euid = p->p_ucred->cr_uid;
937		cmcred->cmcred_ngroups = MIN(p->p_ucred->cr_ngroups,
938							CMGROUP_MAX);
939		for (i = 0; i < cmcred->cmcred_ngroups; i++)
940			cmcred->cmcred_groups[i] = p->p_ucred->cr_groups[i];
941		return(0);
942	}
943
944	oldfds = (cm->cmsg_len - sizeof (*cm)) / sizeof (int);
945	/*
946	 * check that all the FDs passed in refer to legal OPEN files
947	 * If not, reject the entire operation.
948	 */
949	rp = (struct file **)(cm + 1);
950	for (i = 0; i < oldfds; i++) {
951		fd = *(int *)rp++;
952		if ((unsigned)fd >= fdp->fd_nfiles ||
953		    fdp->fd_ofiles[fd] == NULL)
954			return (EBADF);
955	}
956	/*
957	 * Now replace the integer FDs with pointers to
958	 * the associated global file table entry..
959	 * XXX this assumes a pointer and an int are the same size!
960	 */
961	rp = (struct file **)(cm + 1);
962	for (i = 0; i < oldfds; i++) {
963		fp = fdp->fd_ofiles[*(int *)rp];
964		*rp++ = fp;
965		fp->f_count++;
966		fp->f_msgcount++;
967		unp_rights++;
968	}
969	return (0);
970}
971
972static int	unp_defer, unp_gcing;
973
974static void
975unp_gc()
976{
977	register struct file *fp, *nextfp;
978	register struct socket *so;
979	struct file **extra_ref, **fpp;
980	int nunref, i;
981
982	if (unp_gcing)
983		return;
984	unp_gcing = 1;
985	unp_defer = 0;
986	/*
987	 * before going through all this, set all FDs to
988	 * be NOT defered and NOT externally accessible
989	 */
990	for (fp = filehead.lh_first; fp != 0; fp = fp->f_list.le_next)
991		fp->f_flag &= ~(FMARK|FDEFER);
992	do {
993		for (fp = filehead.lh_first; fp != 0; fp = fp->f_list.le_next) {
994			/*
995			 * If the file is not open, skip it
996			 */
997			if (fp->f_count == 0)
998				continue;
999			/*
1000			 * If we already marked it as 'defer'  in a
1001			 * previous pass, then try process it this time
1002			 * and un-mark it
1003			 */
1004			if (fp->f_flag & FDEFER) {
1005				fp->f_flag &= ~FDEFER;
1006				unp_defer--;
1007			} else {
1008				/*
1009				 * if it's not defered, then check if it's
1010				 * already marked.. if so skip it
1011				 */
1012				if (fp->f_flag & FMARK)
1013					continue;
1014				/*
1015				 * If all references are from messages
1016				 * in transit, then skip it. it's not
1017				 * externally accessible.
1018				 */
1019				if (fp->f_count == fp->f_msgcount)
1020					continue;
1021				/*
1022				 * If it got this far then it must be
1023				 * externally accessible.
1024				 */
1025				fp->f_flag |= FMARK;
1026			}
1027			/*
1028			 * either it was defered, or it is externally
1029			 * accessible and not already marked so.
1030			 * Now check if it is possibly one of OUR sockets.
1031			 */
1032			if (fp->f_type != DTYPE_SOCKET ||
1033			    (so = (struct socket *)fp->f_data) == 0)
1034				continue;
1035			if (so->so_proto->pr_domain != &localdomain ||
1036			    (so->so_proto->pr_flags&PR_RIGHTS) == 0)
1037				continue;
1038#ifdef notdef
1039			if (so->so_rcv.sb_flags & SB_LOCK) {
1040				/*
1041				 * This is problematical; it's not clear
1042				 * we need to wait for the sockbuf to be
1043				 * unlocked (on a uniprocessor, at least),
1044				 * and it's also not clear what to do
1045				 * if sbwait returns an error due to receipt
1046				 * of a signal.  If sbwait does return
1047				 * an error, we'll go into an infinite
1048				 * loop.  Delete all of this for now.
1049				 */
1050				(void) sbwait(&so->so_rcv);
1051				goto restart;
1052			}
1053#endif
1054			/*
1055			 * So, Ok, it's one of our sockets and it IS externally
1056			 * accessible (or was defered). Now we look
1057			 * to see if we hold any file descriptors in its
1058			 * message buffers. Follow those links and mark them
1059			 * as accessible too.
1060			 */
1061			unp_scan(so->so_rcv.sb_mb, unp_mark);
1062		}
1063	} while (unp_defer);
1064	/*
1065	 * We grab an extra reference to each of the file table entries
1066	 * that are not otherwise accessible and then free the rights
1067	 * that are stored in messages on them.
1068	 *
1069	 * The bug in the orginal code is a little tricky, so I'll describe
1070	 * what's wrong with it here.
1071	 *
1072	 * It is incorrect to simply unp_discard each entry for f_msgcount
1073	 * times -- consider the case of sockets A and B that contain
1074	 * references to each other.  On a last close of some other socket,
1075	 * we trigger a gc since the number of outstanding rights (unp_rights)
1076	 * is non-zero.  If during the sweep phase the gc code un_discards,
1077	 * we end up doing a (full) closef on the descriptor.  A closef on A
1078	 * results in the following chain.  Closef calls soo_close, which
1079	 * calls soclose.   Soclose calls first (through the switch
1080	 * uipc_usrreq) unp_detach, which re-invokes unp_gc.  Unp_gc simply
1081	 * returns because the previous instance had set unp_gcing, and
1082	 * we return all the way back to soclose, which marks the socket
1083	 * with SS_NOFDREF, and then calls sofree.  Sofree calls sorflush
1084	 * to free up the rights that are queued in messages on the socket A,
1085	 * i.e., the reference on B.  The sorflush calls via the dom_dispose
1086	 * switch unp_dispose, which unp_scans with unp_discard.  This second
1087	 * instance of unp_discard just calls closef on B.
1088	 *
1089	 * Well, a similar chain occurs on B, resulting in a sorflush on B,
1090	 * which results in another closef on A.  Unfortunately, A is already
1091	 * being closed, and the descriptor has already been marked with
1092	 * SS_NOFDREF, and soclose panics at this point.
1093	 *
1094	 * Here, we first take an extra reference to each inaccessible
1095	 * descriptor.  Then, we call sorflush ourself, since we know
1096	 * it is a Unix domain socket anyhow.  After we destroy all the
1097	 * rights carried in messages, we do a last closef to get rid
1098	 * of our extra reference.  This is the last close, and the
1099	 * unp_detach etc will shut down the socket.
1100	 *
1101	 * 91/09/19, bsy@cs.cmu.edu
1102	 */
1103	extra_ref = malloc(nfiles * sizeof(struct file *), M_FILE, M_WAITOK);
1104	for (nunref = 0, fp = filehead.lh_first, fpp = extra_ref; fp != 0;
1105	    fp = nextfp) {
1106		nextfp = fp->f_list.le_next;
1107		/*
1108		 * If it's not open, skip it
1109		 */
1110		if (fp->f_count == 0)
1111			continue;
1112		/*
1113		 * If all refs are from msgs, and it's not marked accessible
1114		 * then it must be referenced from some unreachable cycle
1115		 * of (shut-down) FDs, so include it in our
1116		 * list of FDs to remove
1117		 */
1118		if (fp->f_count == fp->f_msgcount && !(fp->f_flag & FMARK)) {
1119			*fpp++ = fp;
1120			nunref++;
1121			fp->f_count++;
1122		}
1123	}
1124	/*
1125	 * for each FD on our hit list, do the following two things
1126	 */
1127	for (i = nunref, fpp = extra_ref; --i >= 0; ++fpp) {
1128		struct file *tfp = *fpp;
1129		if (tfp->f_type == DTYPE_SOCKET && tfp->f_data != NULL)
1130			sorflush((struct socket *)(tfp->f_data));
1131	}
1132	for (i = nunref, fpp = extra_ref; --i >= 0; ++fpp)
1133		closef(*fpp, (struct proc *) NULL);
1134	free((caddr_t)extra_ref, M_FILE);
1135	unp_gcing = 0;
1136}
1137
1138void
1139unp_dispose(m)
1140	struct mbuf *m;
1141{
1142
1143	if (m)
1144		unp_scan(m, unp_discard);
1145}
1146
1147static void
1148unp_scan(m0, op)
1149	register struct mbuf *m0;
1150	void (*op) __P((struct file *));
1151{
1152	register struct mbuf *m;
1153	register struct file **rp;
1154	register struct cmsghdr *cm;
1155	register int i;
1156	int qfds;
1157
1158	while (m0) {
1159		for (m = m0; m; m = m->m_next)
1160			if (m->m_type == MT_CONTROL &&
1161			    m->m_len >= sizeof(*cm)) {
1162				cm = mtod(m, struct cmsghdr *);
1163				if (cm->cmsg_level != SOL_SOCKET ||
1164				    cm->cmsg_type != SCM_RIGHTS)
1165					continue;
1166				qfds = (cm->cmsg_len - sizeof *cm)
1167						/ sizeof (struct file *);
1168				rp = (struct file **)(cm + 1);
1169				for (i = 0; i < qfds; i++)
1170					(*op)(*rp++);
1171				break;		/* XXX, but saves time */
1172			}
1173		m0 = m0->m_act;
1174	}
1175}
1176
1177static void
1178unp_mark(fp)
1179	struct file *fp;
1180{
1181
1182	if (fp->f_flag & FMARK)
1183		return;
1184	unp_defer++;
1185	fp->f_flag |= (FMARK|FDEFER);
1186}
1187
1188static void
1189unp_discard(fp)
1190	struct file *fp;
1191{
1192
1193	fp->f_msgcount--;
1194	unp_rights--;
1195	(void) closef(fp, (struct proc *)NULL);
1196}
1197