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