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