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