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