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