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