2 * Copyright (c) 2004 Jeffrey M. Hsu. All rights reserved.
3 * Copyright (c) 2004 The DragonFly Project. All rights reserved.
5 * This code is derived from software contributed to The DragonFly Project
8 * Redistribution and use in source and binary forms, with or without
9 * modification, are permitted provided that the following conditions
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.
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
35 * Copyright (c) 2004 Jeffrey M. Hsu. All rights reserved.
37 * License terms: all terms for the DragonFly license above plus the following:
39 * 4. All advertising materials mentioning features or use of this software
40 * must display the following acknowledgement:
42 * This product includes software developed by Jeffrey M. Hsu
43 * for the DragonFly Project.
45 * This requirement may be waived with permission from Jeffrey Hsu.
46 * This requirement will sunset and may be removed on July 8 2005,
47 * after which the standard DragonFly license (as shown above) will
52 * Copyright (c) 1982, 1986, 1988, 1990, 1993
53 * The Regents of the University of California. All rights reserved.
55 * Redistribution and use in source and binary forms, with or without
56 * modification, are permitted provided that the following conditions
58 * 1. Redistributions of source code must retain the above copyright
59 * notice, this list of conditions and the following disclaimer.
60 * 2. Redistributions in binary form must reproduce the above copyright
61 * notice, this list of conditions and the following disclaimer in the
62 * documentation and/or other materials provided with the distribution.
63 * 3. All advertising materials mentioning features or use of this software
64 * must display the following acknowledgement:
65 * This product includes software developed by the University of
66 * California, Berkeley and its contributors.
67 * 4. Neither the name of the University nor the names of its contributors
68 * may be used to endorse or promote products derived from this software
69 * without specific prior written permission.
71 * THIS SOFTWARE IS PROVIDED BY THE REGENTS AND CONTRIBUTORS ``AS IS'' AND
72 * ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
73 * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE
74 * ARE DISCLAIMED. IN NO EVENT SHALL THE REGENTS OR CONTRIBUTORS BE LIABLE
75 * FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL
76 * DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS
77 * OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION)
78 * HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT
79 * LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY
80 * OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF
83 * @(#)uipc_socket.c 8.3 (Berkeley) 4/15/94
84 * $FreeBSD: src/sys/kern/uipc_socket.c,v 1.68.2.24 2003/11/11 17:18:18 silby Exp $
85 * $DragonFly: src/sys/kern/uipc_socket.c,v 1.42 2007/01/01 22:51:17 corecode Exp $
91 #include <sys/param.h>
92 #include <sys/systm.h>
93 #include <sys/fcntl.h>
94 #include <sys/malloc.h>
96 #include <sys/domain.h>
97 #include <sys/file.h> /* for struct knote */
98 #include <sys/kernel.h>
99 #include <sys/malloc.h>
100 #include <sys/event.h>
101 #include <sys/poll.h>
102 #include <sys/proc.h>
103 #include <sys/protosw.h>
104 #include <sys/socket.h>
105 #include <sys/socketvar.h>
106 #include <sys/socketops.h>
107 #include <sys/resourcevar.h>
108 #include <sys/signalvar.h>
109 #include <sys/sysctl.h>
111 #include <sys/jail.h>
112 #include <vm/vm_zone.h>
114 #include <sys/thread2.h>
116 #include <machine/limits.h>
119 static int do_setopt_accept_filter(struct socket *so, struct sockopt *sopt);
122 static void filt_sordetach(struct knote *kn);
123 static int filt_soread(struct knote *kn, long hint);
124 static void filt_sowdetach(struct knote *kn);
125 static int filt_sowrite(struct knote *kn, long hint);
126 static int filt_solisten(struct knote *kn, long hint);
128 static struct filterops solisten_filtops =
129 { 1, NULL, filt_sordetach, filt_solisten };
130 static struct filterops soread_filtops =
131 { 1, NULL, filt_sordetach, filt_soread };
132 static struct filterops sowrite_filtops =
133 { 1, NULL, filt_sowdetach, filt_sowrite };
135 struct vm_zone *socket_zone;
137 MALLOC_DEFINE(M_SONAME, "soname", "socket name");
138 MALLOC_DEFINE(M_PCB, "pcb", "protocol control block");
141 static int somaxconn = SOMAXCONN;
142 SYSCTL_INT(_kern_ipc, KIPC_SOMAXCONN, somaxconn, CTLFLAG_RW,
143 &somaxconn, 0, "Maximum pending socket connection queue size");
146 * Socket operation routines.
147 * These routines are called by the routines in
148 * sys_socket.c or from a system process, and
149 * implement the semantics of socket operations by
150 * switching out to the protocol specific routines.
154 * Get a socket structure from our zone, and initialize it.
155 * We don't implement `waitok' yet (see comments in uipc_domain.c).
156 * Note that it would probably be better to allocate socket
157 * and PCB at the same time, but I'm not convinced that all
158 * the protocols can be easily modified to do this.
165 so = zalloc(socket_zone);
167 /* XXX race condition for reentrant kernel */
168 bzero(so, sizeof *so);
169 TAILQ_INIT(&so->so_aiojobq);
170 TAILQ_INIT(&so->so_rcv.sb_sel.si_mlist);
171 TAILQ_INIT(&so->so_snd.sb_sel.si_mlist);
177 socreate(int dom, struct socket **aso, int type,
178 int proto, struct thread *td)
180 struct proc *p = td->td_proc;
183 struct pru_attach_info ai;
187 prp = pffindproto(dom, proto, type);
189 prp = pffindtype(dom, type);
191 if (prp == 0 || prp->pr_usrreqs->pru_attach == 0)
192 return (EPROTONOSUPPORT);
194 if (p->p_ucred->cr_prison && jail_socket_unixiproute_only &&
195 prp->pr_domain->dom_family != PF_LOCAL &&
196 prp->pr_domain->dom_family != PF_INET &&
197 prp->pr_domain->dom_family != PF_INET6 &&
198 prp->pr_domain->dom_family != PF_ROUTE) {
199 return (EPROTONOSUPPORT);
202 if (prp->pr_type != type)
204 so = soalloc(p != 0);
208 TAILQ_INIT(&so->so_incomp);
209 TAILQ_INIT(&so->so_comp);
211 so->so_cred = crhold(p->p_ucred);
213 ai.sb_rlimit = &p->p_rlimit[RLIMIT_SBSIZE];
214 ai.p_ucred = p->p_ucred;
215 ai.fd_rdir = p->p_fd->fd_rdir;
216 error = so_pru_attach(so, proto, &ai);
218 so->so_state |= SS_NOFDREF;
227 sobind(struct socket *so, struct sockaddr *nam, struct thread *td)
232 error = so_pru_bind(so, nam, td);
238 sodealloc(struct socket *so)
240 if (so->so_rcv.sb_hiwat)
241 (void)chgsbsize(so->so_cred->cr_uidinfo,
242 &so->so_rcv.sb_hiwat, 0, RLIM_INFINITY);
243 if (so->so_snd.sb_hiwat)
244 (void)chgsbsize(so->so_cred->cr_uidinfo,
245 &so->so_snd.sb_hiwat, 0, RLIM_INFINITY);
247 /* remove accept filter if present */
248 if (so->so_accf != NULL)
249 do_setopt_accept_filter(so, NULL);
252 zfree(socket_zone, so);
256 solisten(struct socket *so, int backlog, struct thread *td)
260 short oldopt, oldqlimit;
264 if (so->so_state & (SS_ISCONNECTED | SS_ISCONNECTING)) {
270 oldopt = so->so_options;
271 oldqlimit = so->so_qlimit;
274 if (TAILQ_EMPTY(&so->so_comp))
275 so->so_options |= SO_ACCEPTCONN;
276 if (backlog < 0 || backlog > somaxconn)
278 so->so_qlimit = backlog;
279 /* SCTP needs to look at tweak both the inbound backlog parameter AND
280 * the so_options (UDP model both connect's and gets inbound
281 * connections .. implicitly).
283 error = so_pru_listen(so, td);
286 /* Restore the params */
287 so->so_options = oldopt;
288 so->so_qlimit = oldqlimit;
298 sofree(struct socket *so)
300 struct socket *head = so->so_head;
302 if (so->so_pcb || (so->so_state & SS_NOFDREF) == 0)
305 if (so->so_state & SS_INCOMP) {
306 TAILQ_REMOVE(&head->so_incomp, so, so_list);
308 } else if (so->so_state & SS_COMP) {
310 * We must not decommission a socket that's
311 * on the accept(2) queue. If we do, then
312 * accept(2) may hang after select(2) indicated
313 * that the listening socket was ready.
317 panic("sofree: not queued");
319 so->so_state &= ~SS_INCOMP;
322 sbrelease(&so->so_snd, so);
328 * Close a socket on last file table reference removal.
329 * Initiate disconnect if connected.
330 * Free socket when disconnect complete.
333 soclose(struct socket *so, int fflag)
338 funsetown(so->so_sigio);
339 if (so->so_pcb == NULL)
341 if (so->so_state & SS_ISCONNECTED) {
342 if ((so->so_state & SS_ISDISCONNECTING) == 0) {
343 error = sodisconnect(so);
347 if (so->so_options & SO_LINGER) {
348 if ((so->so_state & SS_ISDISCONNECTING) &&
351 while (so->so_state & SS_ISCONNECTED) {
352 error = tsleep((caddr_t)&so->so_timeo,
353 PCATCH, "soclos", so->so_linger * hz);
363 error2 = so_pru_detach(so);
368 if (so->so_options & SO_ACCEPTCONN) {
369 struct socket *sp, *sonext;
371 sp = TAILQ_FIRST(&so->so_incomp);
372 for (; sp != NULL; sp = sonext) {
373 sonext = TAILQ_NEXT(sp, so_list);
376 for (sp = TAILQ_FIRST(&so->so_comp); sp != NULL; sp = sonext) {
377 sonext = TAILQ_NEXT(sp, so_list);
378 /* Dequeue from so_comp since sofree() won't do it */
379 TAILQ_REMOVE(&so->so_comp, sp, so_list);
381 sp->so_state &= ~SS_COMP;
386 if (so->so_state & SS_NOFDREF)
387 panic("soclose: NOFDREF");
388 so->so_state |= SS_NOFDREF;
395 * Must be called from a critical section.
398 soabort(struct socket *so)
402 error = so_pru_abort(so);
411 soaccept(struct socket *so, struct sockaddr **nam)
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);
425 soconnect(struct socket *so, struct sockaddr *nam, struct thread *td)
429 if (so->so_options & SO_ACCEPTCONN)
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.,
438 if (so->so_state & (SS_ISCONNECTED|SS_ISCONNECTING) &&
439 ((so->so_proto->pr_flags & PR_CONNREQUIRED) ||
440 (error = sodisconnect(so)))) {
444 * Prevent accumulated error from previous connection
448 error = so_pru_connect(so, nam, td);
455 soconnect2(struct socket *so1, struct socket *so2)
460 error = so_pru_connect2(so1, so2);
466 sodisconnect(struct socket *so)
471 if ((so->so_state & SS_ISCONNECTED) == 0) {
475 if (so->so_state & SS_ISDISCONNECTING) {
479 error = so_pru_disconnect(so);
485 #define SBLOCKWAIT(f) (((f) & MSG_DONTWAIT) ? M_NOWAIT : M_WAITOK)
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.
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.
504 sosend(struct socket *so, struct sockaddr *addr, struct uio *uio,
505 struct mbuf *top, struct mbuf *control, int flags,
510 long space, len, resid;
511 int clen = 0, error, dontroute, mlen;
512 int atomic = sosendallatonce(so) || top;
516 resid = uio->uio_resid;
518 resid = top->m_pkthdr.len;
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.
526 * Also check to make sure that MSG_EOR isn't used on SOCK_STREAM
527 * type sockets since that's an error.
529 if (resid < 0 || (so->so_type == SOCK_STREAM && (flags & MSG_EOR))) {
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++;
540 clen = control->m_len;
541 #define gotoerr(errcode) { error = errcode; crit_exit(); goto release; }
544 error = sblock(&so->so_snd, SBLOCKWAIT(flags));
549 if (so->so_state & SS_CANTSENDMORE)
552 error = so->so_error;
557 if ((so->so_state & SS_ISCONNECTED) == 0) {
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
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))
569 } else if (addr == 0)
570 gotoerr(so->so_proto->pr_flags & PR_CONNREQUIRED ?
571 ENOTCONN : EDESTADDRREQ);
573 space = sbspace(&so->so_snd);
576 if ((atomic && resid > so->so_snd.sb_hiwat) ||
577 clen > so->so_snd.sb_hiwat)
579 if (space < resid + clen && uio &&
580 (atomic || space < so->so_snd.sb_lowat || space < clen)) {
581 if (flags & (MSG_FNONBLOCKING|MSG_DONTWAIT))
582 gotoerr(EWOULDBLOCK);
583 sbunlock(&so->so_snd);
584 error = sbwait(&so->so_snd);
596 * Data is prepackaged in "top".
600 top->m_flags |= M_EOR;
602 m = m_getl(resid, MB_WAIT, MT_DATA,
603 top == NULL ? M_PKTHDR : 0, &mlen);
606 m->m_pkthdr.rcvif = (struct ifnet *)0;
608 len = min(min(mlen, resid), space);
609 if (resid < MINCLSIZE) {
611 * For datagram protocols, leave room
612 * for protocol headers in first mbuf.
614 if (atomic && top == 0 && len < mlen)
618 error = uiomove(mtod(m, caddr_t), (int)len, uio);
619 resid = uio->uio_resid;
622 top->m_pkthdr.len += len;
628 top->m_flags |= M_EOR;
631 } while (space > 0 && atomic);
633 so->so_options |= SO_DONTROUTE;
634 if (flags & MSG_OOB) {
635 pru_flags = PRUS_OOB;
636 } else if ((flags & MSG_EOF) &&
637 (so->so_proto->pr_flags & PR_IMPLOPCL) &&
640 * If the user set MSG_EOF, the protocol
641 * understands this flag and nothing left to
642 * send then use PRU_SEND_EOF instead of PRU_SEND.
644 pru_flags = PRUS_EOF;
645 } else if (resid > 0 && space > 0) {
646 /* If there is more to send, set PRUS_MORETOCOME */
647 pru_flags = PRUS_MORETOCOME;
653 * XXX all the SS_CANTSENDMORE checks previously
654 * done could be out of date. We could have recieved
655 * a reset packet in an interrupt or maybe we slept
656 * while doing page faults in uiomove() etc. We could
657 * probably recheck again inside the splnet() protection
658 * here, but there are probably other places that this
659 * also happens. We must rethink this.
661 error = so_pru_send(so, pru_flags, top, addr, control, td);
664 so->so_options &= ~SO_DONTROUTE;
671 } while (resid && space > 0);
675 sbunlock(&so->so_snd);
685 * A specialization of sosend() for UDP based on protocol-specific knowledge:
686 * so->so_proto->pr_flags has the PR_ATOMIC field set. This means that
687 * sosendallatonce() returns true,
688 * the "atomic" variable is true,
689 * and sosendudp() blocks until space is available for the entire send.
690 * so->so_proto->pr_flags does not have the PR_CONNREQUIRED or
691 * PR_IMPLOPCL flags set.
692 * UDP has no out-of-band data.
693 * UDP has no control data.
694 * UDP does not support MSG_EOR.
697 sosendudp(struct socket *so, struct sockaddr *addr, struct uio *uio,
698 struct mbuf *top, struct mbuf *control, int flags, struct thread *td)
701 boolean_t dontroute; /* temporary SO_DONTROUTE setting */
703 if (td->td_lwp != NULL)
704 td->td_lwp->lwp_ru.ru_msgsnd++;
708 KASSERT((uio && !top) || (top && !uio), ("bad arguments to sosendudp"));
709 resid = uio ? uio->uio_resid : top->m_pkthdr.len;
712 error = sblock(&so->so_snd, SBLOCKWAIT(flags));
717 if (so->so_state & SS_CANTSENDMORE)
720 error = so->so_error;
725 if (!(so->so_state & SS_ISCONNECTED) && addr == NULL)
726 gotoerr(EDESTADDRREQ);
727 if (resid > so->so_snd.sb_hiwat)
729 if (uio && sbspace(&so->so_snd) < resid) {
730 if (flags & (MSG_FNONBLOCKING|MSG_DONTWAIT))
731 gotoerr(EWOULDBLOCK);
732 sbunlock(&so->so_snd);
733 error = sbwait(&so->so_snd);
742 top = m_uiomove(uio);
747 dontroute = (flags & MSG_DONTROUTE) && !(so->so_options & SO_DONTROUTE);
749 so->so_options |= SO_DONTROUTE;
751 error = so_pru_send(so, 0, top, addr, NULL, td);
752 top = NULL; /* sent or freed in lower layer */
755 so->so_options &= ~SO_DONTROUTE;
758 sbunlock(&so->so_snd);
766 * Implement receive operations on a socket.
767 * We depend on the way that records are added to the sockbuf
768 * by sbappend*. In particular, each record (mbufs linked through m_next)
769 * must begin with an address if the protocol so specifies,
770 * followed by an optional mbuf or mbufs containing ancillary data,
771 * and then zero or more mbufs of data.
772 * In order to avoid blocking network interrupts for the entire time here,
773 * we exit the critical section while doing the actual copy to user space.
774 * Although the sockbuf is locked, new data may still be appended,
775 * and thus we must maintain consistency of the sockbuf during that time.
777 * The caller may receive the data as a single mbuf chain by supplying
778 * an mbuf **mp0 for use in returning the chain. The uio is then used
779 * only for the count in uio_resid.
782 soreceive(struct socket *so, struct sockaddr **psa, struct uio *uio,
783 struct mbuf **mp0, struct mbuf **controlp, int *flagsp)
785 struct mbuf *m, *n, **mp;
786 struct mbuf *free_chain = NULL;
787 int flags, len, error, offset;
788 struct protosw *pr = so->so_proto;
790 int orig_resid = uio->uio_resid;
798 flags = *flagsp &~ MSG_EOR;
801 if (flags & MSG_OOB) {
802 m = m_get(MB_WAIT, MT_DATA);
805 error = so_pru_rcvoob(so, m, flags & MSG_PEEK);
809 error = uiomove(mtod(m, caddr_t),
810 (int) min(uio->uio_resid, m->m_len), uio);
812 } while (uio->uio_resid && error == 0 && m);
820 if (so->so_state & SS_ISCONFIRMING && uio->uio_resid)
825 error = sblock(&so->so_rcv, SBLOCKWAIT(flags));
829 m = so->so_rcv.sb_mb;
831 * If we have less data than requested, block awaiting more
832 * (subject to any timeout) if:
833 * 1. the current count is less than the low water mark, or
834 * 2. MSG_WAITALL is set, and it is possible to do the entire
835 * receive operation at once if we block (resid <= hiwat).
836 * 3. MSG_DONTWAIT is not set
837 * If MSG_WAITALL is set but resid is larger than the receive buffer,
838 * we have to do the receive in sections, and thus risk returning
839 * a short count if a timeout or signal occurs after we start.
841 if (m == NULL || (((flags & MSG_DONTWAIT) == 0 &&
842 so->so_rcv.sb_cc < uio->uio_resid) &&
843 (so->so_rcv.sb_cc < so->so_rcv.sb_lowat ||
844 ((flags & MSG_WAITALL) && uio->uio_resid <= so->so_rcv.sb_hiwat)) &&
845 m->m_nextpkt == 0 && (pr->pr_flags & PR_ATOMIC) == 0)) {
846 KASSERT(m != NULL || !so->so_rcv.sb_cc, ("receive 1"));
850 error = so->so_error;
851 if ((flags & MSG_PEEK) == 0)
855 if (so->so_state & SS_CANTRCVMORE) {
861 for (; m; m = m->m_next) {
862 if (m->m_type == MT_OOBDATA || (m->m_flags & M_EOR)) {
863 m = so->so_rcv.sb_mb;
867 if ((so->so_state & (SS_ISCONNECTED|SS_ISCONNECTING)) == 0 &&
868 (pr->pr_flags & PR_CONNREQUIRED)) {
872 if (uio->uio_resid == 0)
874 if (flags & (MSG_FNONBLOCKING|MSG_DONTWAIT)) {
878 sbunlock(&so->so_rcv);
879 error = sbwait(&so->so_rcv);
886 if (uio->uio_td && uio->uio_td->td_proc)
887 uio->uio_td->td_lwp->lwp_ru.ru_msgrcv++;
890 * note: m should be == sb_mb here. Cache the next record while
891 * cleaning up. Note that calling m_free*() will break out critical
894 KKASSERT(m == so->so_rcv.sb_mb);
897 * Skip any address mbufs prepending the record.
899 if (pr->pr_flags & PR_ADDR) {
900 KASSERT(m->m_type == MT_SONAME, ("receive 1a"));
903 *psa = dup_sockaddr(mtod(m, struct sockaddr *));
904 if (flags & MSG_PEEK)
907 m = sbunlinkmbuf(&so->so_rcv, m, &free_chain);
911 * Skip any control mbufs prepending the record.
914 if (pr->pr_flags & PR_ADDR_OPT) {
916 * For SCTP we may be getting a
917 * whole message OR a partial delivery.
919 if (m && m->m_type == MT_SONAME) {
922 *psa = dup_sockaddr(mtod(m, struct sockaddr *));
923 if (flags & MSG_PEEK)
926 m = sbunlinkmbuf(&so->so_rcv, m, &free_chain);
930 while (m && m->m_type == MT_CONTROL && error == 0) {
931 if (flags & MSG_PEEK) {
933 *controlp = m_copy(m, 0, m->m_len);
934 m = m->m_next; /* XXX race */
937 n = sbunlinkmbuf(&so->so_rcv, m, NULL);
938 if (pr->pr_domain->dom_externalize &&
939 mtod(m, struct cmsghdr *)->cmsg_type ==
941 error = (*pr->pr_domain->dom_externalize)(m);
945 m = sbunlinkmbuf(&so->so_rcv, m, &free_chain);
948 if (controlp && *controlp) {
950 controlp = &(*controlp)->m_next;
959 if (type == MT_OOBDATA)
964 * Copy to the UIO or mbuf return chain (*mp).
968 while (m && uio->uio_resid > 0 && error == 0) {
969 if (m->m_type == MT_OOBDATA) {
970 if (type != MT_OOBDATA)
972 } else if (type == MT_OOBDATA)
975 KASSERT(m->m_type == MT_DATA || m->m_type == MT_HEADER,
977 so->so_state &= ~SS_RCVATMARK;
978 len = uio->uio_resid;
979 if (so->so_oobmark && len > so->so_oobmark - offset)
980 len = so->so_oobmark - offset;
981 if (len > m->m_len - moff)
982 len = m->m_len - moff;
984 * If mp is set, just pass back the mbufs.
985 * Otherwise copy them out via the uio, then free.
986 * Sockbuf must be consistent here (points to current mbuf,
987 * it points to next record) when we drop priority;
988 * we must note any additions to the sockbuf when we
989 * block interrupts again.
993 error = uiomove(mtod(m, caddr_t) + moff, (int)len, uio);
998 uio->uio_resid -= len;
1002 * Eat the entire mbuf or just a piece of it
1004 if (len == m->m_len - moff) {
1005 if (m->m_flags & M_EOR)
1008 if (m->m_flags & M_NOTIFICATION)
1009 flags |= MSG_NOTIFICATION;
1011 if (flags & MSG_PEEK) {
1016 n = sbunlinkmbuf(&so->so_rcv, m, NULL);
1021 m = sbunlinkmbuf(&so->so_rcv, m, &free_chain);
1025 if (flags & MSG_PEEK) {
1029 *mp = m_copym(m, 0, len, MB_WAIT);
1032 so->so_rcv.sb_cc -= len;
1035 if (so->so_oobmark) {
1036 if ((flags & MSG_PEEK) == 0) {
1037 so->so_oobmark -= len;
1038 if (so->so_oobmark == 0) {
1039 so->so_state |= SS_RCVATMARK;
1044 if (offset == so->so_oobmark)
1048 if (flags & MSG_EOR)
1051 * If the MSG_WAITALL flag is set (for non-atomic socket),
1052 * we must not quit until "uio->uio_resid == 0" or an error
1053 * termination. If a signal/timeout occurs, return
1054 * with a short count but without error.
1055 * Keep sockbuf locked against other readers.
1057 while (flags & MSG_WAITALL && m == NULL &&
1058 uio->uio_resid > 0 && !sosendallatonce(so) &&
1059 so->so_rcv.sb_mb == NULL) {
1060 if (so->so_error || so->so_state & SS_CANTRCVMORE)
1063 * The window might have closed to zero, make
1064 * sure we send an ack now that we've drained
1065 * the buffer or we might end up blocking until
1066 * the idle takes over (5 seconds).
1068 if (pr->pr_flags & PR_WANTRCVD && so->so_pcb)
1069 so_pru_rcvd(so, flags);
1070 error = sbwait(&so->so_rcv);
1072 sbunlock(&so->so_rcv);
1076 m = so->so_rcv.sb_mb;
1081 * If an atomic read was requested but unread data still remains
1082 * in the record, set MSG_TRUNC.
1084 if (m && pr->pr_flags & PR_ATOMIC)
1088 * Cleanup. If an atomic read was requested drop any unread data.
1090 if ((flags & MSG_PEEK) == 0) {
1091 if (m && (pr->pr_flags & PR_ATOMIC))
1092 sbdroprecord(&so->so_rcv);
1093 if ((pr->pr_flags & PR_WANTRCVD) && so->so_pcb)
1094 so_pru_rcvd(so, flags);
1097 if (orig_resid == uio->uio_resid && orig_resid &&
1098 (flags & MSG_EOR) == 0 && (so->so_state & SS_CANTRCVMORE) == 0) {
1099 sbunlock(&so->so_rcv);
1107 sbunlock(&so->so_rcv);
1111 m_freem(free_chain);
1116 soshutdown(struct socket *so, int how)
1118 if (!(how == SHUT_RD || how == SHUT_WR || how == SHUT_RDWR))
1124 return (so_pru_shutdown(so));
1129 sorflush(struct socket *so)
1131 struct sockbuf *sb = &so->so_rcv;
1132 struct protosw *pr = so->so_proto;
1135 sb->sb_flags |= SB_NOINTR;
1136 (void) sblock(sb, M_WAITOK);
1142 bzero((caddr_t)sb, sizeof (*sb));
1143 if (asb.sb_flags & SB_KNOTE) {
1144 sb->sb_sel.si_note = asb.sb_sel.si_note;
1145 sb->sb_flags = SB_KNOTE;
1149 if (pr->pr_flags & PR_RIGHTS && pr->pr_domain->dom_dispose)
1150 (*pr->pr_domain->dom_dispose)(asb.sb_mb);
1151 sbrelease(&asb, so);
1156 do_setopt_accept_filter(struct socket *so, struct sockopt *sopt)
1158 struct accept_filter_arg *afap = NULL;
1159 struct accept_filter *afp;
1160 struct so_accf *af = so->so_accf;
1163 /* do not set/remove accept filters on non listen sockets */
1164 if ((so->so_options & SO_ACCEPTCONN) == 0) {
1169 /* removing the filter */
1172 if (af->so_accept_filter != NULL &&
1173 af->so_accept_filter->accf_destroy != NULL) {
1174 af->so_accept_filter->accf_destroy(so);
1176 if (af->so_accept_filter_str != NULL) {
1177 FREE(af->so_accept_filter_str, M_ACCF);
1182 so->so_options &= ~SO_ACCEPTFILTER;
1185 /* adding a filter */
1186 /* must remove previous filter first */
1191 /* don't put large objects on the kernel stack */
1192 MALLOC(afap, struct accept_filter_arg *, sizeof(*afap), M_TEMP, M_WAITOK);
1193 error = sooptcopyin(sopt, afap, sizeof *afap, sizeof *afap);
1194 afap->af_name[sizeof(afap->af_name)-1] = '\0';
1195 afap->af_arg[sizeof(afap->af_arg)-1] = '\0';
1198 afp = accept_filt_get(afap->af_name);
1203 MALLOC(af, struct so_accf *, sizeof(*af), M_ACCF, M_WAITOK);
1204 bzero(af, sizeof(*af));
1205 if (afp->accf_create != NULL) {
1206 if (afap->af_name[0] != '\0') {
1207 int len = strlen(afap->af_name) + 1;
1209 MALLOC(af->so_accept_filter_str, char *, len, M_ACCF, M_WAITOK);
1210 strcpy(af->so_accept_filter_str, afap->af_name);
1212 af->so_accept_filter_arg = afp->accf_create(so, afap->af_arg);
1213 if (af->so_accept_filter_arg == NULL) {
1214 FREE(af->so_accept_filter_str, M_ACCF);
1221 af->so_accept_filter = afp;
1223 so->so_options |= SO_ACCEPTFILTER;
1232 * Perhaps this routine, and sooptcopyout(), below, ought to come in
1233 * an additional variant to handle the case where the option value needs
1234 * to be some kind of integer, but not a specific size.
1235 * In addition to their use here, these functions are also called by the
1236 * protocol-level pr_ctloutput() routines.
1239 sooptcopyin(struct sockopt *sopt, void *buf, size_t len, size_t minlen)
1244 * If the user gives us more than we wanted, we ignore it,
1245 * but if we don't get the minimum length the caller
1246 * wants, we return EINVAL. On success, sopt->sopt_valsize
1247 * is set to however much we actually retrieved.
1249 if ((valsize = sopt->sopt_valsize) < minlen)
1252 sopt->sopt_valsize = valsize = len;
1254 if (sopt->sopt_td != NULL)
1255 return (copyin(sopt->sopt_val, buf, valsize));
1257 bcopy(sopt->sopt_val, buf, valsize);
1262 sosetopt(struct socket *so, struct sockopt *sopt)
1270 sopt->sopt_dir = SOPT_SET;
1271 if (sopt->sopt_level != SOL_SOCKET) {
1272 if (so->so_proto && so->so_proto->pr_ctloutput) {
1273 return (so_pr_ctloutput(so, sopt));
1275 error = ENOPROTOOPT;
1277 switch (sopt->sopt_name) {
1279 case SO_ACCEPTFILTER:
1280 error = do_setopt_accept_filter(so, sopt);
1286 error = sooptcopyin(sopt, &l, sizeof l, sizeof l);
1290 so->so_linger = l.l_linger;
1292 so->so_options |= SO_LINGER;
1294 so->so_options &= ~SO_LINGER;
1300 case SO_USELOOPBACK:
1306 error = sooptcopyin(sopt, &optval, sizeof optval,
1311 so->so_options |= sopt->sopt_name;
1313 so->so_options &= ~sopt->sopt_name;
1320 error = sooptcopyin(sopt, &optval, sizeof optval,
1326 * Values < 1 make no sense for any of these
1327 * options, so disallow them.
1334 switch (sopt->sopt_name) {
1337 if (sbreserve(sopt->sopt_name == SO_SNDBUF ?
1338 &so->so_snd : &so->so_rcv, (u_long)optval,
1340 &curproc->p_rlimit[RLIMIT_SBSIZE]) == 0) {
1347 * Make sure the low-water is never greater than
1351 so->so_snd.sb_lowat =
1352 (optval > so->so_snd.sb_hiwat) ?
1353 so->so_snd.sb_hiwat : optval;
1356 so->so_rcv.sb_lowat =
1357 (optval > so->so_rcv.sb_hiwat) ?
1358 so->so_rcv.sb_hiwat : optval;
1365 error = sooptcopyin(sopt, &tv, sizeof tv,
1370 /* assert(hz > 0); */
1371 if (tv.tv_sec < 0 || tv.tv_sec > SHRT_MAX / hz ||
1372 tv.tv_usec < 0 || tv.tv_usec >= 1000000) {
1376 /* assert(tick > 0); */
1377 /* assert(ULONG_MAX - SHRT_MAX >= 1000000); */
1378 val = (u_long)(tv.tv_sec * hz) + tv.tv_usec / tick;
1379 if (val > SHRT_MAX) {
1383 if (val == 0 && tv.tv_usec != 0)
1386 switch (sopt->sopt_name) {
1388 so->so_snd.sb_timeo = val;
1391 so->so_rcv.sb_timeo = val;
1396 error = ENOPROTOOPT;
1399 if (error == 0 && so->so_proto && so->so_proto->pr_ctloutput) {
1400 (void) so_pr_ctloutput(so, sopt);
1407 /* Helper routine for getsockopt */
1409 sooptcopyout(struct sockopt *sopt, const void *buf, size_t len)
1417 * Documented get behavior is that we always return a value,
1418 * possibly truncated to fit in the user's buffer.
1419 * Traditional behavior is that we always tell the user
1420 * precisely how much we copied, rather than something useful
1421 * like the total amount we had available for her.
1422 * Note that this interface is not idempotent; the entire answer must
1423 * generated ahead of time.
1425 valsize = min(len, sopt->sopt_valsize);
1426 sopt->sopt_valsize = valsize;
1427 if (sopt->sopt_val != 0) {
1428 if (sopt->sopt_td != NULL)
1429 error = copyout(buf, sopt->sopt_val, valsize);
1431 bcopy(buf, sopt->sopt_val, valsize);
1437 sogetopt(struct socket *so, struct sockopt *sopt)
1443 struct accept_filter_arg *afap;
1447 sopt->sopt_dir = SOPT_GET;
1448 if (sopt->sopt_level != SOL_SOCKET) {
1449 if (so->so_proto && so->so_proto->pr_ctloutput) {
1450 return (so_pr_ctloutput(so, sopt));
1452 return (ENOPROTOOPT);
1454 switch (sopt->sopt_name) {
1456 case SO_ACCEPTFILTER:
1457 if ((so->so_options & SO_ACCEPTCONN) == 0)
1459 MALLOC(afap, struct accept_filter_arg *, sizeof(*afap),
1461 bzero(afap, sizeof(*afap));
1462 if ((so->so_options & SO_ACCEPTFILTER) != 0) {
1463 strcpy(afap->af_name, so->so_accf->so_accept_filter->accf_name);
1464 if (so->so_accf->so_accept_filter_str != NULL)
1465 strcpy(afap->af_arg, so->so_accf->so_accept_filter_str);
1467 error = sooptcopyout(sopt, afap, sizeof(*afap));
1473 l.l_onoff = so->so_options & SO_LINGER;
1474 l.l_linger = so->so_linger;
1475 error = sooptcopyout(sopt, &l, sizeof l);
1478 case SO_USELOOPBACK:
1487 optval = so->so_options & sopt->sopt_name;
1489 error = sooptcopyout(sopt, &optval, sizeof optval);
1493 optval = so->so_type;
1497 optval = so->so_error;
1502 optval = so->so_snd.sb_hiwat;
1506 optval = so->so_rcv.sb_hiwat;
1510 optval = so->so_snd.sb_lowat;
1514 optval = so->so_rcv.sb_lowat;
1519 optval = (sopt->sopt_name == SO_SNDTIMEO ?
1520 so->so_snd.sb_timeo : so->so_rcv.sb_timeo);
1522 tv.tv_sec = optval / hz;
1523 tv.tv_usec = (optval % hz) * tick;
1524 error = sooptcopyout(sopt, &tv, sizeof tv);
1528 error = ENOPROTOOPT;
1535 /* XXX; prepare mbuf for (__FreeBSD__ < 3) routines. */
1537 soopt_getm(struct sockopt *sopt, struct mbuf **mp)
1539 struct mbuf *m, *m_prev;
1540 int sopt_size = sopt->sopt_valsize, msize;
1542 m = m_getl(sopt_size, sopt->sopt_td ? MB_WAIT : MB_DONTWAIT, MT_DATA,
1546 m->m_len = min(msize, sopt_size);
1547 sopt_size -= m->m_len;
1551 while (sopt_size > 0) {
1552 m = m_getl(sopt_size, sopt->sopt_td ? MB_WAIT : MB_DONTWAIT,
1553 MT_DATA, 0, &msize);
1558 m->m_len = min(msize, sopt_size);
1559 sopt_size -= m->m_len;
1566 /* XXX; copyin sopt data into mbuf chain for (__FreeBSD__ < 3) routines. */
1568 soopt_mcopyin(struct sockopt *sopt, struct mbuf *m)
1570 struct mbuf *m0 = m;
1572 if (sopt->sopt_val == NULL)
1574 while (m != NULL && sopt->sopt_valsize >= m->m_len) {
1575 if (sopt->sopt_td != NULL) {
1578 error = copyin(sopt->sopt_val, mtod(m, char *),
1585 bcopy(sopt->sopt_val, mtod(m, char *), m->m_len);
1586 sopt->sopt_valsize -= m->m_len;
1587 sopt->sopt_val = (caddr_t)sopt->sopt_val + m->m_len;
1590 if (m != NULL) /* should be allocated enoughly at ip6_sooptmcopyin() */
1591 panic("ip6_sooptmcopyin");
1595 /* XXX; copyout mbuf chain data into soopt for (__FreeBSD__ < 3) routines. */
1597 soopt_mcopyout(struct sockopt *sopt, struct mbuf *m)
1599 struct mbuf *m0 = m;
1602 if (sopt->sopt_val == NULL)
1604 while (m != NULL && sopt->sopt_valsize >= m->m_len) {
1605 if (sopt->sopt_td != NULL) {
1608 error = copyout(mtod(m, char *), sopt->sopt_val,
1615 bcopy(mtod(m, char *), sopt->sopt_val, m->m_len);
1616 sopt->sopt_valsize -= m->m_len;
1617 sopt->sopt_val = (caddr_t)sopt->sopt_val + m->m_len;
1618 valsize += m->m_len;
1622 /* enough soopt buffer should be given from user-land */
1626 sopt->sopt_valsize = valsize;
1631 sohasoutofband(struct socket *so)
1633 if (so->so_sigio != NULL)
1634 pgsigio(so->so_sigio, SIGURG, 0);
1635 selwakeup(&so->so_rcv.sb_sel);
1639 sopoll(struct socket *so, int events, struct ucred *cred, struct thread *td)
1645 if (events & (POLLIN | POLLRDNORM))
1647 revents |= events & (POLLIN | POLLRDNORM);
1649 if (events & POLLINIGNEOF)
1650 if (so->so_rcv.sb_cc >= so->so_rcv.sb_lowat ||
1651 !TAILQ_EMPTY(&so->so_comp) || so->so_error)
1652 revents |= POLLINIGNEOF;
1654 if (events & (POLLOUT | POLLWRNORM))
1655 if (sowriteable(so))
1656 revents |= events & (POLLOUT | POLLWRNORM);
1658 if (events & (POLLPRI | POLLRDBAND))
1659 if (so->so_oobmark || (so->so_state & SS_RCVATMARK))
1660 revents |= events & (POLLPRI | POLLRDBAND);
1664 (POLLIN | POLLINIGNEOF | POLLPRI | POLLRDNORM |
1666 selrecord(td, &so->so_rcv.sb_sel);
1667 so->so_rcv.sb_flags |= SB_SEL;
1670 if (events & (POLLOUT | POLLWRNORM)) {
1671 selrecord(td, &so->so_snd.sb_sel);
1672 so->so_snd.sb_flags |= SB_SEL;
1681 sokqfilter(struct file *fp, struct knote *kn)
1683 struct socket *so = (struct socket *)kn->kn_fp->f_data;
1686 switch (kn->kn_filter) {
1688 if (so->so_options & SO_ACCEPTCONN)
1689 kn->kn_fop = &solisten_filtops;
1691 kn->kn_fop = &soread_filtops;
1695 kn->kn_fop = &sowrite_filtops;
1703 SLIST_INSERT_HEAD(&sb->sb_sel.si_note, kn, kn_selnext);
1704 sb->sb_flags |= SB_KNOTE;
1710 filt_sordetach(struct knote *kn)
1712 struct socket *so = (struct socket *)kn->kn_fp->f_data;
1715 SLIST_REMOVE(&so->so_rcv.sb_sel.si_note, kn, knote, kn_selnext);
1716 if (SLIST_EMPTY(&so->so_rcv.sb_sel.si_note))
1717 so->so_rcv.sb_flags &= ~SB_KNOTE;
1723 filt_soread(struct knote *kn, long hint)
1725 struct socket *so = (struct socket *)kn->kn_fp->f_data;
1727 kn->kn_data = so->so_rcv.sb_cc;
1728 if (so->so_state & SS_CANTRCVMORE) {
1729 kn->kn_flags |= EV_EOF;
1730 kn->kn_fflags = so->so_error;
1733 if (so->so_error) /* temporary udp error */
1735 if (kn->kn_sfflags & NOTE_LOWAT)
1736 return (kn->kn_data >= kn->kn_sdata);
1737 return (kn->kn_data >= so->so_rcv.sb_lowat);
1741 filt_sowdetach(struct knote *kn)
1743 struct socket *so = (struct socket *)kn->kn_fp->f_data;
1746 SLIST_REMOVE(&so->so_snd.sb_sel.si_note, kn, knote, kn_selnext);
1747 if (SLIST_EMPTY(&so->so_snd.sb_sel.si_note))
1748 so->so_snd.sb_flags &= ~SB_KNOTE;
1754 filt_sowrite(struct knote *kn, long hint)
1756 struct socket *so = (struct socket *)kn->kn_fp->f_data;
1758 kn->kn_data = sbspace(&so->so_snd);
1759 if (so->so_state & SS_CANTSENDMORE) {
1760 kn->kn_flags |= EV_EOF;
1761 kn->kn_fflags = so->so_error;
1764 if (so->so_error) /* temporary udp error */
1766 if (((so->so_state & SS_ISCONNECTED) == 0) &&
1767 (so->so_proto->pr_flags & PR_CONNREQUIRED))
1769 if (kn->kn_sfflags & NOTE_LOWAT)
1770 return (kn->kn_data >= kn->kn_sdata);
1771 return (kn->kn_data >= so->so_snd.sb_lowat);
1776 filt_solisten(struct knote *kn, long hint)
1778 struct socket *so = (struct socket *)kn->kn_fp->f_data;
1780 kn->kn_data = so->so_qlen;
1781 return (! TAILQ_EMPTY(&so->so_comp));