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