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) 1982, 1986, 1988, 1990, 1993
36 * The Regents of the University of California. All rights reserved.
38 * Redistribution and use in source and binary forms, with or without
39 * modification, are permitted provided that the following conditions
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.
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
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 $
74 #include <sys/param.h>
75 #include <sys/systm.h>
76 #include <sys/fcntl.h>
77 #include <sys/malloc.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>
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>
95 #include <vm/vm_zone.h>
98 #include <sys/thread2.h>
99 #include <sys/socketvar2.h>
101 #include <machine/limits.h>
104 static int do_setopt_accept_filter(struct socket *so, struct sockopt *sopt);
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);
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 static struct filterops soexcept_filtops =
120 { 1, NULL, filt_sordetach, filt_soread };
122 MALLOC_DEFINE(M_SOCKET, "socket", "socket struct");
123 MALLOC_DEFINE(M_SONAME, "soname", "socket name");
124 MALLOC_DEFINE(M_PCB, "pcb", "protocol control block");
127 static int somaxconn = SOMAXCONN;
128 SYSCTL_INT(_kern_ipc, KIPC_SOMAXCONN, somaxconn, CTLFLAG_RW,
129 &somaxconn, 0, "Maximum pending socket connection queue size");
132 * Socket operation routines.
133 * These routines are called by the routines in
134 * sys_socket.c or from a system process, and
135 * implement the semantics of socket operations by
136 * switching out to the protocol specific routines.
140 * Get a socket structure, and initialize it.
141 * Note that it would probably be better to allocate socket
142 * and PCB at the same time, but I'm not convinced that all
143 * the protocols can be easily modified to do this.
151 waitmask = waitok ? M_WAITOK : M_NOWAIT;
152 so = kmalloc(sizeof(struct socket), M_SOCKET, M_ZERO|waitmask);
154 /* XXX race condition for reentrant kernel */
155 TAILQ_INIT(&so->so_aiojobq);
156 TAILQ_INIT(&so->so_rcv.ssb_sel.si_mlist);
157 TAILQ_INIT(&so->so_snd.ssb_sel.si_mlist);
163 socreate(int dom, struct socket **aso, int type,
164 int proto, struct thread *td)
166 struct proc *p = td->td_proc;
169 struct pru_attach_info ai;
173 prp = pffindproto(dom, proto, type);
175 prp = pffindtype(dom, type);
177 if (prp == 0 || prp->pr_usrreqs->pru_attach == 0)
178 return (EPROTONOSUPPORT);
180 if (p->p_ucred->cr_prison && jail_socket_unixiproute_only &&
181 prp->pr_domain->dom_family != PF_LOCAL &&
182 prp->pr_domain->dom_family != PF_INET &&
183 prp->pr_domain->dom_family != PF_INET6 &&
184 prp->pr_domain->dom_family != PF_ROUTE) {
185 return (EPROTONOSUPPORT);
188 if (prp->pr_type != type)
190 so = soalloc(p != 0);
195 * Set a default port for protocol processing. No action will occur
196 * on the socket on this port until an inpcb is attached to it and
197 * is able to match incoming packets, or until the socket becomes
198 * available to userland.
200 so->so_port = cpu0_soport(so, NULL, NULL);
202 TAILQ_INIT(&so->so_incomp);
203 TAILQ_INIT(&so->so_comp);
205 so->so_cred = crhold(p->p_ucred);
207 ai.sb_rlimit = &p->p_rlimit[RLIMIT_SBSIZE];
208 ai.p_ucred = p->p_ucred;
209 ai.fd_rdir = p->p_fd->fd_rdir;
212 * Auto-sizing of socket buffers is managed by the protocols and
213 * the appropriate flags must be set in the pru_attach function.
215 error = so_pru_attach(so, proto, &ai);
217 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.ssb_hiwat)
241 (void)chgsbsize(so->so_cred->cr_uidinfo,
242 &so->so_rcv.ssb_hiwat, 0, RLIM_INFINITY);
243 if (so->so_snd.ssb_hiwat)
244 (void)chgsbsize(so->so_cred->cr_uidinfo,
245 &so->so_snd.ssb_hiwat, 0, RLIM_INFINITY);
247 /* remove accept filter if present */
248 if (so->so_accf != NULL)
249 do_setopt_accept_filter(so, NULL);
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 * Destroy a disconnected socket. This routine is a NOP if entities
299 * still have a reference on the socket:
301 * so_pcb - The protocol stack still has a reference
302 * SS_NOFDREF - There is no longer a file pointer reference
303 * SS_ABORTING - An abort netmsg is in-flight
306 sofree(struct socket *so)
308 struct socket *head = so->so_head;
310 if (so->so_pcb || (so->so_state & SS_NOFDREF) == 0)
312 if (so->so_state & SS_ABORTING)
315 if (so->so_state & SS_INCOMP) {
316 TAILQ_REMOVE(&head->so_incomp, so, so_list);
318 } else if (so->so_state & SS_COMP) {
320 * We must not decommission a socket that's
321 * on the accept(2) queue. If we do, then
322 * accept(2) may hang after select(2) indicated
323 * that the listening socket was ready.
327 panic("sofree: not queued");
329 so->so_state &= ~SS_INCOMP;
332 ssb_release(&so->so_snd, so);
338 * Close a socket on last file table reference removal.
339 * Initiate disconnect if connected.
340 * Free socket when disconnect complete.
343 soclose(struct socket *so, int fflag)
348 funsetown(so->so_sigio);
349 if (so->so_pcb == NULL)
351 if (so->so_state & SS_ISCONNECTED) {
352 if ((so->so_state & SS_ISDISCONNECTING) == 0) {
353 error = sodisconnect(so);
357 if (so->so_options & SO_LINGER) {
358 if ((so->so_state & SS_ISDISCONNECTING) &&
361 while (so->so_state & SS_ISCONNECTED) {
362 error = tsleep((caddr_t)&so->so_timeo,
363 PCATCH, "soclos", so->so_linger * hz);
373 error2 = so_pru_detach(so);
378 if (so->so_options & SO_ACCEPTCONN) {
381 while ((sp = TAILQ_FIRST(&so->so_incomp)) != NULL) {
382 TAILQ_REMOVE(&so->so_incomp, sp, so_list);
383 sp->so_state &= ~SS_INCOMP;
388 while ((sp = TAILQ_FIRST(&so->so_comp)) != NULL) {
389 TAILQ_REMOVE(&so->so_comp, sp, so_list);
390 sp->so_state &= ~SS_COMP;
396 if (so->so_state & SS_NOFDREF)
397 panic("soclose: NOFDREF");
398 so->so_state |= SS_NOFDREF;
405 * Abort and destroy a socket. Only one abort can be in progress
406 * at any given moment.
409 soabort(struct socket *so)
411 if ((so->so_state & SS_ABORTING) == 0) {
412 so->so_state |= SS_ABORTING;
418 soaborta(struct socket *so)
420 if ((so->so_state & SS_ABORTING) == 0) {
421 so->so_state |= SS_ABORTING;
427 soabort_oncpu(struct socket *so)
429 if ((so->so_state & SS_ABORTING) == 0) {
430 so->so_state |= SS_ABORTING;
431 so_pru_abort_oncpu(so);
436 soaccept(struct socket *so, struct sockaddr **nam)
441 if ((so->so_state & SS_NOFDREF) == 0)
442 panic("soaccept: !NOFDREF");
443 so->so_state &= ~SS_NOFDREF;
444 error = so_pru_accept(so, nam);
450 soconnect(struct socket *so, struct sockaddr *nam, struct thread *td)
454 if (so->so_options & SO_ACCEPTCONN)
458 * If protocol is connection-based, can only connect once.
459 * Otherwise, if connected, try to disconnect first.
460 * This allows user to disconnect by connecting to, e.g.,
463 if (so->so_state & (SS_ISCONNECTED|SS_ISCONNECTING) &&
464 ((so->so_proto->pr_flags & PR_CONNREQUIRED) ||
465 (error = sodisconnect(so)))) {
469 * Prevent accumulated error from previous connection
473 error = so_pru_connect(so, nam, td);
480 soconnect2(struct socket *so1, struct socket *so2)
485 error = so_pru_connect2(so1, so2);
491 sodisconnect(struct socket *so)
496 if ((so->so_state & SS_ISCONNECTED) == 0) {
500 if (so->so_state & SS_ISDISCONNECTING) {
504 error = so_pru_disconnect(so);
510 #define SBLOCKWAIT(f) (((f) & MSG_DONTWAIT) ? M_NOWAIT : M_WAITOK)
513 * If send must go all at once and message is larger than
514 * send buffering, then hard error.
515 * Lock against other senders.
516 * If must go all at once and not enough room now, then
517 * inform user that this would block and do nothing.
518 * Otherwise, if nonblocking, send as much as possible.
519 * The data to be sent is described by "uio" if nonzero,
520 * otherwise by the mbuf chain "top" (which must be null
521 * if uio is not). Data provided in mbuf chain must be small
522 * enough to send all at once.
524 * Returns nonzero on error, timeout or signal; callers
525 * must check for short counts if EINTR/ERESTART are returned.
526 * Data and control buffers are freed on return.
529 sosend(struct socket *so, struct sockaddr *addr, struct uio *uio,
530 struct mbuf *top, struct mbuf *control, int flags,
537 int clen = 0, error, dontroute, mlen;
538 int atomic = sosendallatonce(so) || top;
542 resid = uio->uio_resid;
544 resid = (size_t)top->m_pkthdr.len;
547 * WARNING! resid is unsigned, space and len are signed. space
548 * can wind up negative if the sockbuf is overcommitted.
550 * Also check to make sure that MSG_EOR isn't used on SOCK_STREAM
551 * type sockets since that's an error.
553 if (so->so_type == SOCK_STREAM && (flags & MSG_EOR)) {
559 (flags & MSG_DONTROUTE) && (so->so_options & SO_DONTROUTE) == 0 &&
560 (so->so_proto->pr_flags & PR_ATOMIC);
561 if (td->td_lwp != NULL)
562 td->td_lwp->lwp_ru.ru_msgsnd++;
564 clen = control->m_len;
565 #define gotoerr(errcode) { error = errcode; crit_exit(); goto release; }
568 error = ssb_lock(&so->so_snd, SBLOCKWAIT(flags));
574 if (so->so_state & SS_CANTSENDMORE)
577 error = so->so_error;
582 if ((so->so_state & SS_ISCONNECTED) == 0) {
584 * `sendto' and `sendmsg' is allowed on a connection-
585 * based socket if it supports implied connect.
586 * Return ENOTCONN if not connected and no address is
589 if ((so->so_proto->pr_flags & PR_CONNREQUIRED) &&
590 (so->so_proto->pr_flags & PR_IMPLOPCL) == 0) {
591 if ((so->so_state & SS_ISCONFIRMING) == 0 &&
592 !(resid == 0 && clen != 0))
594 } else if (addr == 0)
595 gotoerr(so->so_proto->pr_flags & PR_CONNREQUIRED ?
596 ENOTCONN : EDESTADDRREQ);
598 if ((atomic && resid > so->so_snd.ssb_hiwat) ||
599 clen > so->so_snd.ssb_hiwat) {
602 space = ssb_space(&so->so_snd);
605 if ((space < 0 || (size_t)space < resid + clen) && uio &&
606 (atomic || space < so->so_snd.ssb_lowat || space < clen)) {
607 if (flags & (MSG_FNONBLOCKING|MSG_DONTWAIT))
608 gotoerr(EWOULDBLOCK);
609 ssb_unlock(&so->so_snd);
610 error = ssb_wait(&so->so_snd);
622 * Data is prepackaged in "top".
626 top->m_flags |= M_EOR;
630 m = m_getl((int)resid, MB_WAIT, MT_DATA,
631 top == NULL ? M_PKTHDR : 0, &mlen);
634 m->m_pkthdr.rcvif = NULL;
636 len = imin((int)szmin(mlen, resid), space);
637 if (resid < MINCLSIZE) {
639 * For datagram protocols, leave room
640 * for protocol headers in first mbuf.
642 if (atomic && top == 0 && len < mlen)
646 error = uiomove(mtod(m, caddr_t), (size_t)len, uio);
647 resid = uio->uio_resid;
650 top->m_pkthdr.len += len;
656 top->m_flags |= M_EOR;
659 } while (space > 0 && atomic);
661 so->so_options |= SO_DONTROUTE;
662 if (flags & MSG_OOB) {
663 pru_flags = PRUS_OOB;
664 } else if ((flags & MSG_EOF) &&
665 (so->so_proto->pr_flags & PR_IMPLOPCL) &&
668 * If the user set MSG_EOF, the protocol
669 * understands this flag and nothing left to
670 * send then use PRU_SEND_EOF instead of PRU_SEND.
672 pru_flags = PRUS_EOF;
673 } else if (resid > 0 && space > 0) {
674 /* If there is more to send, set PRUS_MORETOCOME */
675 pru_flags = PRUS_MORETOCOME;
681 * XXX all the SS_CANTSENDMORE checks previously
682 * done could be out of date. We could have recieved
683 * a reset packet in an interrupt or maybe we slept
684 * while doing page faults in uiomove() etc. We could
685 * probably recheck again inside the splnet() protection
686 * here, but there are probably other places that this
687 * also happens. We must rethink this.
689 error = so_pru_send(so, pru_flags, top, addr, control, td);
692 so->so_options &= ~SO_DONTROUTE;
699 } while (resid && space > 0);
703 ssb_unlock(&so->so_snd);
713 * A specialization of sosend() for UDP based on protocol-specific knowledge:
714 * so->so_proto->pr_flags has the PR_ATOMIC field set. This means that
715 * sosendallatonce() returns true,
716 * the "atomic" variable is true,
717 * and sosendudp() blocks until space is available for the entire send.
718 * so->so_proto->pr_flags does not have the PR_CONNREQUIRED or
719 * PR_IMPLOPCL flags set.
720 * UDP has no out-of-band data.
721 * UDP has no control data.
722 * UDP does not support MSG_EOR.
725 sosendudp(struct socket *so, struct sockaddr *addr, struct uio *uio,
726 struct mbuf *top, struct mbuf *control, int flags, struct thread *td)
728 boolean_t dontroute; /* temporary SO_DONTROUTE setting */
733 if (td->td_lwp != NULL)
734 td->td_lwp->lwp_ru.ru_msgsnd++;
738 KASSERT((uio && !top) || (top && !uio), ("bad arguments to sosendudp"));
739 resid = uio ? uio->uio_resid : (size_t)top->m_pkthdr.len;
742 error = ssb_lock(&so->so_snd, SBLOCKWAIT(flags));
747 if (so->so_state & SS_CANTSENDMORE)
750 error = so->so_error;
755 if (!(so->so_state & SS_ISCONNECTED) && addr == NULL)
756 gotoerr(EDESTADDRREQ);
757 if (resid > so->so_snd.ssb_hiwat)
759 space = ssb_space(&so->so_snd);
760 if (uio && (space < 0 || (size_t)space < resid)) {
761 if (flags & (MSG_FNONBLOCKING|MSG_DONTWAIT))
762 gotoerr(EWOULDBLOCK);
763 ssb_unlock(&so->so_snd);
764 error = ssb_wait(&so->so_snd);
773 top = m_uiomove(uio);
778 dontroute = (flags & MSG_DONTROUTE) && !(so->so_options & SO_DONTROUTE);
780 so->so_options |= SO_DONTROUTE;
782 error = so_pru_send(so, 0, top, addr, NULL, td);
783 top = NULL; /* sent or freed in lower layer */
786 so->so_options &= ~SO_DONTROUTE;
789 ssb_unlock(&so->so_snd);
797 * Implement receive operations on a socket.
798 * We depend on the way that records are added to the signalsockbuf
799 * by sbappend*. In particular, each record (mbufs linked through m_next)
800 * must begin with an address if the protocol so specifies,
801 * followed by an optional mbuf or mbufs containing ancillary data,
802 * and then zero or more mbufs of data.
803 * In order to avoid blocking network interrupts for the entire time here,
804 * we exit the critical section while doing the actual copy to user space.
805 * Although the signalsockbuf is locked, new data may still be appended,
806 * and thus we must maintain consistency of the signalsockbuf during that time.
808 * The caller may receive the data as a single mbuf chain by supplying
809 * an mbuf **mp0 for use in returning the chain. The uio is then used
810 * only for the count in uio_resid.
813 soreceive(struct socket *so, struct sockaddr **psa, struct uio *uio,
814 struct sockbuf *sio, struct mbuf **controlp, int *flagsp)
817 struct mbuf *free_chain = NULL;
818 int flags, len, error, offset;
819 struct protosw *pr = so->so_proto;
821 size_t resid, orig_resid;
824 resid = uio->uio_resid;
826 resid = (size_t)(sio->sb_climit - sio->sb_cc);
834 flags = *flagsp &~ MSG_EOR;
837 if (flags & MSG_OOB) {
838 m = m_get(MB_WAIT, MT_DATA);
841 error = so_pru_rcvoob(so, m, flags & MSG_PEEK);
847 KKASSERT(resid >= (size_t)m->m_len);
848 resid -= (size_t)m->m_len;
849 } while (resid > 0 && m);
852 uio->uio_resid = resid;
853 error = uiomove(mtod(m, caddr_t),
854 (int)szmin(resid, m->m_len),
856 resid = uio->uio_resid;
858 } while (uio->uio_resid && error == 0 && m);
865 if ((so->so_state & SS_ISCONFIRMING) && resid)
870 error = ssb_lock(&so->so_rcv, SBLOCKWAIT(flags));
874 m = so->so_rcv.ssb_mb;
876 * If we have less data than requested, block awaiting more
877 * (subject to any timeout) if:
878 * 1. the current count is less than the low water mark, or
879 * 2. MSG_WAITALL is set, and it is possible to do the entire
880 * receive operation at once if we block (resid <= hiwat).
881 * 3. MSG_DONTWAIT is not set
882 * If MSG_WAITALL is set but resid is larger than the receive buffer,
883 * we have to do the receive in sections, and thus risk returning
884 * a short count if a timeout or signal occurs after we start.
886 if (m == NULL || (((flags & MSG_DONTWAIT) == 0 &&
887 (size_t)so->so_rcv.ssb_cc < resid) &&
888 (so->so_rcv.ssb_cc < so->so_rcv.ssb_lowat ||
889 ((flags & MSG_WAITALL) && resid <= (size_t)so->so_rcv.ssb_hiwat)) &&
890 m->m_nextpkt == 0 && (pr->pr_flags & PR_ATOMIC) == 0)) {
891 KASSERT(m != NULL || !so->so_rcv.ssb_cc, ("receive 1"));
895 error = so->so_error;
896 if ((flags & MSG_PEEK) == 0)
900 if (so->so_state & SS_CANTRCVMORE) {
906 for (; m; m = m->m_next) {
907 if (m->m_type == MT_OOBDATA || (m->m_flags & M_EOR)) {
908 m = so->so_rcv.ssb_mb;
912 if ((so->so_state & (SS_ISCONNECTED|SS_ISCONNECTING)) == 0 &&
913 (pr->pr_flags & PR_CONNREQUIRED)) {
919 if (flags & (MSG_FNONBLOCKING|MSG_DONTWAIT)) {
923 ssb_unlock(&so->so_rcv);
924 error = ssb_wait(&so->so_rcv);
931 if (uio && uio->uio_td && uio->uio_td->td_proc)
932 uio->uio_td->td_lwp->lwp_ru.ru_msgrcv++;
935 * note: m should be == sb_mb here. Cache the next record while
936 * cleaning up. Note that calling m_free*() will break out critical
939 KKASSERT(m == so->so_rcv.ssb_mb);
942 * Skip any address mbufs prepending the record.
944 if (pr->pr_flags & PR_ADDR) {
945 KASSERT(m->m_type == MT_SONAME, ("receive 1a"));
948 *psa = dup_sockaddr(mtod(m, struct sockaddr *));
949 if (flags & MSG_PEEK)
952 m = sbunlinkmbuf(&so->so_rcv.sb, m, &free_chain);
956 * Skip any control mbufs prepending the record.
959 if (pr->pr_flags & PR_ADDR_OPT) {
961 * For SCTP we may be getting a
962 * whole message OR a partial delivery.
964 if (m && m->m_type == MT_SONAME) {
967 *psa = dup_sockaddr(mtod(m, struct sockaddr *));
968 if (flags & MSG_PEEK)
971 m = sbunlinkmbuf(&so->so_rcv.sb, m, &free_chain);
975 while (m && m->m_type == MT_CONTROL && error == 0) {
976 if (flags & MSG_PEEK) {
978 *controlp = m_copy(m, 0, m->m_len);
979 m = m->m_next; /* XXX race */
982 n = sbunlinkmbuf(&so->so_rcv.sb, m, NULL);
983 if (pr->pr_domain->dom_externalize &&
984 mtod(m, struct cmsghdr *)->cmsg_type ==
986 error = (*pr->pr_domain->dom_externalize)(m);
990 m = sbunlinkmbuf(&so->so_rcv.sb, m, &free_chain);
993 if (controlp && *controlp) {
995 controlp = &(*controlp)->m_next;
1004 if (type == MT_OOBDATA)
1009 * Copy to the UIO or mbuf return chain (*mp).
1013 while (m && resid > 0 && error == 0) {
1014 if (m->m_type == MT_OOBDATA) {
1015 if (type != MT_OOBDATA)
1017 } else if (type == MT_OOBDATA)
1020 KASSERT(m->m_type == MT_DATA || m->m_type == MT_HEADER,
1022 so->so_state &= ~SS_RCVATMARK;
1023 len = (resid > INT_MAX) ? INT_MAX : resid;
1024 if (so->so_oobmark && len > so->so_oobmark - offset)
1025 len = so->so_oobmark - offset;
1026 if (len > m->m_len - moff)
1027 len = m->m_len - moff;
1030 * Copy out to the UIO or pass the mbufs back to the SIO.
1031 * The SIO is dealt with when we eat the mbuf, but deal
1032 * with the resid here either way.
1036 uio->uio_resid = resid;
1037 error = uiomove(mtod(m, caddr_t) + moff, len, uio);
1038 resid = uio->uio_resid;
1043 resid -= (size_t)len;
1047 * Eat the entire mbuf or just a piece of it
1049 if (len == m->m_len - moff) {
1050 if (m->m_flags & M_EOR)
1053 if (m->m_flags & M_NOTIFICATION)
1054 flags |= MSG_NOTIFICATION;
1056 if (flags & MSG_PEEK) {
1061 n = sbunlinkmbuf(&so->so_rcv.sb, m, NULL);
1065 m = sbunlinkmbuf(&so->so_rcv.sb, m, &free_chain);
1069 if (flags & MSG_PEEK) {
1073 n = m_copym(m, 0, len, MB_WAIT);
1079 so->so_rcv.ssb_cc -= len;
1082 if (so->so_oobmark) {
1083 if ((flags & MSG_PEEK) == 0) {
1084 so->so_oobmark -= len;
1085 if (so->so_oobmark == 0) {
1086 so->so_state |= SS_RCVATMARK;
1091 if (offset == so->so_oobmark)
1095 if (flags & MSG_EOR)
1098 * If the MSG_WAITALL flag is set (for non-atomic socket),
1099 * we must not quit until resid == 0 or an error
1100 * termination. If a signal/timeout occurs, return
1101 * with a short count but without error.
1102 * Keep signalsockbuf locked against other readers.
1104 while ((flags & MSG_WAITALL) && m == NULL &&
1105 resid > 0 && !sosendallatonce(so) &&
1106 so->so_rcv.ssb_mb == NULL) {
1107 if (so->so_error || so->so_state & SS_CANTRCVMORE)
1110 * The window might have closed to zero, make
1111 * sure we send an ack now that we've drained
1112 * the buffer or we might end up blocking until
1113 * the idle takes over (5 seconds).
1115 if (pr->pr_flags & PR_WANTRCVD && so->so_pcb)
1116 so_pru_rcvd(so, flags);
1117 error = ssb_wait(&so->so_rcv);
1119 ssb_unlock(&so->so_rcv);
1123 m = so->so_rcv.ssb_mb;
1128 * If an atomic read was requested but unread data still remains
1129 * in the record, set MSG_TRUNC.
1131 if (m && pr->pr_flags & PR_ATOMIC)
1135 * Cleanup. If an atomic read was requested drop any unread data.
1137 if ((flags & MSG_PEEK) == 0) {
1138 if (m && (pr->pr_flags & PR_ATOMIC))
1139 sbdroprecord(&so->so_rcv.sb);
1140 if ((pr->pr_flags & PR_WANTRCVD) && so->so_pcb)
1141 so_pru_rcvd(so, flags);
1144 if (orig_resid == resid && orig_resid &&
1145 (flags & MSG_EOR) == 0 && (so->so_state & SS_CANTRCVMORE) == 0) {
1146 ssb_unlock(&so->so_rcv);
1154 ssb_unlock(&so->so_rcv);
1158 m_freem(free_chain);
1163 soshutdown(struct socket *so, int how)
1165 if (!(how == SHUT_RD || how == SHUT_WR || how == SHUT_RDWR))
1171 return (so_pru_shutdown(so));
1176 sorflush(struct socket *so)
1178 struct signalsockbuf *ssb = &so->so_rcv;
1179 struct protosw *pr = so->so_proto;
1180 struct signalsockbuf asb;
1182 ssb->ssb_flags |= SSB_NOINTR;
1183 (void) ssb_lock(ssb, M_WAITOK);
1189 bzero((caddr_t)ssb, sizeof (*ssb));
1190 if (asb.ssb_flags & SSB_KNOTE) {
1191 ssb->ssb_sel.si_note = asb.ssb_sel.si_note;
1192 ssb->ssb_flags = SSB_KNOTE;
1196 if (pr->pr_flags & PR_RIGHTS && pr->pr_domain->dom_dispose)
1197 (*pr->pr_domain->dom_dispose)(asb.ssb_mb);
1198 ssb_release(&asb, so);
1203 do_setopt_accept_filter(struct socket *so, struct sockopt *sopt)
1205 struct accept_filter_arg *afap = NULL;
1206 struct accept_filter *afp;
1207 struct so_accf *af = so->so_accf;
1210 /* do not set/remove accept filters on non listen sockets */
1211 if ((so->so_options & SO_ACCEPTCONN) == 0) {
1216 /* removing the filter */
1219 if (af->so_accept_filter != NULL &&
1220 af->so_accept_filter->accf_destroy != NULL) {
1221 af->so_accept_filter->accf_destroy(so);
1223 if (af->so_accept_filter_str != NULL) {
1224 FREE(af->so_accept_filter_str, M_ACCF);
1229 so->so_options &= ~SO_ACCEPTFILTER;
1232 /* adding a filter */
1233 /* must remove previous filter first */
1238 /* don't put large objects on the kernel stack */
1239 MALLOC(afap, struct accept_filter_arg *, sizeof(*afap), M_TEMP, M_WAITOK);
1240 error = sooptcopyin(sopt, afap, sizeof *afap, sizeof *afap);
1241 afap->af_name[sizeof(afap->af_name)-1] = '\0';
1242 afap->af_arg[sizeof(afap->af_arg)-1] = '\0';
1245 afp = accept_filt_get(afap->af_name);
1250 MALLOC(af, struct so_accf *, sizeof(*af), M_ACCF, M_WAITOK | M_ZERO);
1251 if (afp->accf_create != NULL) {
1252 if (afap->af_name[0] != '\0') {
1253 int len = strlen(afap->af_name) + 1;
1255 MALLOC(af->so_accept_filter_str, char *, len, M_ACCF, M_WAITOK);
1256 strcpy(af->so_accept_filter_str, afap->af_name);
1258 af->so_accept_filter_arg = afp->accf_create(so, afap->af_arg);
1259 if (af->so_accept_filter_arg == NULL) {
1260 FREE(af->so_accept_filter_str, M_ACCF);
1267 af->so_accept_filter = afp;
1269 so->so_options |= SO_ACCEPTFILTER;
1278 * Perhaps this routine, and sooptcopyout(), below, ought to come in
1279 * an additional variant to handle the case where the option value needs
1280 * to be some kind of integer, but not a specific size.
1281 * In addition to their use here, these functions are also called by the
1282 * protocol-level pr_ctloutput() routines.
1285 sooptcopyin(struct sockopt *sopt, void *buf, size_t len, size_t minlen)
1287 return soopt_to_kbuf(sopt, buf, len, minlen);
1291 soopt_to_kbuf(struct sockopt *sopt, void *buf, size_t len, size_t minlen)
1295 KKASSERT(!sopt->sopt_val || kva_p(sopt->sopt_val));
1296 KKASSERT(kva_p(buf));
1299 * If the user gives us more than we wanted, we ignore it,
1300 * but if we don't get the minimum length the caller
1301 * wants, we return EINVAL. On success, sopt->sopt_valsize
1302 * is set to however much we actually retrieved.
1304 if ((valsize = sopt->sopt_valsize) < minlen)
1307 sopt->sopt_valsize = valsize = len;
1309 bcopy(sopt->sopt_val, buf, valsize);
1315 sosetopt(struct socket *so, struct sockopt *sopt)
1323 sopt->sopt_dir = SOPT_SET;
1324 if (sopt->sopt_level != SOL_SOCKET) {
1325 if (so->so_proto && so->so_proto->pr_ctloutput) {
1326 return (so_pru_ctloutput(so, sopt));
1328 error = ENOPROTOOPT;
1330 switch (sopt->sopt_name) {
1332 case SO_ACCEPTFILTER:
1333 error = do_setopt_accept_filter(so, sopt);
1339 error = sooptcopyin(sopt, &l, sizeof l, sizeof l);
1343 so->so_linger = l.l_linger;
1345 so->so_options |= SO_LINGER;
1347 so->so_options &= ~SO_LINGER;
1353 case SO_USELOOPBACK:
1359 error = sooptcopyin(sopt, &optval, sizeof optval,
1364 so->so_options |= sopt->sopt_name;
1366 so->so_options &= ~sopt->sopt_name;
1373 error = sooptcopyin(sopt, &optval, sizeof optval,
1379 * Values < 1 make no sense for any of these
1380 * options, so disallow them.
1387 switch (sopt->sopt_name) {
1390 if (ssb_reserve(sopt->sopt_name == SO_SNDBUF ?
1391 &so->so_snd : &so->so_rcv, (u_long)optval,
1393 &curproc->p_rlimit[RLIMIT_SBSIZE]) == 0) {
1397 (sopt->sopt_name == SO_SNDBUF ? &so->so_snd :
1398 &so->so_rcv)->ssb_flags &= ~SSB_AUTOSIZE;
1402 * Make sure the low-water is never greater than
1406 so->so_snd.ssb_lowat =
1407 (optval > so->so_snd.ssb_hiwat) ?
1408 so->so_snd.ssb_hiwat : optval;
1409 so->so_snd.ssb_flags &= ~SSB_AUTOLOWAT;
1412 so->so_rcv.ssb_lowat =
1413 (optval > so->so_rcv.ssb_hiwat) ?
1414 so->so_rcv.ssb_hiwat : optval;
1415 so->so_rcv.ssb_flags &= ~SSB_AUTOLOWAT;
1422 error = sooptcopyin(sopt, &tv, sizeof tv,
1427 /* assert(hz > 0); */
1428 if (tv.tv_sec < 0 || tv.tv_sec > SHRT_MAX / hz ||
1429 tv.tv_usec < 0 || tv.tv_usec >= 1000000) {
1433 /* assert(tick > 0); */
1434 /* assert(ULONG_MAX - SHRT_MAX >= 1000000); */
1435 val = (u_long)(tv.tv_sec * hz) + tv.tv_usec / ustick;
1436 if (val > SHRT_MAX) {
1440 if (val == 0 && tv.tv_usec != 0)
1443 switch (sopt->sopt_name) {
1445 so->so_snd.ssb_timeo = val;
1448 so->so_rcv.ssb_timeo = val;
1453 error = ENOPROTOOPT;
1456 if (error == 0 && so->so_proto && so->so_proto->pr_ctloutput) {
1457 (void) so_pru_ctloutput(so, sopt);
1464 /* Helper routine for getsockopt */
1466 sooptcopyout(struct sockopt *sopt, const void *buf, size_t len)
1468 soopt_from_kbuf(sopt, buf, len);
1473 soopt_from_kbuf(struct sockopt *sopt, const void *buf, size_t len)
1478 sopt->sopt_valsize = 0;
1482 KKASSERT(!sopt->sopt_val || kva_p(sopt->sopt_val));
1483 KKASSERT(kva_p(buf));
1486 * Documented get behavior is that we always return a value,
1487 * possibly truncated to fit in the user's buffer.
1488 * Traditional behavior is that we always tell the user
1489 * precisely how much we copied, rather than something useful
1490 * like the total amount we had available for her.
1491 * Note that this interface is not idempotent; the entire answer must
1492 * generated ahead of time.
1494 valsize = szmin(len, sopt->sopt_valsize);
1495 sopt->sopt_valsize = valsize;
1496 if (sopt->sopt_val != 0) {
1497 bcopy(buf, sopt->sopt_val, valsize);
1502 sogetopt(struct socket *so, struct sockopt *sopt)
1508 struct accept_filter_arg *afap;
1512 sopt->sopt_dir = SOPT_GET;
1513 if (sopt->sopt_level != SOL_SOCKET) {
1514 if (so->so_proto && so->so_proto->pr_ctloutput) {
1515 return (so_pru_ctloutput(so, sopt));
1517 return (ENOPROTOOPT);
1519 switch (sopt->sopt_name) {
1521 case SO_ACCEPTFILTER:
1522 if ((so->so_options & SO_ACCEPTCONN) == 0)
1524 MALLOC(afap, struct accept_filter_arg *, sizeof(*afap),
1525 M_TEMP, M_WAITOK | M_ZERO);
1526 if ((so->so_options & SO_ACCEPTFILTER) != 0) {
1527 strcpy(afap->af_name, so->so_accf->so_accept_filter->accf_name);
1528 if (so->so_accf->so_accept_filter_str != NULL)
1529 strcpy(afap->af_arg, so->so_accf->so_accept_filter_str);
1531 error = sooptcopyout(sopt, afap, sizeof(*afap));
1537 l.l_onoff = so->so_options & SO_LINGER;
1538 l.l_linger = so->so_linger;
1539 error = sooptcopyout(sopt, &l, sizeof l);
1542 case SO_USELOOPBACK:
1551 optval = so->so_options & sopt->sopt_name;
1553 error = sooptcopyout(sopt, &optval, sizeof optval);
1557 optval = so->so_type;
1561 optval = so->so_error;
1566 optval = so->so_snd.ssb_hiwat;
1570 optval = so->so_rcv.ssb_hiwat;
1574 optval = so->so_snd.ssb_lowat;
1578 optval = so->so_rcv.ssb_lowat;
1583 optval = (sopt->sopt_name == SO_SNDTIMEO ?
1584 so->so_snd.ssb_timeo : so->so_rcv.ssb_timeo);
1586 tv.tv_sec = optval / hz;
1587 tv.tv_usec = (optval % hz) * ustick;
1588 error = sooptcopyout(sopt, &tv, sizeof tv);
1592 error = ENOPROTOOPT;
1599 /* XXX; prepare mbuf for (__FreeBSD__ < 3) routines. */
1601 soopt_getm(struct sockopt *sopt, struct mbuf **mp)
1603 struct mbuf *m, *m_prev;
1604 int sopt_size = sopt->sopt_valsize, msize;
1606 m = m_getl(sopt_size, sopt->sopt_td ? MB_WAIT : MB_DONTWAIT, MT_DATA,
1610 m->m_len = min(msize, sopt_size);
1611 sopt_size -= m->m_len;
1615 while (sopt_size > 0) {
1616 m = m_getl(sopt_size, sopt->sopt_td ? MB_WAIT : MB_DONTWAIT,
1617 MT_DATA, 0, &msize);
1622 m->m_len = min(msize, sopt_size);
1623 sopt_size -= m->m_len;
1630 /* XXX; copyin sopt data into mbuf chain for (__FreeBSD__ < 3) routines. */
1632 soopt_mcopyin(struct sockopt *sopt, struct mbuf *m)
1634 soopt_to_mbuf(sopt, m);
1639 soopt_to_mbuf(struct sockopt *sopt, struct mbuf *m)
1644 KKASSERT(!sopt->sopt_val || kva_p(sopt->sopt_val));
1646 if (sopt->sopt_val == NULL)
1648 val = sopt->sopt_val;
1649 valsize = sopt->sopt_valsize;
1650 while (m != NULL && valsize >= m->m_len) {
1651 bcopy(val, mtod(m, char *), m->m_len);
1652 valsize -= m->m_len;
1653 val = (caddr_t)val + m->m_len;
1656 if (m != NULL) /* should be allocated enoughly at ip6_sooptmcopyin() */
1657 panic("ip6_sooptmcopyin");
1660 /* XXX; copyout mbuf chain data into soopt for (__FreeBSD__ < 3) routines. */
1662 soopt_mcopyout(struct sockopt *sopt, struct mbuf *m)
1664 return soopt_from_mbuf(sopt, m);
1668 soopt_from_mbuf(struct sockopt *sopt, struct mbuf *m)
1670 struct mbuf *m0 = m;
1675 KKASSERT(!sopt->sopt_val || kva_p(sopt->sopt_val));
1677 if (sopt->sopt_val == NULL)
1679 val = sopt->sopt_val;
1680 maxsize = sopt->sopt_valsize;
1681 while (m != NULL && maxsize >= m->m_len) {
1682 bcopy(mtod(m, char *), val, m->m_len);
1683 maxsize -= m->m_len;
1684 val = (caddr_t)val + m->m_len;
1685 valsize += m->m_len;
1689 /* enough soopt buffer should be given from user-land */
1693 sopt->sopt_valsize = valsize;
1698 sohasoutofband(struct socket *so)
1700 if (so->so_sigio != NULL)
1701 pgsigio(so->so_sigio, SIGURG, 0);
1702 selwakeup(&so->so_rcv.ssb_sel);
1703 KNOTE(&so->so_rcv.ssb_sel.si_note, NOTE_OOB);
1707 sopoll(struct socket *so, int events, struct ucred *cred, struct thread *td)
1713 if (events & (POLLIN | POLLRDNORM))
1715 revents |= events & (POLLIN | POLLRDNORM);
1717 if (events & POLLINIGNEOF)
1718 if (so->so_rcv.ssb_cc >= so->so_rcv.ssb_lowat ||
1719 !TAILQ_EMPTY(&so->so_comp) || so->so_error)
1720 revents |= POLLINIGNEOF;
1722 if (events & (POLLOUT | POLLWRNORM))
1723 if (sowriteable(so))
1724 revents |= events & (POLLOUT | POLLWRNORM);
1726 if (events & (POLLPRI | POLLRDBAND))
1727 if (so->so_oobmark || (so->so_state & SS_RCVATMARK))
1728 revents |= events & (POLLPRI | POLLRDBAND);
1732 (POLLIN | POLLINIGNEOF | POLLPRI | POLLRDNORM |
1734 selrecord(td, &so->so_rcv.ssb_sel);
1735 so->so_rcv.ssb_flags |= SSB_SEL;
1738 if (events & (POLLOUT | POLLWRNORM)) {
1739 selrecord(td, &so->so_snd.ssb_sel);
1740 so->so_snd.ssb_flags |= SSB_SEL;
1749 sokqfilter(struct file *fp, struct knote *kn)
1751 struct socket *so = (struct socket *)kn->kn_fp->f_data;
1752 struct signalsockbuf *ssb;
1754 switch (kn->kn_filter) {
1756 if (so->so_options & SO_ACCEPTCONN)
1757 kn->kn_fop = &solisten_filtops;
1759 kn->kn_fop = &soread_filtops;
1763 kn->kn_fop = &sowrite_filtops;
1767 kn->kn_fop = &soexcept_filtops;
1775 SLIST_INSERT_HEAD(&ssb->ssb_sel.si_note, kn, kn_selnext);
1776 ssb->ssb_flags |= SSB_KNOTE;
1782 filt_sordetach(struct knote *kn)
1784 struct socket *so = (struct socket *)kn->kn_fp->f_data;
1787 SLIST_REMOVE(&so->so_rcv.ssb_sel.si_note, kn, knote, kn_selnext);
1788 if (SLIST_EMPTY(&so->so_rcv.ssb_sel.si_note))
1789 so->so_rcv.ssb_flags &= ~SSB_KNOTE;
1795 filt_soread(struct knote *kn, long hint)
1797 struct socket *so = (struct socket *)kn->kn_fp->f_data;
1799 if (kn->kn_sfflags & NOTE_OOB) {
1800 if ((so->so_oobmark || (so->so_state & SS_RCVATMARK))) {
1801 kn->kn_fflags |= NOTE_OOB;
1806 kn->kn_data = so->so_rcv.ssb_cc;
1807 if (so->so_state & SS_CANTRCVMORE) {
1808 kn->kn_flags |= EV_EOF;
1809 kn->kn_fflags = so->so_error;
1812 if (so->so_error) /* temporary udp error */
1814 if (kn->kn_sfflags & NOTE_LOWAT)
1815 return (kn->kn_data >= kn->kn_sdata);
1816 return ((kn->kn_data >= so->so_rcv.ssb_lowat) ||
1817 !TAILQ_EMPTY(&so->so_comp));
1821 filt_sowdetach(struct knote *kn)
1823 struct socket *so = (struct socket *)kn->kn_fp->f_data;
1826 SLIST_REMOVE(&so->so_snd.ssb_sel.si_note, kn, knote, kn_selnext);
1827 if (SLIST_EMPTY(&so->so_snd.ssb_sel.si_note))
1828 so->so_snd.ssb_flags &= ~SSB_KNOTE;
1834 filt_sowrite(struct knote *kn, long hint)
1836 struct socket *so = (struct socket *)kn->kn_fp->f_data;
1838 kn->kn_data = ssb_space(&so->so_snd);
1839 if (so->so_state & SS_CANTSENDMORE) {
1840 kn->kn_flags |= EV_EOF;
1841 kn->kn_fflags = so->so_error;
1844 if (so->so_error) /* temporary udp error */
1846 if (((so->so_state & SS_ISCONNECTED) == 0) &&
1847 (so->so_proto->pr_flags & PR_CONNREQUIRED))
1849 if (kn->kn_sfflags & NOTE_LOWAT)
1850 return (kn->kn_data >= kn->kn_sdata);
1851 return (kn->kn_data >= so->so_snd.ssb_lowat);
1856 filt_solisten(struct knote *kn, long hint)
1858 struct socket *so = (struct socket *)kn->kn_fp->f_data;
1860 kn->kn_data = so->so_qlen;
1861 return (! TAILQ_EMPTY(&so->so_comp));