uipc_socket.c revision 109439
1/*
2 * Copyright (c) 1982, 1986, 1988, 1990, 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 *	@(#)uipc_socket.c	8.3 (Berkeley) 4/15/94
34 * $FreeBSD: head/sys/kern/uipc_socket.c 109439 2003-01-17 19:20:00Z tmm $
35 */
36
37#include "opt_inet.h"
38#include "opt_mac.h"
39#include "opt_zero.h"
40
41#include <sys/param.h>
42#include <sys/systm.h>
43#include <sys/fcntl.h>
44#include <sys/lock.h>
45#include <sys/mac.h>
46#include <sys/malloc.h>
47#include <sys/mbuf.h>
48#include <sys/mutex.h>
49#include <sys/domain.h>
50#include <sys/file.h>			/* for struct knote */
51#include <sys/kernel.h>
52#include <sys/malloc.h>
53#include <sys/event.h>
54#include <sys/poll.h>
55#include <sys/proc.h>
56#include <sys/protosw.h>
57#include <sys/socket.h>
58#include <sys/socketvar.h>
59#include <sys/resourcevar.h>
60#include <sys/signalvar.h>
61#include <sys/sysctl.h>
62#include <sys/uio.h>
63#include <sys/jail.h>
64
65#include <vm/uma.h>
66
67#include <machine/limits.h>
68
69#ifdef INET
70static int	 do_setopt_accept_filter(struct socket *so, struct sockopt *sopt);
71#endif
72
73static void 	filt_sordetach(struct knote *kn);
74static int 	filt_soread(struct knote *kn, long hint);
75static void 	filt_sowdetach(struct knote *kn);
76static int	filt_sowrite(struct knote *kn, long hint);
77static int	filt_solisten(struct knote *kn, long hint);
78
79static struct filterops solisten_filtops =
80	{ 1, NULL, filt_sordetach, filt_solisten };
81static struct filterops soread_filtops =
82	{ 1, NULL, filt_sordetach, filt_soread };
83static struct filterops sowrite_filtops =
84	{ 1, NULL, filt_sowdetach, filt_sowrite };
85
86uma_zone_t socket_zone;
87so_gen_t	so_gencnt;	/* generation count for sockets */
88
89MALLOC_DEFINE(M_SONAME, "soname", "socket name");
90MALLOC_DEFINE(M_PCB, "pcb", "protocol control block");
91
92SYSCTL_DECL(_kern_ipc);
93
94static int somaxconn = SOMAXCONN;
95SYSCTL_INT(_kern_ipc, KIPC_SOMAXCONN, somaxconn, CTLFLAG_RW,
96    &somaxconn, 0, "Maximum pending socket connection queue size");
97static int numopensockets;
98SYSCTL_INT(_kern_ipc, OID_AUTO, numopensockets, CTLFLAG_RD,
99    &numopensockets, 0, "Number of open sockets");
100#ifdef ZERO_COPY_SOCKETS
101/* These aren't static because they're used in other files. */
102int so_zero_copy_send = 1;
103int so_zero_copy_receive = 1;
104SYSCTL_NODE(_kern_ipc, OID_AUTO, zero_copy, CTLFLAG_RD, 0,
105    "Zero copy controls");
106SYSCTL_INT(_kern_ipc_zero_copy, OID_AUTO, receive, CTLFLAG_RW,
107    &so_zero_copy_receive, 0, "Enable zero copy receive");
108SYSCTL_INT(_kern_ipc_zero_copy, OID_AUTO, send, CTLFLAG_RW,
109    &so_zero_copy_send, 0, "Enable zero copy send");
110#endif /* ZERO_COPY_SOCKETS */
111
112
113/*
114 * Socket operation routines.
115 * These routines are called by the routines in
116 * sys_socket.c or from a system process, and
117 * implement the semantics of socket operations by
118 * switching out to the protocol specific routines.
119 */
120
121/*
122 * Get a socket structure from our zone, and initialize it.
123 * Note that it would probably be better to allocate socket
124 * and PCB at the same time, but I'm not convinced that all
125 * the protocols can be easily modified to do this.
126 *
127 * soalloc() returns a socket with a ref count of 0.
128 */
129struct socket *
130soalloc(waitok)
131	int waitok;
132{
133	struct socket *so;
134#ifdef MAC
135	int error;
136#endif
137	int flag;
138
139	if (waitok == 1)
140		flag = M_WAITOK;
141	else
142		flag = M_NOWAIT;
143	flag |= M_ZERO;
144	so = uma_zalloc(socket_zone, flag);
145	if (so) {
146#ifdef MAC
147		error = mac_init_socket(so, flag);
148		if (error != 0) {
149			uma_zfree(socket_zone, so);
150			so = NULL;
151			return so;
152		}
153#endif
154		/* XXX race condition for reentrant kernel */
155		so->so_gencnt = ++so_gencnt;
156		/* sx_init(&so->so_sxlock, "socket sxlock"); */
157		TAILQ_INIT(&so->so_aiojobq);
158		++numopensockets;
159	}
160	return so;
161}
162
163/*
164 * socreate returns a socket with a ref count of 1.  The socket should be
165 * closed with soclose().
166 */
167int
168socreate(dom, aso, type, proto, cred, td)
169	int dom;
170	struct socket **aso;
171	register int type;
172	int proto;
173	struct ucred *cred;
174	struct thread *td;
175{
176	register struct protosw *prp;
177	register struct socket *so;
178	register int error;
179
180	if (proto)
181		prp = pffindproto(dom, proto, type);
182	else
183		prp = pffindtype(dom, type);
184
185	if (prp == 0 || prp->pr_usrreqs->pru_attach == 0)
186		return (EPROTONOSUPPORT);
187
188	if (jailed(cred) && jail_socket_unixiproute_only &&
189	    prp->pr_domain->dom_family != PF_LOCAL &&
190	    prp->pr_domain->dom_family != PF_INET &&
191	    prp->pr_domain->dom_family != PF_ROUTE) {
192		return (EPROTONOSUPPORT);
193	}
194
195	if (prp->pr_type != type)
196		return (EPROTOTYPE);
197	so = soalloc(M_NOWAIT);
198	if (so == NULL)
199		return (ENOBUFS);
200
201	TAILQ_INIT(&so->so_incomp);
202	TAILQ_INIT(&so->so_comp);
203	so->so_type = type;
204	so->so_cred = crhold(cred);
205	so->so_proto = prp;
206#ifdef MAC
207	mac_create_socket(cred, so);
208#endif
209	soref(so);
210	error = (*prp->pr_usrreqs->pru_attach)(so, proto, td);
211	if (error) {
212		so->so_state |= SS_NOFDREF;
213		sorele(so);
214		return (error);
215	}
216	*aso = so;
217	return (0);
218}
219
220int
221sobind(so, nam, td)
222	struct socket *so;
223	struct sockaddr *nam;
224	struct thread *td;
225{
226	int s = splnet();
227	int error;
228
229	error = (*so->so_proto->pr_usrreqs->pru_bind)(so, nam, td);
230	splx(s);
231	return (error);
232}
233
234void
235sodealloc(struct socket *so)
236{
237
238	KASSERT(so->so_count == 0, ("sodealloc(): so_count %d", so->so_count));
239	so->so_gencnt = ++so_gencnt;
240	if (so->so_rcv.sb_hiwat)
241		(void)chgsbsize(so->so_cred->cr_uidinfo,
242		    &so->so_rcv.sb_hiwat, 0, RLIM_INFINITY);
243	if (so->so_snd.sb_hiwat)
244		(void)chgsbsize(so->so_cred->cr_uidinfo,
245		    &so->so_snd.sb_hiwat, 0, RLIM_INFINITY);
246#ifdef INET
247	/* remove acccept filter if one is present. */
248	if (so->so_accf != NULL)
249		do_setopt_accept_filter(so, NULL);
250#endif
251#ifdef MAC
252	mac_destroy_socket(so);
253#endif
254	crfree(so->so_cred);
255	/* sx_destroy(&so->so_sxlock); */
256	uma_zfree(socket_zone, so);
257	--numopensockets;
258}
259
260int
261solisten(so, backlog, td)
262	register struct socket *so;
263	int backlog;
264	struct thread *td;
265{
266	int s, error;
267
268	s = splnet();
269	if (so->so_state & (SS_ISCONNECTED | SS_ISCONNECTING)) {
270		splx(s);
271		return (EINVAL);
272	}
273	error = (*so->so_proto->pr_usrreqs->pru_listen)(so, td);
274	if (error) {
275		splx(s);
276		return (error);
277	}
278	if (TAILQ_EMPTY(&so->so_comp))
279		so->so_options |= SO_ACCEPTCONN;
280	if (backlog < 0 || backlog > somaxconn)
281		backlog = somaxconn;
282	so->so_qlimit = backlog;
283	splx(s);
284	return (0);
285}
286
287void
288sofree(so)
289	register struct socket *so;
290{
291	struct socket *head = so->so_head;
292
293	KASSERT(so->so_count == 0, ("socket %p so_count not 0", so));
294
295	if (so->so_pcb || (so->so_state & SS_NOFDREF) == 0)
296		return;
297	if (head != NULL) {
298		if (so->so_state & SS_INCOMP) {
299			TAILQ_REMOVE(&head->so_incomp, so, so_list);
300			head->so_incqlen--;
301		} else if (so->so_state & SS_COMP) {
302			/*
303			 * We must not decommission a socket that's
304			 * on the accept(2) queue.  If we do, then
305			 * accept(2) may hang after select(2) indicated
306			 * that the listening socket was ready.
307			 */
308			return;
309		} else {
310			panic("sofree: not queued");
311		}
312		so->so_state &= ~SS_INCOMP;
313		so->so_head = NULL;
314	}
315	sbrelease(&so->so_snd, so);
316	sorflush(so);
317	sodealloc(so);
318}
319
320/*
321 * Close a socket on last file table reference removal.
322 * Initiate disconnect if connected.
323 * Free socket when disconnect complete.
324 *
325 * This function will sorele() the socket.  Note that soclose() may be
326 * called prior to the ref count reaching zero.  The actual socket
327 * structure will not be freed until the ref count reaches zero.
328 */
329int
330soclose(so)
331	register struct socket *so;
332{
333	int s = splnet();		/* conservative */
334	int error = 0;
335
336	funsetown(&so->so_sigio);
337	if (so->so_options & SO_ACCEPTCONN) {
338		struct socket *sp, *sonext;
339
340		sp = TAILQ_FIRST(&so->so_incomp);
341		for (; sp != NULL; sp = sonext) {
342			sonext = TAILQ_NEXT(sp, so_list);
343			(void) soabort(sp);
344		}
345		for (sp = TAILQ_FIRST(&so->so_comp); sp != NULL; sp = sonext) {
346			sonext = TAILQ_NEXT(sp, so_list);
347			/* Dequeue from so_comp since sofree() won't do it */
348			TAILQ_REMOVE(&so->so_comp, sp, so_list);
349			so->so_qlen--;
350			sp->so_state &= ~SS_COMP;
351			sp->so_head = NULL;
352			(void) soabort(sp);
353		}
354	}
355	if (so->so_pcb == 0)
356		goto discard;
357	if (so->so_state & SS_ISCONNECTED) {
358		if ((so->so_state & SS_ISDISCONNECTING) == 0) {
359			error = sodisconnect(so);
360			if (error)
361				goto drop;
362		}
363		if (so->so_options & SO_LINGER) {
364			if ((so->so_state & SS_ISDISCONNECTING) &&
365			    (so->so_state & SS_NBIO))
366				goto drop;
367			while (so->so_state & SS_ISCONNECTED) {
368				error = tsleep(&so->so_timeo,
369				    PSOCK | PCATCH, "soclos", so->so_linger * hz);
370				if (error)
371					break;
372			}
373		}
374	}
375drop:
376	if (so->so_pcb) {
377		int error2 = (*so->so_proto->pr_usrreqs->pru_detach)(so);
378		if (error == 0)
379			error = error2;
380	}
381discard:
382	if (so->so_state & SS_NOFDREF)
383		panic("soclose: NOFDREF");
384	so->so_state |= SS_NOFDREF;
385	sorele(so);
386	splx(s);
387	return (error);
388}
389
390/*
391 * Must be called at splnet...
392 */
393int
394soabort(so)
395	struct socket *so;
396{
397	int error;
398
399	error = (*so->so_proto->pr_usrreqs->pru_abort)(so);
400	if (error) {
401		sotryfree(so);	/* note: does not decrement the ref count */
402		return error;
403	}
404	return (0);
405}
406
407int
408soaccept(so, nam)
409	register struct socket *so;
410	struct sockaddr **nam;
411{
412	int s = splnet();
413	int error;
414
415	if ((so->so_state & SS_NOFDREF) == 0)
416		panic("soaccept: !NOFDREF");
417	so->so_state &= ~SS_NOFDREF;
418	error = (*so->so_proto->pr_usrreqs->pru_accept)(so, nam);
419	splx(s);
420	return (error);
421}
422
423int
424soconnect(so, nam, td)
425	register struct socket *so;
426	struct sockaddr *nam;
427	struct thread *td;
428{
429	int s;
430	int error;
431
432	if (so->so_options & SO_ACCEPTCONN)
433		return (EOPNOTSUPP);
434	s = splnet();
435	/*
436	 * If protocol is connection-based, can only connect once.
437	 * Otherwise, if connected, try to disconnect first.
438	 * This allows user to disconnect by connecting to, e.g.,
439	 * a null address.
440	 */
441	if (so->so_state & (SS_ISCONNECTED|SS_ISCONNECTING) &&
442	    ((so->so_proto->pr_flags & PR_CONNREQUIRED) ||
443	    (error = sodisconnect(so))))
444		error = EISCONN;
445	else
446		error = (*so->so_proto->pr_usrreqs->pru_connect)(so, nam, td);
447	splx(s);
448	return (error);
449}
450
451int
452soconnect2(so1, so2)
453	register struct socket *so1;
454	struct socket *so2;
455{
456	int s = splnet();
457	int error;
458
459	error = (*so1->so_proto->pr_usrreqs->pru_connect2)(so1, so2);
460	splx(s);
461	return (error);
462}
463
464int
465sodisconnect(so)
466	register struct socket *so;
467{
468	int s = splnet();
469	int error;
470
471	if ((so->so_state & SS_ISCONNECTED) == 0) {
472		error = ENOTCONN;
473		goto bad;
474	}
475	if (so->so_state & SS_ISDISCONNECTING) {
476		error = EALREADY;
477		goto bad;
478	}
479	error = (*so->so_proto->pr_usrreqs->pru_disconnect)(so);
480bad:
481	splx(s);
482	return (error);
483}
484
485#define	SBLOCKWAIT(f)	(((f) & MSG_DONTWAIT) ? M_NOWAIT : M_WAITOK)
486/*
487 * Send on a socket.
488 * If send must go all at once and message is larger than
489 * send buffering, then hard error.
490 * Lock against other senders.
491 * If must go all at once and not enough room now, then
492 * inform user that this would block and do nothing.
493 * Otherwise, if nonblocking, send as much as possible.
494 * The data to be sent is described by "uio" if nonzero,
495 * otherwise by the mbuf chain "top" (which must be null
496 * if uio is not).  Data provided in mbuf chain must be small
497 * enough to send all at once.
498 *
499 * Returns nonzero on error, timeout or signal; callers
500 * must check for short counts if EINTR/ERESTART are returned.
501 * Data and control buffers are freed on return.
502 */
503
504#ifdef ZERO_COPY_SOCKETS
505struct so_zerocopy_stats{
506	int size_ok;
507	int align_ok;
508	int found_ifp;
509};
510struct so_zerocopy_stats so_zerocp_stats = {0,0,0};
511#include <netinet/in.h>
512#include <net/route.h>
513#include <netinet/in_pcb.h>
514#include <vm/vm.h>
515#include <vm/vm_page.h>
516#include <vm/vm_object.h>
517#endif /*ZERO_COPY_SOCKETS*/
518
519int
520sosend(so, addr, uio, top, control, flags, td)
521	register struct socket *so;
522	struct sockaddr *addr;
523	struct uio *uio;
524	struct mbuf *top;
525	struct mbuf *control;
526	int flags;
527	struct thread *td;
528{
529	struct mbuf **mp;
530	register struct mbuf *m;
531	register long space, len, resid;
532	int clen = 0, error, s, dontroute, mlen;
533	int atomic = sosendallatonce(so) || top;
534#ifdef ZERO_COPY_SOCKETS
535	int cow_send;
536#endif /* ZERO_COPY_SOCKETS */
537
538	if (uio)
539		resid = uio->uio_resid;
540	else
541		resid = top->m_pkthdr.len;
542	/*
543	 * In theory resid should be unsigned.
544	 * However, space must be signed, as it might be less than 0
545	 * if we over-committed, and we must use a signed comparison
546	 * of space and resid.  On the other hand, a negative resid
547	 * causes us to loop sending 0-length segments to the protocol.
548	 *
549	 * Also check to make sure that MSG_EOR isn't used on SOCK_STREAM
550	 * type sockets since that's an error.
551	 */
552	if (resid < 0 || (so->so_type == SOCK_STREAM && (flags & MSG_EOR))) {
553		error = EINVAL;
554		goto out;
555	}
556
557	dontroute =
558	    (flags & MSG_DONTROUTE) && (so->so_options & SO_DONTROUTE) == 0 &&
559	    (so->so_proto->pr_flags & PR_ATOMIC);
560	if (td)
561		td->td_proc->p_stats->p_ru.ru_msgsnd++;
562	if (control)
563		clen = control->m_len;
564#define	snderr(errno)	{ error = (errno); splx(s); goto release; }
565
566restart:
567	error = sblock(&so->so_snd, SBLOCKWAIT(flags));
568	if (error)
569		goto out;
570	do {
571		s = splnet();
572		if (so->so_state & SS_CANTSENDMORE)
573			snderr(EPIPE);
574		if (so->so_error) {
575			error = so->so_error;
576			so->so_error = 0;
577			splx(s);
578			goto release;
579		}
580		if ((so->so_state & SS_ISCONNECTED) == 0) {
581			/*
582			 * `sendto' and `sendmsg' is allowed on a connection-
583			 * based socket if it supports implied connect.
584			 * Return ENOTCONN if not connected and no address is
585			 * supplied.
586			 */
587			if ((so->so_proto->pr_flags & PR_CONNREQUIRED) &&
588			    (so->so_proto->pr_flags & PR_IMPLOPCL) == 0) {
589				if ((so->so_state & SS_ISCONFIRMING) == 0 &&
590				    !(resid == 0 && clen != 0))
591					snderr(ENOTCONN);
592			} else if (addr == 0)
593			    snderr(so->so_proto->pr_flags & PR_CONNREQUIRED ?
594				   ENOTCONN : EDESTADDRREQ);
595		}
596		space = sbspace(&so->so_snd);
597		if (flags & MSG_OOB)
598			space += 1024;
599		if ((atomic && resid > so->so_snd.sb_hiwat) ||
600		    clen > so->so_snd.sb_hiwat)
601			snderr(EMSGSIZE);
602		if (space < resid + clen &&
603		    (atomic || space < so->so_snd.sb_lowat || space < clen)) {
604			if (so->so_state & SS_NBIO)
605				snderr(EWOULDBLOCK);
606			sbunlock(&so->so_snd);
607			error = sbwait(&so->so_snd);
608			splx(s);
609			if (error)
610				goto out;
611			goto restart;
612		}
613		splx(s);
614		mp = &top;
615		space -= clen;
616		do {
617		    if (uio == NULL) {
618			/*
619			 * Data is prepackaged in "top".
620			 */
621			resid = 0;
622			if (flags & MSG_EOR)
623				top->m_flags |= M_EOR;
624		    } else do {
625#ifdef ZERO_COPY_SOCKETS
626			cow_send = 0;
627#endif /* ZERO_COPY_SOCKETS */
628			if (top == 0) {
629				MGETHDR(m, M_TRYWAIT, MT_DATA);
630				if (m == NULL) {
631					error = ENOBUFS;
632					goto release;
633				}
634				mlen = MHLEN;
635				m->m_pkthdr.len = 0;
636				m->m_pkthdr.rcvif = (struct ifnet *)0;
637			} else {
638				MGET(m, M_TRYWAIT, MT_DATA);
639				if (m == NULL) {
640					error = ENOBUFS;
641					goto release;
642				}
643				mlen = MLEN;
644			}
645			if (resid >= MINCLSIZE) {
646#ifdef ZERO_COPY_SOCKETS
647				if (so_zero_copy_send &&
648				    resid>=PAGE_SIZE &&
649				    space>=PAGE_SIZE &&
650				    uio->uio_iov->iov_len>=PAGE_SIZE) {
651					so_zerocp_stats.size_ok++;
652					if (!((vm_offset_t)
653					  uio->uio_iov->iov_base & PAGE_MASK)){
654						so_zerocp_stats.align_ok++;
655						cow_send = socow_setup(m, uio);
656					}
657				}
658				if (!cow_send){
659#endif /* ZERO_COPY_SOCKETS */
660				MCLGET(m, M_TRYWAIT);
661				if ((m->m_flags & M_EXT) == 0)
662					goto nopages;
663				mlen = MCLBYTES;
664				len = min(min(mlen, resid), space);
665			} else {
666#ifdef ZERO_COPY_SOCKETS
667					len = PAGE_SIZE;
668				}
669
670			} else {
671#endif /* ZERO_COPY_SOCKETS */
672nopages:
673				len = min(min(mlen, resid), space);
674				/*
675				 * For datagram protocols, leave room
676				 * for protocol headers in first mbuf.
677				 */
678				if (atomic && top == 0 && len < mlen)
679					MH_ALIGN(m, len);
680			}
681			space -= len;
682#ifdef ZERO_COPY_SOCKETS
683			if (cow_send)
684				error = 0;
685			else
686#endif /* ZERO_COPY_SOCKETS */
687			error = uiomove(mtod(m, caddr_t), (int)len, uio);
688			resid = uio->uio_resid;
689			m->m_len = len;
690			*mp = m;
691			top->m_pkthdr.len += len;
692			if (error)
693				goto release;
694			mp = &m->m_next;
695			if (resid <= 0) {
696				if (flags & MSG_EOR)
697					top->m_flags |= M_EOR;
698				break;
699			}
700		    } while (space > 0 && atomic);
701		    if (dontroute)
702			    so->so_options |= SO_DONTROUTE;
703		    s = splnet();				/* XXX */
704		    /*
705		     * XXX all the SS_CANTSENDMORE checks previously
706		     * done could be out of date.  We could have recieved
707		     * a reset packet in an interrupt or maybe we slept
708		     * while doing page faults in uiomove() etc. We could
709		     * probably recheck again inside the splnet() protection
710		     * here, but there are probably other places that this
711		     * also happens.  We must rethink this.
712		     */
713		    error = (*so->so_proto->pr_usrreqs->pru_send)(so,
714			(flags & MSG_OOB) ? PRUS_OOB :
715			/*
716			 * If the user set MSG_EOF, the protocol
717			 * understands this flag and nothing left to
718			 * send then use PRU_SEND_EOF instead of PRU_SEND.
719			 */
720			((flags & MSG_EOF) &&
721			 (so->so_proto->pr_flags & PR_IMPLOPCL) &&
722			 (resid <= 0)) ?
723				PRUS_EOF :
724			/* If there is more to send set PRUS_MORETOCOME */
725			(resid > 0 && space > 0) ? PRUS_MORETOCOME : 0,
726			top, addr, control, td);
727		    splx(s);
728		    if (dontroute)
729			    so->so_options &= ~SO_DONTROUTE;
730		    clen = 0;
731		    control = 0;
732		    top = 0;
733		    mp = &top;
734		    if (error)
735			goto release;
736		} while (resid && space > 0);
737	} while (resid);
738
739release:
740	sbunlock(&so->so_snd);
741out:
742	if (top)
743		m_freem(top);
744	if (control)
745		m_freem(control);
746	return (error);
747}
748
749/*
750 * Implement receive operations on a socket.
751 * We depend on the way that records are added to the sockbuf
752 * by sbappend*.  In particular, each record (mbufs linked through m_next)
753 * must begin with an address if the protocol so specifies,
754 * followed by an optional mbuf or mbufs containing ancillary data,
755 * and then zero or more mbufs of data.
756 * In order to avoid blocking network interrupts for the entire time here,
757 * we splx() while doing the actual copy to user space.
758 * Although the sockbuf is locked, new data may still be appended,
759 * and thus we must maintain consistency of the sockbuf during that time.
760 *
761 * The caller may receive the data as a single mbuf chain by supplying
762 * an mbuf **mp0 for use in returning the chain.  The uio is then used
763 * only for the count in uio_resid.
764 */
765int
766soreceive(so, psa, uio, mp0, controlp, flagsp)
767	register struct socket *so;
768	struct sockaddr **psa;
769	struct uio *uio;
770	struct mbuf **mp0;
771	struct mbuf **controlp;
772	int *flagsp;
773{
774	struct mbuf *m, **mp;
775	register int flags, len, error, s, offset;
776	struct protosw *pr = so->so_proto;
777	struct mbuf *nextrecord;
778	int moff, type = 0;
779	int orig_resid = uio->uio_resid;
780
781	mp = mp0;
782	if (psa)
783		*psa = 0;
784	if (controlp)
785		*controlp = 0;
786	if (flagsp)
787		flags = *flagsp &~ MSG_EOR;
788	else
789		flags = 0;
790	if (flags & MSG_OOB) {
791		m = m_get(M_TRYWAIT, MT_DATA);
792		if (m == NULL)
793			return (ENOBUFS);
794		error = (*pr->pr_usrreqs->pru_rcvoob)(so, m, flags & MSG_PEEK);
795		if (error)
796			goto bad;
797		do {
798#ifdef ZERO_COPY_SOCKETS
799			if (so_zero_copy_receive) {
800				vm_page_t pg;
801				int disposable;
802
803				if ((m->m_flags & M_EXT)
804				 && (m->m_ext.ext_type == EXT_DISPOSABLE))
805					disposable = 1;
806				else
807					disposable = 0;
808
809				pg = PHYS_TO_VM_PAGE(vtophys(mtod(m, caddr_t)));
810				if (uio->uio_offset == -1)
811					uio->uio_offset =IDX_TO_OFF(pg->pindex);
812
813				error = uiomoveco(mtod(m, caddr_t),
814						  min(uio->uio_resid, m->m_len),
815						  uio, pg->object,
816						  disposable);
817			} else
818#endif /* ZERO_COPY_SOCKETS */
819			error = uiomove(mtod(m, caddr_t),
820			    (int) min(uio->uio_resid, m->m_len), uio);
821			m = m_free(m);
822		} while (uio->uio_resid && error == 0 && m);
823bad:
824		if (m)
825			m_freem(m);
826		return (error);
827	}
828	if (mp)
829		*mp = (struct mbuf *)0;
830	if (so->so_state & SS_ISCONFIRMING && uio->uio_resid)
831		(*pr->pr_usrreqs->pru_rcvd)(so, 0);
832
833restart:
834	error = sblock(&so->so_rcv, SBLOCKWAIT(flags));
835	if (error)
836		return (error);
837	s = splnet();
838
839	m = so->so_rcv.sb_mb;
840	/*
841	 * If we have less data than requested, block awaiting more
842	 * (subject to any timeout) if:
843	 *   1. the current count is less than the low water mark, or
844	 *   2. MSG_WAITALL is set, and it is possible to do the entire
845	 *	receive operation at once if we block (resid <= hiwat).
846	 *   3. MSG_DONTWAIT is not set
847	 * If MSG_WAITALL is set but resid is larger than the receive buffer,
848	 * we have to do the receive in sections, and thus risk returning
849	 * a short count if a timeout or signal occurs after we start.
850	 */
851	if (m == 0 || (((flags & MSG_DONTWAIT) == 0 &&
852	    so->so_rcv.sb_cc < uio->uio_resid) &&
853	    (so->so_rcv.sb_cc < so->so_rcv.sb_lowat ||
854	    ((flags & MSG_WAITALL) && uio->uio_resid <= so->so_rcv.sb_hiwat)) &&
855	    m->m_nextpkt == 0 && (pr->pr_flags & PR_ATOMIC) == 0)) {
856		KASSERT(m != 0 || !so->so_rcv.sb_cc,
857		    ("receive: m == %p so->so_rcv.sb_cc == %u",
858		    m, so->so_rcv.sb_cc));
859		if (so->so_error) {
860			if (m)
861				goto dontblock;
862			error = so->so_error;
863			if ((flags & MSG_PEEK) == 0)
864				so->so_error = 0;
865			goto release;
866		}
867		if (so->so_state & SS_CANTRCVMORE) {
868			if (m)
869				goto dontblock;
870			else
871				goto release;
872		}
873		for (; m; m = m->m_next)
874			if (m->m_type == MT_OOBDATA  || (m->m_flags & M_EOR)) {
875				m = so->so_rcv.sb_mb;
876				goto dontblock;
877			}
878		if ((so->so_state & (SS_ISCONNECTED|SS_ISCONNECTING)) == 0 &&
879		    (so->so_proto->pr_flags & PR_CONNREQUIRED)) {
880			error = ENOTCONN;
881			goto release;
882		}
883		if (uio->uio_resid == 0)
884			goto release;
885		if ((so->so_state & SS_NBIO) || (flags & MSG_DONTWAIT)) {
886			error = EWOULDBLOCK;
887			goto release;
888		}
889		sbunlock(&so->so_rcv);
890		error = sbwait(&so->so_rcv);
891		splx(s);
892		if (error)
893			return (error);
894		goto restart;
895	}
896dontblock:
897	if (uio->uio_td)
898		uio->uio_td->td_proc->p_stats->p_ru.ru_msgrcv++;
899	nextrecord = m->m_nextpkt;
900	if (pr->pr_flags & PR_ADDR) {
901		KASSERT(m->m_type == MT_SONAME,
902		    ("m->m_type == %d", m->m_type));
903		orig_resid = 0;
904		if (psa)
905			*psa = dup_sockaddr(mtod(m, struct sockaddr *),
906					    mp0 == 0);
907		if (flags & MSG_PEEK) {
908			m = m->m_next;
909		} else {
910			sbfree(&so->so_rcv, m);
911			so->so_rcv.sb_mb = m_free(m);
912			m = so->so_rcv.sb_mb;
913		}
914	}
915	while (m && m->m_type == MT_CONTROL && error == 0) {
916		if (flags & MSG_PEEK) {
917			if (controlp)
918				*controlp = m_copy(m, 0, m->m_len);
919			m = m->m_next;
920		} else {
921			sbfree(&so->so_rcv, m);
922			so->so_rcv.sb_mb = m->m_next;
923			m->m_next = NULL;
924			if (pr->pr_domain->dom_externalize)
925				error =
926				(*pr->pr_domain->dom_externalize)(m, controlp);
927			else if (controlp)
928				*controlp = m;
929			else
930				m_freem(m);
931			m = so->so_rcv.sb_mb;
932		}
933		if (controlp) {
934			orig_resid = 0;
935			do
936				controlp = &(*controlp)->m_next;
937			while (*controlp != NULL);
938		}
939	}
940	if (m) {
941		if ((flags & MSG_PEEK) == 0)
942			m->m_nextpkt = nextrecord;
943		type = m->m_type;
944		if (type == MT_OOBDATA)
945			flags |= MSG_OOB;
946	}
947	moff = 0;
948	offset = 0;
949	while (m && uio->uio_resid > 0 && error == 0) {
950		if (m->m_type == MT_OOBDATA) {
951			if (type != MT_OOBDATA)
952				break;
953		} else if (type == MT_OOBDATA)
954			break;
955		else
956		    KASSERT(m->m_type == MT_DATA || m->m_type == MT_HEADER,
957			("m->m_type == %d", m->m_type));
958		so->so_state &= ~SS_RCVATMARK;
959		len = uio->uio_resid;
960		if (so->so_oobmark && len > so->so_oobmark - offset)
961			len = so->so_oobmark - offset;
962		if (len > m->m_len - moff)
963			len = m->m_len - moff;
964		/*
965		 * If mp is set, just pass back the mbufs.
966		 * Otherwise copy them out via the uio, then free.
967		 * Sockbuf must be consistent here (points to current mbuf,
968		 * it points to next record) when we drop priority;
969		 * we must note any additions to the sockbuf when we
970		 * block interrupts again.
971		 */
972		if (mp == 0) {
973			splx(s);
974#ifdef ZERO_COPY_SOCKETS
975			if (so_zero_copy_receive) {
976				vm_page_t pg;
977				int disposable;
978
979				if ((m->m_flags & M_EXT)
980				 && (m->m_ext.ext_type == EXT_DISPOSABLE))
981					disposable = 1;
982				else
983					disposable = 0;
984
985				pg = PHYS_TO_VM_PAGE(vtophys(mtod(m, caddr_t) +
986					moff));
987
988				if (uio->uio_offset == -1)
989					uio->uio_offset =IDX_TO_OFF(pg->pindex);
990
991				error = uiomoveco(mtod(m, caddr_t) + moff,
992						  (int)len, uio,pg->object,
993						  disposable);
994			} else
995#endif /* ZERO_COPY_SOCKETS */
996			error = uiomove(mtod(m, caddr_t) + moff, (int)len, uio);
997			s = splnet();
998			if (error)
999				goto release;
1000		} else
1001			uio->uio_resid -= len;
1002		if (len == m->m_len - moff) {
1003			if (m->m_flags & M_EOR)
1004				flags |= MSG_EOR;
1005			if (flags & MSG_PEEK) {
1006				m = m->m_next;
1007				moff = 0;
1008			} else {
1009				nextrecord = m->m_nextpkt;
1010				sbfree(&so->so_rcv, m);
1011				if (mp) {
1012					*mp = m;
1013					mp = &m->m_next;
1014					so->so_rcv.sb_mb = m = m->m_next;
1015					*mp = (struct mbuf *)0;
1016				} else {
1017					so->so_rcv.sb_mb = m_free(m);
1018					m = so->so_rcv.sb_mb;
1019				}
1020				if (m)
1021					m->m_nextpkt = nextrecord;
1022			}
1023		} else {
1024			if (flags & MSG_PEEK)
1025				moff += len;
1026			else {
1027				if (mp)
1028					*mp = m_copym(m, 0, len, M_TRYWAIT);
1029				m->m_data += len;
1030				m->m_len -= len;
1031				so->so_rcv.sb_cc -= len;
1032			}
1033		}
1034		if (so->so_oobmark) {
1035			if ((flags & MSG_PEEK) == 0) {
1036				so->so_oobmark -= len;
1037				if (so->so_oobmark == 0) {
1038					so->so_state |= SS_RCVATMARK;
1039					break;
1040				}
1041			} else {
1042				offset += len;
1043				if (offset == so->so_oobmark)
1044					break;
1045			}
1046		}
1047		if (flags & MSG_EOR)
1048			break;
1049		/*
1050		 * If the MSG_WAITALL flag is set (for non-atomic socket),
1051		 * we must not quit until "uio->uio_resid == 0" or an error
1052		 * termination.  If a signal/timeout occurs, return
1053		 * with a short count but without error.
1054		 * Keep sockbuf locked against other readers.
1055		 */
1056		while (flags & MSG_WAITALL && m == 0 && uio->uio_resid > 0 &&
1057		    !sosendallatonce(so) && !nextrecord) {
1058			if (so->so_error || so->so_state & SS_CANTRCVMORE)
1059				break;
1060			/*
1061			 * Notify the protocol that some data has been
1062			 * drained before blocking.
1063			 */
1064			if (pr->pr_flags & PR_WANTRCVD && so->so_pcb)
1065				(*pr->pr_usrreqs->pru_rcvd)(so, flags);
1066			error = sbwait(&so->so_rcv);
1067			if (error) {
1068				sbunlock(&so->so_rcv);
1069				splx(s);
1070				return (0);
1071			}
1072			m = so->so_rcv.sb_mb;
1073			if (m)
1074				nextrecord = m->m_nextpkt;
1075		}
1076	}
1077
1078	if (m && pr->pr_flags & PR_ATOMIC) {
1079		flags |= MSG_TRUNC;
1080		if ((flags & MSG_PEEK) == 0)
1081			(void) sbdroprecord(&so->so_rcv);
1082	}
1083	if ((flags & MSG_PEEK) == 0) {
1084		if (m == 0)
1085			so->so_rcv.sb_mb = nextrecord;
1086		if (pr->pr_flags & PR_WANTRCVD && so->so_pcb)
1087			(*pr->pr_usrreqs->pru_rcvd)(so, flags);
1088	}
1089	if (orig_resid == uio->uio_resid && orig_resid &&
1090	    (flags & MSG_EOR) == 0 && (so->so_state & SS_CANTRCVMORE) == 0) {
1091		sbunlock(&so->so_rcv);
1092		splx(s);
1093		goto restart;
1094	}
1095
1096	if (flagsp)
1097		*flagsp |= flags;
1098release:
1099	sbunlock(&so->so_rcv);
1100	splx(s);
1101	return (error);
1102}
1103
1104int
1105soshutdown(so, how)
1106	register struct socket *so;
1107	register int how;
1108{
1109	register struct protosw *pr = so->so_proto;
1110
1111	if (!(how == SHUT_RD || how == SHUT_WR || how == SHUT_RDWR))
1112		return (EINVAL);
1113
1114	if (how != SHUT_WR)
1115		sorflush(so);
1116	if (how != SHUT_RD)
1117		return ((*pr->pr_usrreqs->pru_shutdown)(so));
1118	return (0);
1119}
1120
1121void
1122sorflush(so)
1123	register struct socket *so;
1124{
1125	register struct sockbuf *sb = &so->so_rcv;
1126	register struct protosw *pr = so->so_proto;
1127	register int s;
1128	struct sockbuf asb;
1129
1130	sb->sb_flags |= SB_NOINTR;
1131	(void) sblock(sb, M_WAITOK);
1132	s = splimp();
1133	socantrcvmore(so);
1134	sbunlock(sb);
1135	asb = *sb;
1136	bzero(sb, sizeof (*sb));
1137	splx(s);
1138	if (pr->pr_flags & PR_RIGHTS && pr->pr_domain->dom_dispose)
1139		(*pr->pr_domain->dom_dispose)(asb.sb_mb);
1140	sbrelease(&asb, so);
1141}
1142
1143#ifdef INET
1144static int
1145do_setopt_accept_filter(so, sopt)
1146	struct	socket *so;
1147	struct	sockopt *sopt;
1148{
1149	struct accept_filter_arg	*afap = NULL;
1150	struct accept_filter	*afp;
1151	struct so_accf	*af = so->so_accf;
1152	int	error = 0;
1153
1154	/* do not set/remove accept filters on non listen sockets */
1155	if ((so->so_options & SO_ACCEPTCONN) == 0) {
1156		error = EINVAL;
1157		goto out;
1158	}
1159
1160	/* removing the filter */
1161	if (sopt == NULL) {
1162		if (af != NULL) {
1163			if (af->so_accept_filter != NULL &&
1164				af->so_accept_filter->accf_destroy != NULL) {
1165				af->so_accept_filter->accf_destroy(so);
1166			}
1167			if (af->so_accept_filter_str != NULL) {
1168				FREE(af->so_accept_filter_str, M_ACCF);
1169			}
1170			FREE(af, M_ACCF);
1171			so->so_accf = NULL;
1172		}
1173		so->so_options &= ~SO_ACCEPTFILTER;
1174		return (0);
1175	}
1176	/* adding a filter */
1177	/* must remove previous filter first */
1178	if (af != NULL) {
1179		error = EINVAL;
1180		goto out;
1181	}
1182	/* don't put large objects on the kernel stack */
1183	MALLOC(afap, struct accept_filter_arg *, sizeof(*afap), M_TEMP, M_WAITOK);
1184	error = sooptcopyin(sopt, afap, sizeof *afap, sizeof *afap);
1185	afap->af_name[sizeof(afap->af_name)-1] = '\0';
1186	afap->af_arg[sizeof(afap->af_arg)-1] = '\0';
1187	if (error)
1188		goto out;
1189	afp = accept_filt_get(afap->af_name);
1190	if (afp == NULL) {
1191		error = ENOENT;
1192		goto out;
1193	}
1194	MALLOC(af, struct so_accf *, sizeof(*af), M_ACCF, M_WAITOK | M_ZERO);
1195	if (afp->accf_create != NULL) {
1196		if (afap->af_name[0] != '\0') {
1197			int len = strlen(afap->af_name) + 1;
1198
1199			MALLOC(af->so_accept_filter_str, char *, len, M_ACCF, M_WAITOK);
1200			strcpy(af->so_accept_filter_str, afap->af_name);
1201		}
1202		af->so_accept_filter_arg = afp->accf_create(so, afap->af_arg);
1203		if (af->so_accept_filter_arg == NULL) {
1204			FREE(af->so_accept_filter_str, M_ACCF);
1205			FREE(af, M_ACCF);
1206			so->so_accf = NULL;
1207			error = EINVAL;
1208			goto out;
1209		}
1210	}
1211	af->so_accept_filter = afp;
1212	so->so_accf = af;
1213	so->so_options |= SO_ACCEPTFILTER;
1214out:
1215	if (afap != NULL)
1216		FREE(afap, M_TEMP);
1217	return (error);
1218}
1219#endif /* INET */
1220
1221/*
1222 * Perhaps this routine, and sooptcopyout(), below, ought to come in
1223 * an additional variant to handle the case where the option value needs
1224 * to be some kind of integer, but not a specific size.
1225 * In addition to their use here, these functions are also called by the
1226 * protocol-level pr_ctloutput() routines.
1227 */
1228int
1229sooptcopyin(sopt, buf, len, minlen)
1230	struct	sockopt *sopt;
1231	void	*buf;
1232	size_t	len;
1233	size_t	minlen;
1234{
1235	size_t	valsize;
1236
1237	/*
1238	 * If the user gives us more than we wanted, we ignore it,
1239	 * but if we don't get the minimum length the caller
1240	 * wants, we return EINVAL.  On success, sopt->sopt_valsize
1241	 * is set to however much we actually retrieved.
1242	 */
1243	if ((valsize = sopt->sopt_valsize) < minlen)
1244		return EINVAL;
1245	if (valsize > len)
1246		sopt->sopt_valsize = valsize = len;
1247
1248	if (sopt->sopt_td != 0)
1249		return (copyin(sopt->sopt_val, buf, valsize));
1250
1251	bcopy(sopt->sopt_val, buf, valsize);
1252	return 0;
1253}
1254
1255int
1256sosetopt(so, sopt)
1257	struct socket *so;
1258	struct sockopt *sopt;
1259{
1260	int	error, optval;
1261	struct	linger l;
1262	struct	timeval tv;
1263	u_long  val;
1264#ifdef MAC
1265	struct mac extmac;
1266#endif
1267
1268	error = 0;
1269	if (sopt->sopt_level != SOL_SOCKET) {
1270		if (so->so_proto && so->so_proto->pr_ctloutput)
1271			return ((*so->so_proto->pr_ctloutput)
1272				  (so, sopt));
1273		error = ENOPROTOOPT;
1274	} else {
1275		switch (sopt->sopt_name) {
1276#ifdef INET
1277		case SO_ACCEPTFILTER:
1278			error = do_setopt_accept_filter(so, sopt);
1279			if (error)
1280				goto bad;
1281			break;
1282#endif
1283		case SO_LINGER:
1284			error = sooptcopyin(sopt, &l, sizeof l, sizeof l);
1285			if (error)
1286				goto bad;
1287
1288			so->so_linger = l.l_linger;
1289			if (l.l_onoff)
1290				so->so_options |= SO_LINGER;
1291			else
1292				so->so_options &= ~SO_LINGER;
1293			break;
1294
1295		case SO_DEBUG:
1296		case SO_KEEPALIVE:
1297		case SO_DONTROUTE:
1298		case SO_USELOOPBACK:
1299		case SO_BROADCAST:
1300		case SO_REUSEADDR:
1301		case SO_REUSEPORT:
1302		case SO_OOBINLINE:
1303		case SO_TIMESTAMP:
1304		case SO_NOSIGPIPE:
1305			error = sooptcopyin(sopt, &optval, sizeof optval,
1306					    sizeof optval);
1307			if (error)
1308				goto bad;
1309			if (optval)
1310				so->so_options |= sopt->sopt_name;
1311			else
1312				so->so_options &= ~sopt->sopt_name;
1313			break;
1314
1315		case SO_SNDBUF:
1316		case SO_RCVBUF:
1317		case SO_SNDLOWAT:
1318		case SO_RCVLOWAT:
1319			error = sooptcopyin(sopt, &optval, sizeof optval,
1320					    sizeof optval);
1321			if (error)
1322				goto bad;
1323
1324			/*
1325			 * Values < 1 make no sense for any of these
1326			 * options, so disallow them.
1327			 */
1328			if (optval < 1) {
1329				error = EINVAL;
1330				goto bad;
1331			}
1332
1333			switch (sopt->sopt_name) {
1334			case SO_SNDBUF:
1335			case SO_RCVBUF:
1336				if (sbreserve(sopt->sopt_name == SO_SNDBUF ?
1337				    &so->so_snd : &so->so_rcv, (u_long)optval,
1338				    so, curthread) == 0) {
1339					error = ENOBUFS;
1340					goto bad;
1341				}
1342				break;
1343
1344			/*
1345			 * Make sure the low-water is never greater than
1346			 * the high-water.
1347			 */
1348			case SO_SNDLOWAT:
1349				so->so_snd.sb_lowat =
1350				    (optval > so->so_snd.sb_hiwat) ?
1351				    so->so_snd.sb_hiwat : optval;
1352				break;
1353			case SO_RCVLOWAT:
1354				so->so_rcv.sb_lowat =
1355				    (optval > so->so_rcv.sb_hiwat) ?
1356				    so->so_rcv.sb_hiwat : optval;
1357				break;
1358			}
1359			break;
1360
1361		case SO_SNDTIMEO:
1362		case SO_RCVTIMEO:
1363			error = sooptcopyin(sopt, &tv, sizeof tv,
1364					    sizeof tv);
1365			if (error)
1366				goto bad;
1367
1368			/* assert(hz > 0); */
1369			if (tv.tv_sec < 0 || tv.tv_sec > SHRT_MAX / hz ||
1370			    tv.tv_usec < 0 || tv.tv_usec >= 1000000) {
1371				error = EDOM;
1372				goto bad;
1373			}
1374			/* assert(tick > 0); */
1375			/* assert(ULONG_MAX - SHRT_MAX >= 1000000); */
1376			val = (u_long)(tv.tv_sec * hz) + tv.tv_usec / tick;
1377			if (val > SHRT_MAX) {
1378				error = EDOM;
1379				goto bad;
1380			}
1381			if (val == 0 && tv.tv_usec != 0)
1382				val = 1;
1383
1384			switch (sopt->sopt_name) {
1385			case SO_SNDTIMEO:
1386				so->so_snd.sb_timeo = val;
1387				break;
1388			case SO_RCVTIMEO:
1389				so->so_rcv.sb_timeo = val;
1390				break;
1391			}
1392			break;
1393		case SO_LABEL:
1394#ifdef MAC
1395			error = sooptcopyin(sopt, &extmac, sizeof extmac,
1396			    sizeof extmac);
1397			if (error)
1398				goto bad;
1399
1400			error = mac_setsockopt_label_set(
1401			    sopt->sopt_td->td_ucred, so, &extmac);
1402
1403#else
1404			error = EOPNOTSUPP;
1405#endif
1406			break;
1407		default:
1408			error = ENOPROTOOPT;
1409			break;
1410		}
1411		if (error == 0 && so->so_proto && so->so_proto->pr_ctloutput) {
1412			(void) ((*so->so_proto->pr_ctloutput)
1413				  (so, sopt));
1414		}
1415	}
1416bad:
1417	return (error);
1418}
1419
1420/* Helper routine for getsockopt */
1421int
1422sooptcopyout(sopt, buf, len)
1423	struct	sockopt *sopt;
1424	void	*buf;
1425	size_t	len;
1426{
1427	int	error;
1428	size_t	valsize;
1429
1430	error = 0;
1431
1432	/*
1433	 * Documented get behavior is that we always return a value,
1434	 * possibly truncated to fit in the user's buffer.
1435	 * Traditional behavior is that we always tell the user
1436	 * precisely how much we copied, rather than something useful
1437	 * like the total amount we had available for her.
1438	 * Note that this interface is not idempotent; the entire answer must
1439	 * generated ahead of time.
1440	 */
1441	valsize = min(len, sopt->sopt_valsize);
1442	sopt->sopt_valsize = valsize;
1443	if (sopt->sopt_val != 0) {
1444		if (sopt->sopt_td != 0)
1445			error = copyout(buf, sopt->sopt_val, valsize);
1446		else
1447			bcopy(buf, sopt->sopt_val, valsize);
1448	}
1449	return error;
1450}
1451
1452int
1453sogetopt(so, sopt)
1454	struct socket *so;
1455	struct sockopt *sopt;
1456{
1457	int	error, optval;
1458	struct	linger l;
1459	struct	timeval tv;
1460#ifdef INET
1461	struct accept_filter_arg *afap;
1462#endif
1463#ifdef MAC
1464	struct mac extmac;
1465#endif
1466
1467	error = 0;
1468	if (sopt->sopt_level != SOL_SOCKET) {
1469		if (so->so_proto && so->so_proto->pr_ctloutput) {
1470			return ((*so->so_proto->pr_ctloutput)
1471				  (so, sopt));
1472		} else
1473			return (ENOPROTOOPT);
1474	} else {
1475		switch (sopt->sopt_name) {
1476#ifdef INET
1477		case SO_ACCEPTFILTER:
1478			if ((so->so_options & SO_ACCEPTCONN) == 0)
1479				return (EINVAL);
1480			MALLOC(afap, struct accept_filter_arg *, sizeof(*afap),
1481				M_TEMP, M_WAITOK | M_ZERO);
1482			if ((so->so_options & SO_ACCEPTFILTER) != 0) {
1483				strcpy(afap->af_name, so->so_accf->so_accept_filter->accf_name);
1484				if (so->so_accf->so_accept_filter_str != NULL)
1485					strcpy(afap->af_arg, so->so_accf->so_accept_filter_str);
1486			}
1487			error = sooptcopyout(sopt, afap, sizeof(*afap));
1488			FREE(afap, M_TEMP);
1489			break;
1490#endif
1491
1492		case SO_LINGER:
1493			l.l_onoff = so->so_options & SO_LINGER;
1494			l.l_linger = so->so_linger;
1495			error = sooptcopyout(sopt, &l, sizeof l);
1496			break;
1497
1498		case SO_USELOOPBACK:
1499		case SO_DONTROUTE:
1500		case SO_DEBUG:
1501		case SO_KEEPALIVE:
1502		case SO_REUSEADDR:
1503		case SO_REUSEPORT:
1504		case SO_BROADCAST:
1505		case SO_OOBINLINE:
1506		case SO_TIMESTAMP:
1507		case SO_NOSIGPIPE:
1508			optval = so->so_options & sopt->sopt_name;
1509integer:
1510			error = sooptcopyout(sopt, &optval, sizeof optval);
1511			break;
1512
1513		case SO_TYPE:
1514			optval = so->so_type;
1515			goto integer;
1516
1517		case SO_ERROR:
1518			optval = so->so_error;
1519			so->so_error = 0;
1520			goto integer;
1521
1522		case SO_SNDBUF:
1523			optval = so->so_snd.sb_hiwat;
1524			goto integer;
1525
1526		case SO_RCVBUF:
1527			optval = so->so_rcv.sb_hiwat;
1528			goto integer;
1529
1530		case SO_SNDLOWAT:
1531			optval = so->so_snd.sb_lowat;
1532			goto integer;
1533
1534		case SO_RCVLOWAT:
1535			optval = so->so_rcv.sb_lowat;
1536			goto integer;
1537
1538		case SO_SNDTIMEO:
1539		case SO_RCVTIMEO:
1540			optval = (sopt->sopt_name == SO_SNDTIMEO ?
1541				  so->so_snd.sb_timeo : so->so_rcv.sb_timeo);
1542
1543			tv.tv_sec = optval / hz;
1544			tv.tv_usec = (optval % hz) * tick;
1545			error = sooptcopyout(sopt, &tv, sizeof tv);
1546			break;
1547		case SO_LABEL:
1548#ifdef MAC
1549			error = mac_getsockopt_label_get(
1550			    sopt->sopt_td->td_ucred, so, &extmac);
1551			if (error)
1552				return (error);
1553			error = sooptcopyout(sopt, &extmac, sizeof extmac);
1554#else
1555			error = EOPNOTSUPP;
1556#endif
1557			break;
1558		case SO_PEERLABEL:
1559#ifdef MAC
1560			error = mac_getsockopt_peerlabel_get(
1561			    sopt->sopt_td->td_ucred, so, &extmac);
1562			if (error)
1563				return (error);
1564			error = sooptcopyout(sopt, &extmac, sizeof extmac);
1565#else
1566			error = EOPNOTSUPP;
1567#endif
1568			break;
1569		default:
1570			error = ENOPROTOOPT;
1571			break;
1572		}
1573		return (error);
1574	}
1575}
1576
1577/* XXX; prepare mbuf for (__FreeBSD__ < 3) routines. */
1578int
1579soopt_getm(struct sockopt *sopt, struct mbuf **mp)
1580{
1581	struct mbuf *m, *m_prev;
1582	int sopt_size = sopt->sopt_valsize;
1583
1584	MGET(m, sopt->sopt_td ? M_TRYWAIT : M_DONTWAIT, MT_DATA);
1585	if (m == 0)
1586		return ENOBUFS;
1587	if (sopt_size > MLEN) {
1588		MCLGET(m, sopt->sopt_td ? M_TRYWAIT : M_DONTWAIT);
1589		if ((m->m_flags & M_EXT) == 0) {
1590			m_free(m);
1591			return ENOBUFS;
1592		}
1593		m->m_len = min(MCLBYTES, sopt_size);
1594	} else {
1595		m->m_len = min(MLEN, sopt_size);
1596	}
1597	sopt_size -= m->m_len;
1598	*mp = m;
1599	m_prev = m;
1600
1601	while (sopt_size) {
1602		MGET(m, sopt->sopt_td ? M_TRYWAIT : M_DONTWAIT, MT_DATA);
1603		if (m == 0) {
1604			m_freem(*mp);
1605			return ENOBUFS;
1606		}
1607		if (sopt_size > MLEN) {
1608			MCLGET(m, sopt->sopt_td ? M_TRYWAIT : M_DONTWAIT);
1609			if ((m->m_flags & M_EXT) == 0) {
1610				m_freem(*mp);
1611				return ENOBUFS;
1612			}
1613			m->m_len = min(MCLBYTES, sopt_size);
1614		} else {
1615			m->m_len = min(MLEN, sopt_size);
1616		}
1617		sopt_size -= m->m_len;
1618		m_prev->m_next = m;
1619		m_prev = m;
1620	}
1621	return 0;
1622}
1623
1624/* XXX; copyin sopt data into mbuf chain for (__FreeBSD__ < 3) routines. */
1625int
1626soopt_mcopyin(struct sockopt *sopt, struct mbuf *m)
1627{
1628	struct mbuf *m0 = m;
1629
1630	if (sopt->sopt_val == NULL)
1631		return 0;
1632	while (m != NULL && sopt->sopt_valsize >= m->m_len) {
1633		if (sopt->sopt_td != NULL) {
1634			int error;
1635
1636			error = copyin(sopt->sopt_val, mtod(m, char *),
1637				       m->m_len);
1638			if (error != 0) {
1639				m_freem(m0);
1640				return(error);
1641			}
1642		} else
1643			bcopy(sopt->sopt_val, mtod(m, char *), m->m_len);
1644		sopt->sopt_valsize -= m->m_len;
1645		(caddr_t)sopt->sopt_val += m->m_len;
1646		m = m->m_next;
1647	}
1648	if (m != NULL) /* should be allocated enoughly at ip6_sooptmcopyin() */
1649		panic("ip6_sooptmcopyin");
1650	return 0;
1651}
1652
1653/* XXX; copyout mbuf chain data into soopt for (__FreeBSD__ < 3) routines. */
1654int
1655soopt_mcopyout(struct sockopt *sopt, struct mbuf *m)
1656{
1657	struct mbuf *m0 = m;
1658	size_t valsize = 0;
1659
1660	if (sopt->sopt_val == NULL)
1661		return 0;
1662	while (m != NULL && sopt->sopt_valsize >= m->m_len) {
1663		if (sopt->sopt_td != NULL) {
1664			int error;
1665
1666			error = copyout(mtod(m, char *), sopt->sopt_val,
1667				       m->m_len);
1668			if (error != 0) {
1669				m_freem(m0);
1670				return(error);
1671			}
1672		} else
1673			bcopy(mtod(m, char *), sopt->sopt_val, m->m_len);
1674	       sopt->sopt_valsize -= m->m_len;
1675	       (caddr_t)sopt->sopt_val += m->m_len;
1676	       valsize += m->m_len;
1677	       m = m->m_next;
1678	}
1679	if (m != NULL) {
1680		/* enough soopt buffer should be given from user-land */
1681		m_freem(m0);
1682		return(EINVAL);
1683	}
1684	sopt->sopt_valsize = valsize;
1685	return 0;
1686}
1687
1688void
1689sohasoutofband(so)
1690	register struct socket *so;
1691{
1692	if (so->so_sigio != NULL)
1693		pgsigio(&so->so_sigio, SIGURG, 0);
1694	selwakeup(&so->so_rcv.sb_sel);
1695}
1696
1697int
1698sopoll(struct socket *so, int events, struct ucred *active_cred,
1699    struct thread *td)
1700{
1701	int revents = 0;
1702	int s = splnet();
1703
1704	if (events & (POLLIN | POLLRDNORM))
1705		if (soreadable(so))
1706			revents |= events & (POLLIN | POLLRDNORM);
1707
1708	if (events & POLLINIGNEOF)
1709		if (so->so_rcv.sb_cc >= so->so_rcv.sb_lowat ||
1710		    !TAILQ_EMPTY(&so->so_comp) || so->so_error)
1711			revents |= POLLINIGNEOF;
1712
1713	if (events & (POLLOUT | POLLWRNORM))
1714		if (sowriteable(so))
1715			revents |= events & (POLLOUT | POLLWRNORM);
1716
1717	if (events & (POLLPRI | POLLRDBAND))
1718		if (so->so_oobmark || (so->so_state & SS_RCVATMARK))
1719			revents |= events & (POLLPRI | POLLRDBAND);
1720
1721	if (revents == 0) {
1722		if (events &
1723		    (POLLIN | POLLINIGNEOF | POLLPRI | POLLRDNORM |
1724		     POLLRDBAND)) {
1725			selrecord(td, &so->so_rcv.sb_sel);
1726			so->so_rcv.sb_flags |= SB_SEL;
1727		}
1728
1729		if (events & (POLLOUT | POLLWRNORM)) {
1730			selrecord(td, &so->so_snd.sb_sel);
1731			so->so_snd.sb_flags |= SB_SEL;
1732		}
1733	}
1734
1735	splx(s);
1736	return (revents);
1737}
1738
1739int
1740soo_kqfilter(struct file *fp, struct knote *kn)
1741{
1742	struct socket *so = kn->kn_fp->f_data;
1743	struct sockbuf *sb;
1744	int s;
1745
1746	switch (kn->kn_filter) {
1747	case EVFILT_READ:
1748		if (so->so_options & SO_ACCEPTCONN)
1749			kn->kn_fop = &solisten_filtops;
1750		else
1751			kn->kn_fop = &soread_filtops;
1752		sb = &so->so_rcv;
1753		break;
1754	case EVFILT_WRITE:
1755		kn->kn_fop = &sowrite_filtops;
1756		sb = &so->so_snd;
1757		break;
1758	default:
1759		return (1);
1760	}
1761
1762	s = splnet();
1763	SLIST_INSERT_HEAD(&sb->sb_sel.si_note, kn, kn_selnext);
1764	sb->sb_flags |= SB_KNOTE;
1765	splx(s);
1766	return (0);
1767}
1768
1769static void
1770filt_sordetach(struct knote *kn)
1771{
1772	struct socket *so = kn->kn_fp->f_data;
1773	int s = splnet();
1774
1775	SLIST_REMOVE(&so->so_rcv.sb_sel.si_note, kn, knote, kn_selnext);
1776	if (SLIST_EMPTY(&so->so_rcv.sb_sel.si_note))
1777		so->so_rcv.sb_flags &= ~SB_KNOTE;
1778	splx(s);
1779}
1780
1781/*ARGSUSED*/
1782static int
1783filt_soread(struct knote *kn, long hint)
1784{
1785	struct socket *so = kn->kn_fp->f_data;
1786
1787	kn->kn_data = so->so_rcv.sb_cc - so->so_rcv.sb_ctl;
1788	if (so->so_state & SS_CANTRCVMORE) {
1789		kn->kn_flags |= EV_EOF;
1790		kn->kn_fflags = so->so_error;
1791		return (1);
1792	}
1793	if (so->so_error)	/* temporary udp error */
1794		return (1);
1795	if (kn->kn_sfflags & NOTE_LOWAT)
1796		return (kn->kn_data >= kn->kn_sdata);
1797	return (so->so_rcv.sb_cc >= so->so_rcv.sb_lowat);
1798}
1799
1800static void
1801filt_sowdetach(struct knote *kn)
1802{
1803	struct socket *so = kn->kn_fp->f_data;
1804	int s = splnet();
1805
1806	SLIST_REMOVE(&so->so_snd.sb_sel.si_note, kn, knote, kn_selnext);
1807	if (SLIST_EMPTY(&so->so_snd.sb_sel.si_note))
1808		so->so_snd.sb_flags &= ~SB_KNOTE;
1809	splx(s);
1810}
1811
1812/*ARGSUSED*/
1813static int
1814filt_sowrite(struct knote *kn, long hint)
1815{
1816	struct socket *so = kn->kn_fp->f_data;
1817
1818	kn->kn_data = sbspace(&so->so_snd);
1819	if (so->so_state & SS_CANTSENDMORE) {
1820		kn->kn_flags |= EV_EOF;
1821		kn->kn_fflags = so->so_error;
1822		return (1);
1823	}
1824	if (so->so_error)	/* temporary udp error */
1825		return (1);
1826	if (((so->so_state & SS_ISCONNECTED) == 0) &&
1827	    (so->so_proto->pr_flags & PR_CONNREQUIRED))
1828		return (0);
1829	if (kn->kn_sfflags & NOTE_LOWAT)
1830		return (kn->kn_data >= kn->kn_sdata);
1831	return (kn->kn_data >= so->so_snd.sb_lowat);
1832}
1833
1834/*ARGSUSED*/
1835static int
1836filt_solisten(struct knote *kn, long hint)
1837{
1838	struct socket *so = kn->kn_fp->f_data;
1839
1840	kn->kn_data = so->so_qlen;
1841	return (! TAILQ_EMPTY(&so->so_comp));
1842}
1843
1844int
1845socheckuid(struct socket *so, uid_t uid)
1846{
1847
1848	if (so == NULL)
1849		return (EPERM);
1850	if (so->so_cred->cr_uid == uid)
1851		return (0);
1852	return (EPERM);
1853}
1854