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