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>
85 #include <sys/protosw.h>
86 #include <sys/socket.h>
87 #include <sys/socketvar.h>
88 #include <sys/socketops.h>
89 #include <sys/resourcevar.h>
90 #include <sys/signalvar.h>
91 #include <sys/sysctl.h>
94 #include <vm/vm_zone.h>
97 #include <sys/thread2.h>
98 #include <sys/socketvar2.h>
100 #include <machine/limits.h>
103 static int do_setopt_accept_filter(struct socket *so, struct sockopt *sopt);
106 static void filt_sordetach(struct knote *kn);
107 static int filt_soread(struct knote *kn, long hint);
108 static void filt_sowdetach(struct knote *kn);
109 static int filt_sowrite(struct knote *kn, long hint);
110 static int filt_solisten(struct knote *kn, long hint);
112 static struct filterops solisten_filtops =
113 { FILTEROP_ISFD, NULL, filt_sordetach, filt_solisten };
114 static struct filterops soread_filtops =
115 { FILTEROP_ISFD, NULL, filt_sordetach, filt_soread };
116 static struct filterops sowrite_filtops =
117 { FILTEROP_ISFD, NULL, filt_sowdetach, filt_sowrite };
118 static struct filterops soexcept_filtops =
119 { FILTEROP_ISFD, NULL, filt_sordetach, filt_soread };
121 MALLOC_DEFINE(M_SOCKET, "socket", "socket struct");
122 MALLOC_DEFINE(M_SONAME, "soname", "socket name");
123 MALLOC_DEFINE(M_PCB, "pcb", "protocol control block");
126 static int somaxconn = SOMAXCONN;
127 SYSCTL_INT(_kern_ipc, KIPC_SOMAXCONN, somaxconn, CTLFLAG_RW,
128 &somaxconn, 0, "Maximum pending socket connection queue size");
131 * Socket operation routines.
132 * These routines are called by the routines in
133 * sys_socket.c or from a system process, and
134 * implement the semantics of socket operations by
135 * switching out to the protocol specific routines.
139 * Get a socket structure, and initialize it.
140 * Note that it would probably be better to allocate socket
141 * and PCB at the same time, but I'm not convinced that all
142 * the protocols can be easily modified to do this.
150 waitmask = waitok ? M_WAITOK : M_NOWAIT;
151 so = kmalloc(sizeof(struct socket), M_SOCKET, M_ZERO|waitmask);
153 /* XXX race condition for reentrant kernel */
154 TAILQ_INIT(&so->so_aiojobq);
155 TAILQ_INIT(&so->so_rcv.ssb_kq.ki_mlist);
156 TAILQ_INIT(&so->so_snd.ssb_kq.ki_mlist);
162 socreate(int dom, struct socket **aso, int type,
163 int proto, struct thread *td)
165 struct proc *p = td->td_proc;
168 struct pru_attach_info ai;
172 prp = pffindproto(dom, proto, type);
174 prp = pffindtype(dom, type);
176 if (prp == 0 || prp->pr_usrreqs->pru_attach == 0)
177 return (EPROTONOSUPPORT);
179 if (p->p_ucred->cr_prison && jail_socket_unixiproute_only &&
180 prp->pr_domain->dom_family != PF_LOCAL &&
181 prp->pr_domain->dom_family != PF_INET &&
182 prp->pr_domain->dom_family != PF_INET6 &&
183 prp->pr_domain->dom_family != PF_ROUTE) {
184 return (EPROTONOSUPPORT);
187 if (prp->pr_type != type)
189 so = soalloc(p != 0);
194 * Set a default port for protocol processing. No action will occur
195 * on the socket on this port until an inpcb is attached to it and
196 * is able to match incoming packets, or until the socket becomes
197 * available to userland.
199 so->so_port = cpu0_soport(so, NULL, NULL);
201 TAILQ_INIT(&so->so_incomp);
202 TAILQ_INIT(&so->so_comp);
204 so->so_cred = crhold(p->p_ucred);
206 ai.sb_rlimit = &p->p_rlimit[RLIMIT_SBSIZE];
207 ai.p_ucred = p->p_ucred;
208 ai.fd_rdir = p->p_fd->fd_rdir;
211 * Auto-sizing of socket buffers is managed by the protocols and
212 * the appropriate flags must be set in the pru_attach function.
214 error = so_pru_attach(so, proto, &ai);
216 so->so_state |= SS_NOFDREF;
226 sobind(struct socket *so, struct sockaddr *nam, struct thread *td)
231 error = so_pru_bind(so, nam, td);
237 sodealloc(struct socket *so)
239 if (so->so_rcv.ssb_hiwat)
240 (void)chgsbsize(so->so_cred->cr_uidinfo,
241 &so->so_rcv.ssb_hiwat, 0, RLIM_INFINITY);
242 if (so->so_snd.ssb_hiwat)
243 (void)chgsbsize(so->so_cred->cr_uidinfo,
244 &so->so_snd.ssb_hiwat, 0, RLIM_INFINITY);
246 /* remove accept filter if present */
247 if (so->so_accf != NULL)
248 do_setopt_accept_filter(so, NULL);
255 solisten(struct socket *so, int backlog, struct thread *td)
259 short oldopt, oldqlimit;
263 if (so->so_state & (SS_ISCONNECTED | SS_ISCONNECTING)) {
269 oldopt = so->so_options;
270 oldqlimit = so->so_qlimit;
273 if (TAILQ_EMPTY(&so->so_comp))
274 so->so_options |= SO_ACCEPTCONN;
275 if (backlog < 0 || backlog > somaxconn)
277 so->so_qlimit = backlog;
278 /* SCTP needs to look at tweak both the inbound backlog parameter AND
279 * the so_options (UDP model both connect's and gets inbound
280 * connections .. implicitly).
282 error = so_pru_listen(so, td);
285 /* Restore the params */
286 so->so_options = oldopt;
287 so->so_qlimit = oldqlimit;
297 * Destroy a disconnected socket. This routine is a NOP if entities
298 * still have a reference on the socket:
300 * so_pcb - The protocol stack still has a reference
301 * SS_NOFDREF - There is no longer a file pointer reference
302 * SS_ABORTING - An abort netmsg is in-flight
305 sofree(struct socket *so)
307 struct socket *head = so->so_head;
309 if (so->so_pcb || (so->so_state & SS_NOFDREF) == 0)
311 if (so->so_state & SS_ABORTING)
314 if (so->so_state & SS_INCOMP) {
315 TAILQ_REMOVE(&head->so_incomp, so, so_list);
317 } else if (so->so_state & SS_COMP) {
319 * We must not decommission a socket that's
320 * on the accept(2) queue. If we do, then
321 * accept(2) may hang after select(2) indicated
322 * that the listening socket was ready.
326 panic("sofree: not queued");
328 so->so_state &= ~SS_INCOMP;
331 ssb_release(&so->so_snd, so);
337 * Close a socket on last file table reference removal.
338 * Initiate disconnect if connected.
339 * Free socket when disconnect complete.
342 soclose(struct socket *so, int fflag)
347 funsetown(so->so_sigio);
348 if (so->so_pcb == NULL)
350 if (so->so_state & SS_ISCONNECTED) {
351 if ((so->so_state & SS_ISDISCONNECTING) == 0) {
352 error = sodisconnect(so);
356 if (so->so_options & SO_LINGER) {
357 if ((so->so_state & SS_ISDISCONNECTING) &&
360 while (so->so_state & SS_ISCONNECTED) {
361 error = tsleep((caddr_t)&so->so_timeo,
362 PCATCH, "soclos", so->so_linger * hz);
372 error2 = so_pru_detach(so);
377 if (so->so_options & SO_ACCEPTCONN) {
380 while ((sp = TAILQ_FIRST(&so->so_incomp)) != NULL) {
381 TAILQ_REMOVE(&so->so_incomp, sp, so_list);
382 sp->so_state &= ~SS_INCOMP;
387 while ((sp = TAILQ_FIRST(&so->so_comp)) != NULL) {
388 TAILQ_REMOVE(&so->so_comp, sp, so_list);
389 sp->so_state &= ~SS_COMP;
395 if (so->so_state & SS_NOFDREF)
396 panic("soclose: NOFDREF");
397 so->so_state |= SS_NOFDREF;
404 * Abort and destroy a socket. Only one abort can be in progress
405 * at any given moment.
408 soabort(struct socket *so)
410 if ((so->so_state & SS_ABORTING) == 0) {
411 so->so_state |= SS_ABORTING;
417 soaborta(struct socket *so)
419 if ((so->so_state & SS_ABORTING) == 0) {
420 so->so_state |= SS_ABORTING;
426 soabort_oncpu(struct socket *so)
428 if ((so->so_state & SS_ABORTING) == 0) {
429 so->so_state |= SS_ABORTING;
430 so_pru_abort_oncpu(so);
435 soaccept(struct socket *so, struct sockaddr **nam)
440 if ((so->so_state & SS_NOFDREF) == 0)
441 panic("soaccept: !NOFDREF");
442 so->so_state &= ~SS_NOFDREF;
443 error = so_pru_accept(so, nam);
449 soconnect(struct socket *so, struct sockaddr *nam, struct thread *td)
453 if (so->so_options & SO_ACCEPTCONN)
457 * If protocol is connection-based, can only connect once.
458 * Otherwise, if connected, try to disconnect first.
459 * This allows user to disconnect by connecting to, e.g.,
462 if (so->so_state & (SS_ISCONNECTED|SS_ISCONNECTING) &&
463 ((so->so_proto->pr_flags & PR_CONNREQUIRED) ||
464 (error = sodisconnect(so)))) {
468 * Prevent accumulated error from previous connection
472 error = so_pru_connect(so, nam, td);
479 soconnect2(struct socket *so1, struct socket *so2)
484 error = so_pru_connect2(so1, so2);
490 sodisconnect(struct socket *so)
495 if ((so->so_state & SS_ISCONNECTED) == 0) {
499 if (so->so_state & SS_ISDISCONNECTING) {
503 error = so_pru_disconnect(so);
509 #define SBLOCKWAIT(f) (((f) & MSG_DONTWAIT) ? M_NOWAIT : M_WAITOK)
512 * If send must go all at once and message is larger than
513 * send buffering, then hard error.
514 * Lock against other senders.
515 * If must go all at once and not enough room now, then
516 * inform user that this would block and do nothing.
517 * Otherwise, if nonblocking, send as much as possible.
518 * The data to be sent is described by "uio" if nonzero,
519 * otherwise by the mbuf chain "top" (which must be null
520 * if uio is not). Data provided in mbuf chain must be small
521 * enough to send all at once.
523 * Returns nonzero on error, timeout or signal; callers
524 * must check for short counts if EINTR/ERESTART are returned.
525 * Data and control buffers are freed on return.
528 sosend(struct socket *so, struct sockaddr *addr, struct uio *uio,
529 struct mbuf *top, struct mbuf *control, int flags,
536 int clen = 0, error, dontroute, mlen;
537 int atomic = sosendallatonce(so) || top;
541 resid = uio->uio_resid;
543 resid = (size_t)top->m_pkthdr.len;
546 * WARNING! resid is unsigned, space and len are signed. space
547 * can wind up negative if the sockbuf is overcommitted.
549 * Also check to make sure that MSG_EOR isn't used on SOCK_STREAM
550 * type sockets since that's an error.
552 if (so->so_type == SOCK_STREAM && (flags & MSG_EOR)) {
558 (flags & MSG_DONTROUTE) && (so->so_options & SO_DONTROUTE) == 0 &&
559 (so->so_proto->pr_flags & PR_ATOMIC);
560 if (td->td_lwp != NULL)
561 td->td_lwp->lwp_ru.ru_msgsnd++;
563 clen = control->m_len;
564 #define gotoerr(errcode) { error = errcode; crit_exit(); goto release; }
567 error = ssb_lock(&so->so_snd, SBLOCKWAIT(flags));
573 if (so->so_state & SS_CANTSENDMORE)
576 error = so->so_error;
581 if ((so->so_state & SS_ISCONNECTED) == 0) {
583 * `sendto' and `sendmsg' is allowed on a connection-
584 * based socket if it supports implied connect.
585 * Return ENOTCONN if not connected and no address is
588 if ((so->so_proto->pr_flags & PR_CONNREQUIRED) &&
589 (so->so_proto->pr_flags & PR_IMPLOPCL) == 0) {
590 if ((so->so_state & SS_ISCONFIRMING) == 0 &&
591 !(resid == 0 && clen != 0))
593 } else if (addr == 0)
594 gotoerr(so->so_proto->pr_flags & PR_CONNREQUIRED ?
595 ENOTCONN : EDESTADDRREQ);
597 if ((atomic && resid > so->so_snd.ssb_hiwat) ||
598 clen > so->so_snd.ssb_hiwat) {
601 space = ssb_space(&so->so_snd);
604 if ((space < 0 || (size_t)space < resid + clen) && uio &&
605 (atomic || space < so->so_snd.ssb_lowat || space < clen)) {
606 if (flags & (MSG_FNONBLOCKING|MSG_DONTWAIT))
607 gotoerr(EWOULDBLOCK);
608 ssb_unlock(&so->so_snd);
609 error = ssb_wait(&so->so_snd);
621 * Data is prepackaged in "top".
625 top->m_flags |= M_EOR;
629 m = m_getl((int)resid, MB_WAIT, MT_DATA,
630 top == NULL ? M_PKTHDR : 0, &mlen);
633 m->m_pkthdr.rcvif = NULL;
635 len = imin((int)szmin(mlen, resid), space);
636 if (resid < MINCLSIZE) {
638 * For datagram protocols, leave room
639 * for protocol headers in first mbuf.
641 if (atomic && top == 0 && len < mlen)
645 error = uiomove(mtod(m, caddr_t), (size_t)len, uio);
646 resid = uio->uio_resid;
649 top->m_pkthdr.len += len;
655 top->m_flags |= M_EOR;
658 } while (space > 0 && atomic);
660 so->so_options |= SO_DONTROUTE;
661 if (flags & MSG_OOB) {
662 pru_flags = PRUS_OOB;
663 } else if ((flags & MSG_EOF) &&
664 (so->so_proto->pr_flags & PR_IMPLOPCL) &&
667 * If the user set MSG_EOF, the protocol
668 * understands this flag and nothing left to
669 * send then use PRU_SEND_EOF instead of PRU_SEND.
671 pru_flags = PRUS_EOF;
672 } else if (resid > 0 && space > 0) {
673 /* If there is more to send, set PRUS_MORETOCOME */
674 pru_flags = PRUS_MORETOCOME;
680 * XXX all the SS_CANTSENDMORE checks previously
681 * done could be out of date. We could have recieved
682 * a reset packet in an interrupt or maybe we slept
683 * while doing page faults in uiomove() etc. We could
684 * probably recheck again inside the splnet() protection
685 * here, but there are probably other places that this
686 * also happens. We must rethink this.
688 error = so_pru_send(so, pru_flags, top, addr, control, td);
691 so->so_options &= ~SO_DONTROUTE;
698 } while (resid && space > 0);
702 ssb_unlock(&so->so_snd);
712 * A specialization of sosend() for UDP based on protocol-specific knowledge:
713 * so->so_proto->pr_flags has the PR_ATOMIC field set. This means that
714 * sosendallatonce() returns true,
715 * the "atomic" variable is true,
716 * and sosendudp() blocks until space is available for the entire send.
717 * so->so_proto->pr_flags does not have the PR_CONNREQUIRED or
718 * PR_IMPLOPCL flags set.
719 * UDP has no out-of-band data.
720 * UDP has no control data.
721 * UDP does not support MSG_EOR.
724 sosendudp(struct socket *so, struct sockaddr *addr, struct uio *uio,
725 struct mbuf *top, struct mbuf *control, int flags, struct thread *td)
727 boolean_t dontroute; /* temporary SO_DONTROUTE setting */
732 if (td->td_lwp != NULL)
733 td->td_lwp->lwp_ru.ru_msgsnd++;
737 KASSERT((uio && !top) || (top && !uio), ("bad arguments to sosendudp"));
738 resid = uio ? uio->uio_resid : (size_t)top->m_pkthdr.len;
741 error = ssb_lock(&so->so_snd, SBLOCKWAIT(flags));
746 if (so->so_state & SS_CANTSENDMORE)
749 error = so->so_error;
754 if (!(so->so_state & SS_ISCONNECTED) && addr == NULL)
755 gotoerr(EDESTADDRREQ);
756 if (resid > so->so_snd.ssb_hiwat)
758 space = ssb_space(&so->so_snd);
759 if (uio && (space < 0 || (size_t)space < resid)) {
760 if (flags & (MSG_FNONBLOCKING|MSG_DONTWAIT))
761 gotoerr(EWOULDBLOCK);
762 ssb_unlock(&so->so_snd);
763 error = ssb_wait(&so->so_snd);
772 top = m_uiomove(uio);
777 dontroute = (flags & MSG_DONTROUTE) && !(so->so_options & SO_DONTROUTE);
779 so->so_options |= SO_DONTROUTE;
781 error = so_pru_send(so, 0, top, addr, NULL, td);
782 top = NULL; /* sent or freed in lower layer */
785 so->so_options &= ~SO_DONTROUTE;
788 ssb_unlock(&so->so_snd);
796 * Implement receive operations on a socket.
797 * We depend on the way that records are added to the signalsockbuf
798 * by sbappend*. In particular, each record (mbufs linked through m_next)
799 * must begin with an address if the protocol so specifies,
800 * followed by an optional mbuf or mbufs containing ancillary data,
801 * and then zero or more mbufs of data.
802 * In order to avoid blocking network interrupts for the entire time here,
803 * we exit the critical section while doing the actual copy to user space.
804 * Although the signalsockbuf is locked, new data may still be appended,
805 * and thus we must maintain consistency of the signalsockbuf during that time.
807 * The caller may receive the data as a single mbuf chain by supplying
808 * an mbuf **mp0 for use in returning the chain. The uio is then used
809 * only for the count in uio_resid.
812 soreceive(struct socket *so, struct sockaddr **psa, struct uio *uio,
813 struct sockbuf *sio, struct mbuf **controlp, int *flagsp)
816 struct mbuf *free_chain = NULL;
817 int flags, len, error, offset;
818 struct protosw *pr = so->so_proto;
820 size_t resid, orig_resid;
823 resid = uio->uio_resid;
825 resid = (size_t)(sio->sb_climit - sio->sb_cc);
833 flags = *flagsp &~ MSG_EOR;
836 if (flags & MSG_OOB) {
837 m = m_get(MB_WAIT, MT_DATA);
840 error = so_pru_rcvoob(so, m, flags & MSG_PEEK);
846 KKASSERT(resid >= (size_t)m->m_len);
847 resid -= (size_t)m->m_len;
848 } while (resid > 0 && m);
851 uio->uio_resid = resid;
852 error = uiomove(mtod(m, caddr_t),
853 (int)szmin(resid, m->m_len),
855 resid = uio->uio_resid;
857 } while (uio->uio_resid && error == 0 && m);
864 if ((so->so_state & SS_ISCONFIRMING) && resid)
869 error = ssb_lock(&so->so_rcv, SBLOCKWAIT(flags));
873 m = so->so_rcv.ssb_mb;
875 * If we have less data than requested, block awaiting more
876 * (subject to any timeout) if:
877 * 1. the current count is less than the low water mark, or
878 * 2. MSG_WAITALL is set, and it is possible to do the entire
879 * receive operation at once if we block (resid <= hiwat).
880 * 3. MSG_DONTWAIT is not set
881 * If MSG_WAITALL is set but resid is larger than the receive buffer,
882 * we have to do the receive in sections, and thus risk returning
883 * a short count if a timeout or signal occurs after we start.
885 if (m == NULL || (((flags & MSG_DONTWAIT) == 0 &&
886 (size_t)so->so_rcv.ssb_cc < resid) &&
887 (so->so_rcv.ssb_cc < so->so_rcv.ssb_lowat ||
888 ((flags & MSG_WAITALL) && resid <= (size_t)so->so_rcv.ssb_hiwat)) &&
889 m->m_nextpkt == 0 && (pr->pr_flags & PR_ATOMIC) == 0)) {
890 KASSERT(m != NULL || !so->so_rcv.ssb_cc, ("receive 1"));
894 error = so->so_error;
895 if ((flags & MSG_PEEK) == 0)
899 if (so->so_state & SS_CANTRCVMORE) {
905 for (; m; m = m->m_next) {
906 if (m->m_type == MT_OOBDATA || (m->m_flags & M_EOR)) {
907 m = so->so_rcv.ssb_mb;
911 if ((so->so_state & (SS_ISCONNECTED|SS_ISCONNECTING)) == 0 &&
912 (pr->pr_flags & PR_CONNREQUIRED)) {
918 if (flags & (MSG_FNONBLOCKING|MSG_DONTWAIT)) {
922 ssb_unlock(&so->so_rcv);
923 error = ssb_wait(&so->so_rcv);
930 if (uio && uio->uio_td && uio->uio_td->td_proc)
931 uio->uio_td->td_lwp->lwp_ru.ru_msgrcv++;
934 * note: m should be == sb_mb here. Cache the next record while
935 * cleaning up. Note that calling m_free*() will break out critical
938 KKASSERT(m == so->so_rcv.ssb_mb);
941 * Skip any address mbufs prepending the record.
943 if (pr->pr_flags & PR_ADDR) {
944 KASSERT(m->m_type == MT_SONAME, ("receive 1a"));
947 *psa = dup_sockaddr(mtod(m, struct sockaddr *));
948 if (flags & MSG_PEEK)
951 m = sbunlinkmbuf(&so->so_rcv.sb, m, &free_chain);
955 * Skip any control mbufs prepending the record.
958 if (pr->pr_flags & PR_ADDR_OPT) {
960 * For SCTP we may be getting a
961 * whole message OR a partial delivery.
963 if (m && m->m_type == MT_SONAME) {
966 *psa = dup_sockaddr(mtod(m, struct sockaddr *));
967 if (flags & MSG_PEEK)
970 m = sbunlinkmbuf(&so->so_rcv.sb, m, &free_chain);
974 while (m && m->m_type == MT_CONTROL && error == 0) {
975 if (flags & MSG_PEEK) {
977 *controlp = m_copy(m, 0, m->m_len);
978 m = m->m_next; /* XXX race */
981 n = sbunlinkmbuf(&so->so_rcv.sb, m, NULL);
982 if (pr->pr_domain->dom_externalize &&
983 mtod(m, struct cmsghdr *)->cmsg_type ==
985 error = (*pr->pr_domain->dom_externalize)(m);
989 m = sbunlinkmbuf(&so->so_rcv.sb, m, &free_chain);
992 if (controlp && *controlp) {
994 controlp = &(*controlp)->m_next;
1003 if (type == MT_OOBDATA)
1008 * Copy to the UIO or mbuf return chain (*mp).
1012 while (m && resid > 0 && error == 0) {
1013 if (m->m_type == MT_OOBDATA) {
1014 if (type != MT_OOBDATA)
1016 } else if (type == MT_OOBDATA)
1019 KASSERT(m->m_type == MT_DATA || m->m_type == MT_HEADER,
1021 so->so_state &= ~SS_RCVATMARK;
1022 len = (resid > INT_MAX) ? INT_MAX : resid;
1023 if (so->so_oobmark && len > so->so_oobmark - offset)
1024 len = so->so_oobmark - offset;
1025 if (len > m->m_len - moff)
1026 len = m->m_len - moff;
1029 * Copy out to the UIO or pass the mbufs back to the SIO.
1030 * The SIO is dealt with when we eat the mbuf, but deal
1031 * with the resid here either way.
1035 uio->uio_resid = resid;
1036 error = uiomove(mtod(m, caddr_t) + moff, len, uio);
1037 resid = uio->uio_resid;
1042 resid -= (size_t)len;
1046 * Eat the entire mbuf or just a piece of it
1048 if (len == m->m_len - moff) {
1049 if (m->m_flags & M_EOR)
1052 if (m->m_flags & M_NOTIFICATION)
1053 flags |= MSG_NOTIFICATION;
1055 if (flags & MSG_PEEK) {
1060 n = sbunlinkmbuf(&so->so_rcv.sb, m, NULL);
1064 m = sbunlinkmbuf(&so->so_rcv.sb, m, &free_chain);
1068 if (flags & MSG_PEEK) {
1072 n = m_copym(m, 0, len, MB_WAIT);
1078 so->so_rcv.ssb_cc -= len;
1081 if (so->so_oobmark) {
1082 if ((flags & MSG_PEEK) == 0) {
1083 so->so_oobmark -= len;
1084 if (so->so_oobmark == 0) {
1085 so->so_state |= SS_RCVATMARK;
1090 if (offset == so->so_oobmark)
1094 if (flags & MSG_EOR)
1097 * If the MSG_WAITALL flag is set (for non-atomic socket),
1098 * we must not quit until resid == 0 or an error
1099 * termination. If a signal/timeout occurs, return
1100 * with a short count but without error.
1101 * Keep signalsockbuf locked against other readers.
1103 while ((flags & MSG_WAITALL) && m == NULL &&
1104 resid > 0 && !sosendallatonce(so) &&
1105 so->so_rcv.ssb_mb == NULL) {
1106 if (so->so_error || so->so_state & SS_CANTRCVMORE)
1109 * The window might have closed to zero, make
1110 * sure we send an ack now that we've drained
1111 * the buffer or we might end up blocking until
1112 * the idle takes over (5 seconds).
1114 if (pr->pr_flags & PR_WANTRCVD && so->so_pcb)
1115 so_pru_rcvd(so, flags);
1116 error = ssb_wait(&so->so_rcv);
1118 ssb_unlock(&so->so_rcv);
1122 m = so->so_rcv.ssb_mb;
1127 * If an atomic read was requested but unread data still remains
1128 * in the record, set MSG_TRUNC.
1130 if (m && pr->pr_flags & PR_ATOMIC)
1134 * Cleanup. If an atomic read was requested drop any unread data.
1136 if ((flags & MSG_PEEK) == 0) {
1137 if (m && (pr->pr_flags & PR_ATOMIC))
1138 sbdroprecord(&so->so_rcv.sb);
1139 if ((pr->pr_flags & PR_WANTRCVD) && so->so_pcb)
1140 so_pru_rcvd(so, flags);
1143 if (orig_resid == resid && orig_resid &&
1144 (flags & MSG_EOR) == 0 && (so->so_state & SS_CANTRCVMORE) == 0) {
1145 ssb_unlock(&so->so_rcv);
1153 ssb_unlock(&so->so_rcv);
1157 m_freem(free_chain);
1162 soshutdown(struct socket *so, int how)
1164 if (!(how == SHUT_RD || how == SHUT_WR || how == SHUT_RDWR))
1170 return (so_pru_shutdown(so));
1175 sorflush(struct socket *so)
1177 struct signalsockbuf *ssb = &so->so_rcv;
1178 struct protosw *pr = so->so_proto;
1179 struct signalsockbuf asb;
1181 ssb->ssb_flags |= SSB_NOINTR;
1182 (void) ssb_lock(ssb, M_WAITOK);
1188 bzero((caddr_t)ssb, sizeof (*ssb));
1189 if (asb.ssb_flags & SSB_KNOTE) {
1190 ssb->ssb_kq.ki_note = asb.ssb_kq.ki_note;
1191 ssb->ssb_flags = SSB_KNOTE;
1195 if (pr->pr_flags & PR_RIGHTS && pr->pr_domain->dom_dispose)
1196 (*pr->pr_domain->dom_dispose)(asb.ssb_mb);
1197 ssb_release(&asb, so);
1202 do_setopt_accept_filter(struct socket *so, struct sockopt *sopt)
1204 struct accept_filter_arg *afap = NULL;
1205 struct accept_filter *afp;
1206 struct so_accf *af = so->so_accf;
1209 /* do not set/remove accept filters on non listen sockets */
1210 if ((so->so_options & SO_ACCEPTCONN) == 0) {
1215 /* removing the filter */
1218 if (af->so_accept_filter != NULL &&
1219 af->so_accept_filter->accf_destroy != NULL) {
1220 af->so_accept_filter->accf_destroy(so);
1222 if (af->so_accept_filter_str != NULL) {
1223 FREE(af->so_accept_filter_str, M_ACCF);
1228 so->so_options &= ~SO_ACCEPTFILTER;
1231 /* adding a filter */
1232 /* must remove previous filter first */
1237 /* don't put large objects on the kernel stack */
1238 MALLOC(afap, struct accept_filter_arg *, sizeof(*afap), M_TEMP, M_WAITOK);
1239 error = sooptcopyin(sopt, afap, sizeof *afap, sizeof *afap);
1240 afap->af_name[sizeof(afap->af_name)-1] = '\0';
1241 afap->af_arg[sizeof(afap->af_arg)-1] = '\0';
1244 afp = accept_filt_get(afap->af_name);
1249 MALLOC(af, struct so_accf *, sizeof(*af), M_ACCF, M_WAITOK | M_ZERO);
1250 if (afp->accf_create != NULL) {
1251 if (afap->af_name[0] != '\0') {
1252 int len = strlen(afap->af_name) + 1;
1254 MALLOC(af->so_accept_filter_str, char *, len, M_ACCF, M_WAITOK);
1255 strcpy(af->so_accept_filter_str, afap->af_name);
1257 af->so_accept_filter_arg = afp->accf_create(so, afap->af_arg);
1258 if (af->so_accept_filter_arg == NULL) {
1259 FREE(af->so_accept_filter_str, M_ACCF);
1266 af->so_accept_filter = afp;
1268 so->so_options |= SO_ACCEPTFILTER;
1277 * Perhaps this routine, and sooptcopyout(), below, ought to come in
1278 * an additional variant to handle the case where the option value needs
1279 * to be some kind of integer, but not a specific size.
1280 * In addition to their use here, these functions are also called by the
1281 * protocol-level pr_ctloutput() routines.
1284 sooptcopyin(struct sockopt *sopt, void *buf, size_t len, size_t minlen)
1286 return soopt_to_kbuf(sopt, buf, len, minlen);
1290 soopt_to_kbuf(struct sockopt *sopt, void *buf, size_t len, size_t minlen)
1294 KKASSERT(!sopt->sopt_val || kva_p(sopt->sopt_val));
1295 KKASSERT(kva_p(buf));
1298 * If the user gives us more than we wanted, we ignore it,
1299 * but if we don't get the minimum length the caller
1300 * wants, we return EINVAL. On success, sopt->sopt_valsize
1301 * is set to however much we actually retrieved.
1303 if ((valsize = sopt->sopt_valsize) < minlen)
1306 sopt->sopt_valsize = valsize = len;
1308 bcopy(sopt->sopt_val, buf, valsize);
1314 sosetopt(struct socket *so, struct sockopt *sopt)
1322 sopt->sopt_dir = SOPT_SET;
1323 if (sopt->sopt_level != SOL_SOCKET) {
1324 if (so->so_proto && so->so_proto->pr_ctloutput) {
1325 return (so_pru_ctloutput(so, sopt));
1327 error = ENOPROTOOPT;
1329 switch (sopt->sopt_name) {
1331 case SO_ACCEPTFILTER:
1332 error = do_setopt_accept_filter(so, sopt);
1338 error = sooptcopyin(sopt, &l, sizeof l, sizeof l);
1342 so->so_linger = l.l_linger;
1344 so->so_options |= SO_LINGER;
1346 so->so_options &= ~SO_LINGER;
1352 case SO_USELOOPBACK:
1358 error = sooptcopyin(sopt, &optval, sizeof optval,
1363 so->so_options |= sopt->sopt_name;
1365 so->so_options &= ~sopt->sopt_name;
1372 error = sooptcopyin(sopt, &optval, sizeof optval,
1378 * Values < 1 make no sense for any of these
1379 * options, so disallow them.
1386 switch (sopt->sopt_name) {
1389 if (ssb_reserve(sopt->sopt_name == SO_SNDBUF ?
1390 &so->so_snd : &so->so_rcv, (u_long)optval,
1392 &curproc->p_rlimit[RLIMIT_SBSIZE]) == 0) {
1396 (sopt->sopt_name == SO_SNDBUF ? &so->so_snd :
1397 &so->so_rcv)->ssb_flags &= ~SSB_AUTOSIZE;
1401 * Make sure the low-water is never greater than
1405 so->so_snd.ssb_lowat =
1406 (optval > so->so_snd.ssb_hiwat) ?
1407 so->so_snd.ssb_hiwat : optval;
1408 so->so_snd.ssb_flags &= ~SSB_AUTOLOWAT;
1411 so->so_rcv.ssb_lowat =
1412 (optval > so->so_rcv.ssb_hiwat) ?
1413 so->so_rcv.ssb_hiwat : optval;
1414 so->so_rcv.ssb_flags &= ~SSB_AUTOLOWAT;
1421 error = sooptcopyin(sopt, &tv, sizeof tv,
1426 /* assert(hz > 0); */
1427 if (tv.tv_sec < 0 || tv.tv_sec > SHRT_MAX / hz ||
1428 tv.tv_usec < 0 || tv.tv_usec >= 1000000) {
1432 /* assert(tick > 0); */
1433 /* assert(ULONG_MAX - SHRT_MAX >= 1000000); */
1434 val = (u_long)(tv.tv_sec * hz) + tv.tv_usec / ustick;
1435 if (val > SHRT_MAX) {
1439 if (val == 0 && tv.tv_usec != 0)
1442 switch (sopt->sopt_name) {
1444 so->so_snd.ssb_timeo = val;
1447 so->so_rcv.ssb_timeo = val;
1452 error = ENOPROTOOPT;
1455 if (error == 0 && so->so_proto && so->so_proto->pr_ctloutput) {
1456 (void) so_pru_ctloutput(so, sopt);
1463 /* Helper routine for getsockopt */
1465 sooptcopyout(struct sockopt *sopt, const void *buf, size_t len)
1467 soopt_from_kbuf(sopt, buf, len);
1472 soopt_from_kbuf(struct sockopt *sopt, const void *buf, size_t len)
1477 sopt->sopt_valsize = 0;
1481 KKASSERT(!sopt->sopt_val || kva_p(sopt->sopt_val));
1482 KKASSERT(kva_p(buf));
1485 * Documented get behavior is that we always return a value,
1486 * possibly truncated to fit in the user's buffer.
1487 * Traditional behavior is that we always tell the user
1488 * precisely how much we copied, rather than something useful
1489 * like the total amount we had available for her.
1490 * Note that this interface is not idempotent; the entire answer must
1491 * generated ahead of time.
1493 valsize = szmin(len, sopt->sopt_valsize);
1494 sopt->sopt_valsize = valsize;
1495 if (sopt->sopt_val != 0) {
1496 bcopy(buf, sopt->sopt_val, valsize);
1501 sogetopt(struct socket *so, struct sockopt *sopt)
1507 struct accept_filter_arg *afap;
1511 sopt->sopt_dir = SOPT_GET;
1512 if (sopt->sopt_level != SOL_SOCKET) {
1513 if (so->so_proto && so->so_proto->pr_ctloutput) {
1514 return (so_pru_ctloutput(so, sopt));
1516 return (ENOPROTOOPT);
1518 switch (sopt->sopt_name) {
1520 case SO_ACCEPTFILTER:
1521 if ((so->so_options & SO_ACCEPTCONN) == 0)
1523 MALLOC(afap, struct accept_filter_arg *, sizeof(*afap),
1524 M_TEMP, M_WAITOK | M_ZERO);
1525 if ((so->so_options & SO_ACCEPTFILTER) != 0) {
1526 strcpy(afap->af_name, so->so_accf->so_accept_filter->accf_name);
1527 if (so->so_accf->so_accept_filter_str != NULL)
1528 strcpy(afap->af_arg, so->so_accf->so_accept_filter_str);
1530 error = sooptcopyout(sopt, afap, sizeof(*afap));
1536 l.l_onoff = so->so_options & SO_LINGER;
1537 l.l_linger = so->so_linger;
1538 error = sooptcopyout(sopt, &l, sizeof l);
1541 case SO_USELOOPBACK:
1550 optval = so->so_options & sopt->sopt_name;
1552 error = sooptcopyout(sopt, &optval, sizeof optval);
1556 optval = so->so_type;
1560 optval = so->so_error;
1565 optval = so->so_snd.ssb_hiwat;
1569 optval = so->so_rcv.ssb_hiwat;
1573 optval = so->so_snd.ssb_lowat;
1577 optval = so->so_rcv.ssb_lowat;
1582 optval = (sopt->sopt_name == SO_SNDTIMEO ?
1583 so->so_snd.ssb_timeo : so->so_rcv.ssb_timeo);
1585 tv.tv_sec = optval / hz;
1586 tv.tv_usec = (optval % hz) * ustick;
1587 error = sooptcopyout(sopt, &tv, sizeof tv);
1591 error = ENOPROTOOPT;
1598 /* XXX; prepare mbuf for (__FreeBSD__ < 3) routines. */
1600 soopt_getm(struct sockopt *sopt, struct mbuf **mp)
1602 struct mbuf *m, *m_prev;
1603 int sopt_size = sopt->sopt_valsize, msize;
1605 m = m_getl(sopt_size, sopt->sopt_td ? MB_WAIT : MB_DONTWAIT, MT_DATA,
1609 m->m_len = min(msize, sopt_size);
1610 sopt_size -= m->m_len;
1614 while (sopt_size > 0) {
1615 m = m_getl(sopt_size, sopt->sopt_td ? MB_WAIT : MB_DONTWAIT,
1616 MT_DATA, 0, &msize);
1621 m->m_len = min(msize, sopt_size);
1622 sopt_size -= m->m_len;
1629 /* XXX; copyin sopt data into mbuf chain for (__FreeBSD__ < 3) routines. */
1631 soopt_mcopyin(struct sockopt *sopt, struct mbuf *m)
1633 soopt_to_mbuf(sopt, m);
1638 soopt_to_mbuf(struct sockopt *sopt, struct mbuf *m)
1643 KKASSERT(!sopt->sopt_val || kva_p(sopt->sopt_val));
1645 if (sopt->sopt_val == NULL)
1647 val = sopt->sopt_val;
1648 valsize = sopt->sopt_valsize;
1649 while (m != NULL && valsize >= m->m_len) {
1650 bcopy(val, mtod(m, char *), m->m_len);
1651 valsize -= m->m_len;
1652 val = (caddr_t)val + m->m_len;
1655 if (m != NULL) /* should be allocated enoughly at ip6_sooptmcopyin() */
1656 panic("ip6_sooptmcopyin");
1659 /* XXX; copyout mbuf chain data into soopt for (__FreeBSD__ < 3) routines. */
1661 soopt_mcopyout(struct sockopt *sopt, struct mbuf *m)
1663 return soopt_from_mbuf(sopt, m);
1667 soopt_from_mbuf(struct sockopt *sopt, struct mbuf *m)
1669 struct mbuf *m0 = m;
1674 KKASSERT(!sopt->sopt_val || kva_p(sopt->sopt_val));
1676 if (sopt->sopt_val == NULL)
1678 val = sopt->sopt_val;
1679 maxsize = sopt->sopt_valsize;
1680 while (m != NULL && maxsize >= m->m_len) {
1681 bcopy(mtod(m, char *), val, m->m_len);
1682 maxsize -= m->m_len;
1683 val = (caddr_t)val + m->m_len;
1684 valsize += m->m_len;
1688 /* enough soopt buffer should be given from user-land */
1692 sopt->sopt_valsize = valsize;
1697 sohasoutofband(struct socket *so)
1699 if (so->so_sigio != NULL)
1700 pgsigio(so->so_sigio, SIGURG, 0);
1701 KNOTE(&so->so_rcv.ssb_kq.ki_note, NOTE_OOB);
1705 sokqfilter(struct file *fp, struct knote *kn)
1707 struct socket *so = (struct socket *)kn->kn_fp->f_data;
1708 struct signalsockbuf *ssb;
1710 switch (kn->kn_filter) {
1712 if (so->so_options & SO_ACCEPTCONN)
1713 kn->kn_fop = &solisten_filtops;
1715 kn->kn_fop = &soread_filtops;
1719 kn->kn_fop = &sowrite_filtops;
1723 kn->kn_fop = &soexcept_filtops;
1727 return (EOPNOTSUPP);
1730 knote_insert(&ssb->ssb_kq.ki_note, kn);
1731 ssb->ssb_flags |= SSB_KNOTE;
1736 filt_sordetach(struct knote *kn)
1738 struct socket *so = (struct socket *)kn->kn_fp->f_data;
1740 knote_remove(&so->so_rcv.ssb_kq.ki_note, kn);
1741 if (SLIST_EMPTY(&so->so_rcv.ssb_kq.ki_note))
1742 so->so_rcv.ssb_flags &= ~SSB_KNOTE;
1747 filt_soread(struct knote *kn, long hint)
1749 struct socket *so = (struct socket *)kn->kn_fp->f_data;
1751 if (kn->kn_sfflags & NOTE_OOB) {
1752 if ((so->so_oobmark || (so->so_state & SS_RCVATMARK))) {
1753 kn->kn_fflags |= NOTE_OOB;
1758 kn->kn_data = so->so_rcv.ssb_cc;
1761 * Only set EOF if all data has been exhausted.
1763 if ((so->so_state & SS_CANTRCVMORE) && kn->kn_data == 0) {
1764 kn->kn_flags |= EV_EOF;
1765 kn->kn_fflags = so->so_error;
1768 if (so->so_error) /* temporary udp error */
1770 if (kn->kn_sfflags & NOTE_LOWAT)
1771 return (kn->kn_data >= kn->kn_sdata);
1772 return ((kn->kn_data >= so->so_rcv.ssb_lowat) ||
1773 !TAILQ_EMPTY(&so->so_comp));
1777 filt_sowdetach(struct knote *kn)
1779 struct socket *so = (struct socket *)kn->kn_fp->f_data;
1781 knote_remove(&so->so_snd.ssb_kq.ki_note, kn);
1782 if (SLIST_EMPTY(&so->so_snd.ssb_kq.ki_note))
1783 so->so_snd.ssb_flags &= ~SSB_KNOTE;
1788 filt_sowrite(struct knote *kn, long hint)
1790 struct socket *so = (struct socket *)kn->kn_fp->f_data;
1792 kn->kn_data = ssb_space(&so->so_snd);
1793 if (so->so_state & SS_CANTSENDMORE) {
1794 kn->kn_flags |= EV_EOF;
1795 kn->kn_fflags = so->so_error;
1798 if (so->so_error) /* temporary udp error */
1800 if (((so->so_state & SS_ISCONNECTED) == 0) &&
1801 (so->so_proto->pr_flags & PR_CONNREQUIRED))
1803 if (kn->kn_sfflags & NOTE_LOWAT)
1804 return (kn->kn_data >= kn->kn_sdata);
1805 return (kn->kn_data >= so->so_snd.ssb_lowat);
1810 filt_solisten(struct knote *kn, long hint)
1812 struct socket *so = (struct socket *)kn->kn_fp->f_data;
1814 kn->kn_data = so->so_qlen;
1815 return (! TAILQ_EMPTY(&so->so_comp));