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.51 2008/07/07 14:35:12 aggelos 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 };
120 struct vm_zone *socket_zone;
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 from our zone, and initialize it.
140 * We don't implement `waitok' yet (see comments in uipc_domain.c).
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.
150 so = zalloc(socket_zone);
152 /* XXX race condition for reentrant kernel */
153 bzero(so, sizeof *so);
154 TAILQ_INIT(&so->so_aiojobq);
155 TAILQ_INIT(&so->so_rcv.ssb_sel.si_mlist);
156 TAILQ_INIT(&so->so_snd.ssb_sel.si_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);
193 TAILQ_INIT(&so->so_incomp);
194 TAILQ_INIT(&so->so_comp);
196 so->so_cred = crhold(p->p_ucred);
198 ai.sb_rlimit = &p->p_rlimit[RLIMIT_SBSIZE];
199 ai.p_ucred = p->p_ucred;
200 ai.fd_rdir = p->p_fd->fd_rdir;
201 error = so_pru_attach(so, proto, &ai);
203 so->so_state |= SS_NOFDREF;
212 sobind(struct socket *so, struct sockaddr *nam, struct thread *td)
217 error = so_pru_bind(so, nam, td);
223 sodealloc(struct socket *so)
225 if (so->so_rcv.ssb_hiwat)
226 (void)chgsbsize(so->so_cred->cr_uidinfo,
227 &so->so_rcv.ssb_hiwat, 0, RLIM_INFINITY);
228 if (so->so_snd.ssb_hiwat)
229 (void)chgsbsize(so->so_cred->cr_uidinfo,
230 &so->so_snd.ssb_hiwat, 0, RLIM_INFINITY);
232 /* remove accept filter if present */
233 if (so->so_accf != NULL)
234 do_setopt_accept_filter(so, NULL);
237 zfree(socket_zone, so);
241 solisten(struct socket *so, int backlog, struct thread *td)
245 short oldopt, oldqlimit;
249 if (so->so_state & (SS_ISCONNECTED | SS_ISCONNECTING)) {
255 oldopt = so->so_options;
256 oldqlimit = so->so_qlimit;
259 if (TAILQ_EMPTY(&so->so_comp))
260 so->so_options |= SO_ACCEPTCONN;
261 if (backlog < 0 || backlog > somaxconn)
263 so->so_qlimit = backlog;
264 /* SCTP needs to look at tweak both the inbound backlog parameter AND
265 * the so_options (UDP model both connect's and gets inbound
266 * connections .. implicitly).
268 error = so_pru_listen(so, td);
271 /* Restore the params */
272 so->so_options = oldopt;
273 so->so_qlimit = oldqlimit;
283 sofree(struct socket *so)
285 struct socket *head = so->so_head;
287 if (so->so_pcb || (so->so_state & SS_NOFDREF) == 0)
290 if (so->so_state & SS_INCOMP) {
291 TAILQ_REMOVE(&head->so_incomp, so, so_list);
293 } else if (so->so_state & SS_COMP) {
295 * We must not decommission a socket that's
296 * on the accept(2) queue. If we do, then
297 * accept(2) may hang after select(2) indicated
298 * that the listening socket was ready.
302 panic("sofree: not queued");
304 so->so_state &= ~SS_INCOMP;
307 ssb_release(&so->so_snd, so);
313 * Close a socket on last file table reference removal.
314 * Initiate disconnect if connected.
315 * Free socket when disconnect complete.
318 soclose(struct socket *so, int fflag)
323 funsetown(so->so_sigio);
324 if (so->so_pcb == NULL)
326 if (so->so_state & SS_ISCONNECTED) {
327 if ((so->so_state & SS_ISDISCONNECTING) == 0) {
328 error = sodisconnect(so);
332 if (so->so_options & SO_LINGER) {
333 if ((so->so_state & SS_ISDISCONNECTING) &&
336 while (so->so_state & SS_ISCONNECTED) {
337 error = tsleep((caddr_t)&so->so_timeo,
338 PCATCH, "soclos", so->so_linger * hz);
348 error2 = so_pru_detach(so);
353 if (so->so_options & SO_ACCEPTCONN) {
354 struct socket *sp, *sonext;
356 sp = TAILQ_FIRST(&so->so_incomp);
357 for (; sp != NULL; sp = sonext) {
358 sonext = TAILQ_NEXT(sp, so_list);
361 for (sp = TAILQ_FIRST(&so->so_comp); sp != NULL; sp = sonext) {
362 sonext = TAILQ_NEXT(sp, so_list);
363 /* Dequeue from so_comp since sofree() won't do it */
364 TAILQ_REMOVE(&so->so_comp, sp, so_list);
366 sp->so_state &= ~SS_COMP;
371 if (so->so_state & SS_NOFDREF)
372 panic("soclose: NOFDREF");
373 so->so_state |= SS_NOFDREF;
380 * Must be called from a critical section.
383 soabort(struct socket *so)
387 error = so_pru_abort(so);
396 soaccept(struct socket *so, struct sockaddr **nam)
401 if ((so->so_state & SS_NOFDREF) == 0)
402 panic("soaccept: !NOFDREF");
403 so->so_state &= ~SS_NOFDREF;
404 error = so_pru_accept(so, nam);
410 soconnect(struct socket *so, struct sockaddr *nam, struct thread *td)
414 if (so->so_options & SO_ACCEPTCONN)
418 * If protocol is connection-based, can only connect once.
419 * Otherwise, if connected, try to disconnect first.
420 * This allows user to disconnect by connecting to, e.g.,
423 if (so->so_state & (SS_ISCONNECTED|SS_ISCONNECTING) &&
424 ((so->so_proto->pr_flags & PR_CONNREQUIRED) ||
425 (error = sodisconnect(so)))) {
429 * Prevent accumulated error from previous connection
433 error = so_pru_connect(so, nam, td);
440 soconnect2(struct socket *so1, struct socket *so2)
445 error = so_pru_connect2(so1, so2);
451 sodisconnect(struct socket *so)
456 if ((so->so_state & SS_ISCONNECTED) == 0) {
460 if (so->so_state & SS_ISDISCONNECTING) {
464 error = so_pru_disconnect(so);
470 #define SBLOCKWAIT(f) (((f) & MSG_DONTWAIT) ? M_NOWAIT : M_WAITOK)
473 * If send must go all at once and message is larger than
474 * send buffering, then hard error.
475 * Lock against other senders.
476 * If must go all at once and not enough room now, then
477 * inform user that this would block and do nothing.
478 * Otherwise, if nonblocking, send as much as possible.
479 * The data to be sent is described by "uio" if nonzero,
480 * otherwise by the mbuf chain "top" (which must be null
481 * if uio is not). Data provided in mbuf chain must be small
482 * enough to send all at once.
484 * Returns nonzero on error, timeout or signal; callers
485 * must check for short counts if EINTR/ERESTART are returned.
486 * Data and control buffers are freed on return.
489 sosend(struct socket *so, struct sockaddr *addr, struct uio *uio,
490 struct mbuf *top, struct mbuf *control, int flags,
495 long space, len, resid;
496 int clen = 0, error, dontroute, mlen;
497 int atomic = sosendallatonce(so) || top;
501 resid = uio->uio_resid;
503 resid = top->m_pkthdr.len;
505 * In theory resid should be unsigned.
506 * However, space must be signed, as it might be less than 0
507 * if we over-committed, and we must use a signed comparison
508 * of space and resid. On the other hand, a negative resid
509 * causes us to loop sending 0-length segments to the protocol.
511 * Also check to make sure that MSG_EOR isn't used on SOCK_STREAM
512 * type sockets since that's an error.
514 if (resid < 0 || (so->so_type == SOCK_STREAM && (flags & MSG_EOR))) {
520 (flags & MSG_DONTROUTE) && (so->so_options & SO_DONTROUTE) == 0 &&
521 (so->so_proto->pr_flags & PR_ATOMIC);
522 if (td->td_lwp != NULL)
523 td->td_lwp->lwp_ru.ru_msgsnd++;
525 clen = control->m_len;
526 #define gotoerr(errcode) { error = errcode; crit_exit(); goto release; }
529 error = ssb_lock(&so->so_snd, SBLOCKWAIT(flags));
534 if (so->so_state & SS_CANTSENDMORE)
537 error = so->so_error;
542 if ((so->so_state & SS_ISCONNECTED) == 0) {
544 * `sendto' and `sendmsg' is allowed on a connection-
545 * based socket if it supports implied connect.
546 * Return ENOTCONN if not connected and no address is
549 if ((so->so_proto->pr_flags & PR_CONNREQUIRED) &&
550 (so->so_proto->pr_flags & PR_IMPLOPCL) == 0) {
551 if ((so->so_state & SS_ISCONFIRMING) == 0 &&
552 !(resid == 0 && clen != 0))
554 } else if (addr == 0)
555 gotoerr(so->so_proto->pr_flags & PR_CONNREQUIRED ?
556 ENOTCONN : EDESTADDRREQ);
558 if ((atomic && resid > so->so_snd.ssb_hiwat) ||
559 clen > so->so_snd.ssb_hiwat) {
562 space = ssb_space(&so->so_snd);
565 if (space < resid + clen && uio &&
566 (atomic || space < so->so_snd.ssb_lowat || space < clen)) {
567 if (flags & (MSG_FNONBLOCKING|MSG_DONTWAIT))
568 gotoerr(EWOULDBLOCK);
569 ssb_unlock(&so->so_snd);
570 error = ssb_wait(&so->so_snd);
582 * Data is prepackaged in "top".
586 top->m_flags |= M_EOR;
588 m = m_getl(resid, MB_WAIT, MT_DATA,
589 top == NULL ? M_PKTHDR : 0, &mlen);
592 m->m_pkthdr.rcvif = (struct ifnet *)0;
594 len = min(min(mlen, resid), space);
595 if (resid < MINCLSIZE) {
597 * For datagram protocols, leave room
598 * for protocol headers in first mbuf.
600 if (atomic && top == 0 && len < mlen)
604 error = uiomove(mtod(m, caddr_t), (int)len, uio);
605 resid = uio->uio_resid;
608 top->m_pkthdr.len += len;
614 top->m_flags |= M_EOR;
617 } while (space > 0 && atomic);
619 so->so_options |= SO_DONTROUTE;
620 if (flags & MSG_OOB) {
621 pru_flags = PRUS_OOB;
622 } else if ((flags & MSG_EOF) &&
623 (so->so_proto->pr_flags & PR_IMPLOPCL) &&
626 * If the user set MSG_EOF, the protocol
627 * understands this flag and nothing left to
628 * send then use PRU_SEND_EOF instead of PRU_SEND.
630 pru_flags = PRUS_EOF;
631 } else if (resid > 0 && space > 0) {
632 /* If there is more to send, set PRUS_MORETOCOME */
633 pru_flags = PRUS_MORETOCOME;
639 * XXX all the SS_CANTSENDMORE checks previously
640 * done could be out of date. We could have recieved
641 * a reset packet in an interrupt or maybe we slept
642 * while doing page faults in uiomove() etc. We could
643 * probably recheck again inside the splnet() protection
644 * here, but there are probably other places that this
645 * also happens. We must rethink this.
647 error = so_pru_send(so, pru_flags, top, addr, control, td);
650 so->so_options &= ~SO_DONTROUTE;
657 } while (resid && space > 0);
661 ssb_unlock(&so->so_snd);
671 * A specialization of sosend() for UDP based on protocol-specific knowledge:
672 * so->so_proto->pr_flags has the PR_ATOMIC field set. This means that
673 * sosendallatonce() returns true,
674 * the "atomic" variable is true,
675 * and sosendudp() blocks until space is available for the entire send.
676 * so->so_proto->pr_flags does not have the PR_CONNREQUIRED or
677 * PR_IMPLOPCL flags set.
678 * UDP has no out-of-band data.
679 * UDP has no control data.
680 * UDP does not support MSG_EOR.
683 sosendudp(struct socket *so, struct sockaddr *addr, struct uio *uio,
684 struct mbuf *top, struct mbuf *control, int flags, struct thread *td)
687 boolean_t dontroute; /* temporary SO_DONTROUTE setting */
689 if (td->td_lwp != NULL)
690 td->td_lwp->lwp_ru.ru_msgsnd++;
694 KASSERT((uio && !top) || (top && !uio), ("bad arguments to sosendudp"));
695 resid = uio ? uio->uio_resid : top->m_pkthdr.len;
698 error = ssb_lock(&so->so_snd, SBLOCKWAIT(flags));
703 if (so->so_state & SS_CANTSENDMORE)
706 error = so->so_error;
711 if (!(so->so_state & SS_ISCONNECTED) && addr == NULL)
712 gotoerr(EDESTADDRREQ);
713 if (resid > so->so_snd.ssb_hiwat)
715 if (uio && ssb_space(&so->so_snd) < resid) {
716 if (flags & (MSG_FNONBLOCKING|MSG_DONTWAIT))
717 gotoerr(EWOULDBLOCK);
718 ssb_unlock(&so->so_snd);
719 error = ssb_wait(&so->so_snd);
728 top = m_uiomove(uio);
733 dontroute = (flags & MSG_DONTROUTE) && !(so->so_options & SO_DONTROUTE);
735 so->so_options |= SO_DONTROUTE;
737 error = so_pru_send(so, 0, top, addr, NULL, td);
738 top = NULL; /* sent or freed in lower layer */
741 so->so_options &= ~SO_DONTROUTE;
744 ssb_unlock(&so->so_snd);
752 * Implement receive operations on a socket.
753 * We depend on the way that records are added to the signalsockbuf
754 * by sbappend*. In particular, each record (mbufs linked through m_next)
755 * must begin with an address if the protocol so specifies,
756 * followed by an optional mbuf or mbufs containing ancillary data,
757 * and then zero or more mbufs of data.
758 * In order to avoid blocking network interrupts for the entire time here,
759 * we exit the critical section while doing the actual copy to user space.
760 * Although the signalsockbuf is locked, new data may still be appended,
761 * and thus we must maintain consistency of the signalsockbuf during that time.
763 * The caller may receive the data as a single mbuf chain by supplying
764 * an mbuf **mp0 for use in returning the chain. The uio is then used
765 * only for the count in uio_resid.
768 soreceive(struct socket *so, struct sockaddr **psa, struct uio *uio,
769 struct sockbuf *sio, struct mbuf **controlp, int *flagsp)
772 struct mbuf *free_chain = NULL;
773 int flags, len, error, offset;
774 struct protosw *pr = so->so_proto;
776 int resid, orig_resid;
779 resid = uio->uio_resid;
781 resid = (int)(sio->sb_climit - sio->sb_cc);
789 flags = *flagsp &~ MSG_EOR;
792 if (flags & MSG_OOB) {
793 m = m_get(MB_WAIT, MT_DATA);
796 error = so_pru_rcvoob(so, m, flags & MSG_PEEK);
803 } while (resid > 0 && m);
806 uio->uio_resid = resid;
807 error = uiomove(mtod(m, caddr_t),
808 (int)min(resid, m->m_len), uio);
809 resid = uio->uio_resid;
811 } while (uio->uio_resid && error == 0 && m);
818 if (so->so_state & SS_ISCONFIRMING && resid)
823 error = ssb_lock(&so->so_rcv, SBLOCKWAIT(flags));
827 m = so->so_rcv.ssb_mb;
829 * If we have less data than requested, block awaiting more
830 * (subject to any timeout) if:
831 * 1. the current count is less than the low water mark, or
832 * 2. MSG_WAITALL is set, and it is possible to do the entire
833 * receive operation at once if we block (resid <= hiwat).
834 * 3. MSG_DONTWAIT is not set
835 * If MSG_WAITALL is set but resid is larger than the receive buffer,
836 * we have to do the receive in sections, and thus risk returning
837 * a short count if a timeout or signal occurs after we start.
839 if (m == NULL || (((flags & MSG_DONTWAIT) == 0 &&
840 so->so_rcv.ssb_cc < resid) &&
841 (so->so_rcv.ssb_cc < so->so_rcv.ssb_lowat ||
842 ((flags & MSG_WAITALL) && resid <= so->so_rcv.ssb_hiwat)) &&
843 m->m_nextpkt == 0 && (pr->pr_flags & PR_ATOMIC) == 0)) {
844 KASSERT(m != NULL || !so->so_rcv.ssb_cc, ("receive 1"));
848 error = so->so_error;
849 if ((flags & MSG_PEEK) == 0)
853 if (so->so_state & SS_CANTRCVMORE) {
859 for (; m; m = m->m_next) {
860 if (m->m_type == MT_OOBDATA || (m->m_flags & M_EOR)) {
861 m = so->so_rcv.ssb_mb;
865 if ((so->so_state & (SS_ISCONNECTED|SS_ISCONNECTING)) == 0 &&
866 (pr->pr_flags & PR_CONNREQUIRED)) {
872 if (flags & (MSG_FNONBLOCKING|MSG_DONTWAIT)) {
876 ssb_unlock(&so->so_rcv);
877 error = ssb_wait(&so->so_rcv);
884 if (uio && uio->uio_td && uio->uio_td->td_proc)
885 uio->uio_td->td_lwp->lwp_ru.ru_msgrcv++;
888 * note: m should be == sb_mb here. Cache the next record while
889 * cleaning up. Note that calling m_free*() will break out critical
892 KKASSERT(m == so->so_rcv.ssb_mb);
895 * Skip any address mbufs prepending the record.
897 if (pr->pr_flags & PR_ADDR) {
898 KASSERT(m->m_type == MT_SONAME, ("receive 1a"));
901 *psa = dup_sockaddr(mtod(m, struct sockaddr *));
902 if (flags & MSG_PEEK)
905 m = sbunlinkmbuf(&so->so_rcv.sb, m, &free_chain);
909 * Skip any control mbufs prepending the record.
912 if (pr->pr_flags & PR_ADDR_OPT) {
914 * For SCTP we may be getting a
915 * whole message OR a partial delivery.
917 if (m && m->m_type == MT_SONAME) {
920 *psa = dup_sockaddr(mtod(m, struct sockaddr *));
921 if (flags & MSG_PEEK)
924 m = sbunlinkmbuf(&so->so_rcv.sb, m, &free_chain);
928 while (m && m->m_type == MT_CONTROL && error == 0) {
929 if (flags & MSG_PEEK) {
931 *controlp = m_copy(m, 0, m->m_len);
932 m = m->m_next; /* XXX race */
935 n = sbunlinkmbuf(&so->so_rcv.sb, m, NULL);
936 if (pr->pr_domain->dom_externalize &&
937 mtod(m, struct cmsghdr *)->cmsg_type ==
939 error = (*pr->pr_domain->dom_externalize)(m);
943 m = sbunlinkmbuf(&so->so_rcv.sb, m, &free_chain);
946 if (controlp && *controlp) {
948 controlp = &(*controlp)->m_next;
957 if (type == MT_OOBDATA)
962 * Copy to the UIO or mbuf return chain (*mp).
966 while (m && resid > 0 && error == 0) {
967 if (m->m_type == MT_OOBDATA) {
968 if (type != MT_OOBDATA)
970 } else if (type == MT_OOBDATA)
973 KASSERT(m->m_type == MT_DATA || m->m_type == MT_HEADER,
975 so->so_state &= ~SS_RCVATMARK;
977 if (so->so_oobmark && len > so->so_oobmark - offset)
978 len = so->so_oobmark - offset;
979 if (len > m->m_len - moff)
980 len = m->m_len - moff;
983 * Copy out to the UIO or pass the mbufs back to the SIO.
984 * The SIO is dealt with when we eat the mbuf, but deal
985 * with the resid here either way.
989 uio->uio_resid = resid;
990 error = uiomove(mtod(m, caddr_t) + moff, len, uio);
991 resid = uio->uio_resid;
1000 * Eat the entire mbuf or just a piece of it
1002 if (len == m->m_len - moff) {
1003 if (m->m_flags & M_EOR)
1006 if (m->m_flags & M_NOTIFICATION)
1007 flags |= MSG_NOTIFICATION;
1009 if (flags & MSG_PEEK) {
1014 n = sbunlinkmbuf(&so->so_rcv.sb, m, NULL);
1018 m = sbunlinkmbuf(&so->so_rcv.sb, m, &free_chain);
1022 if (flags & MSG_PEEK) {
1026 n = m_copym(m, 0, len, MB_WAIT);
1032 so->so_rcv.ssb_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 resid == 0 or an error
1053 * termination. If a signal/timeout occurs, return
1054 * with a short count but without error.
1055 * Keep signalsockbuf locked against other readers.
1057 while ((flags & MSG_WAITALL) && m == NULL &&
1058 resid > 0 && !sosendallatonce(so) &&
1059 so->so_rcv.ssb_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 = ssb_wait(&so->so_rcv);
1072 ssb_unlock(&so->so_rcv);
1076 m = so->so_rcv.ssb_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.sb);
1093 if ((pr->pr_flags & PR_WANTRCVD) && so->so_pcb)
1094 so_pru_rcvd(so, flags);
1097 if (orig_resid == resid && orig_resid &&
1098 (flags & MSG_EOR) == 0 && (so->so_state & SS_CANTRCVMORE) == 0) {
1099 ssb_unlock(&so->so_rcv);
1107 ssb_unlock(&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 signalsockbuf *ssb = &so->so_rcv;
1132 struct protosw *pr = so->so_proto;
1133 struct signalsockbuf asb;
1135 ssb->ssb_flags |= SSB_NOINTR;
1136 (void) ssb_lock(ssb, M_WAITOK);
1142 bzero((caddr_t)ssb, sizeof (*ssb));
1143 if (asb.ssb_flags & SSB_KNOTE) {
1144 ssb->ssb_sel.si_note = asb.ssb_sel.si_note;
1145 ssb->ssb_flags = SSB_KNOTE;
1149 if (pr->pr_flags & PR_RIGHTS && pr->pr_domain->dom_dispose)
1150 (*pr->pr_domain->dom_dispose)(asb.ssb_mb);
1151 ssb_release(&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 | M_ZERO);
1204 if (afp->accf_create != NULL) {
1205 if (afap->af_name[0] != '\0') {
1206 int len = strlen(afap->af_name) + 1;
1208 MALLOC(af->so_accept_filter_str, char *, len, M_ACCF, M_WAITOK);
1209 strcpy(af->so_accept_filter_str, afap->af_name);
1211 af->so_accept_filter_arg = afp->accf_create(so, afap->af_arg);
1212 if (af->so_accept_filter_arg == NULL) {
1213 FREE(af->so_accept_filter_str, M_ACCF);
1220 af->so_accept_filter = afp;
1222 so->so_options |= SO_ACCEPTFILTER;
1231 * Perhaps this routine, and sooptcopyout(), below, ought to come in
1232 * an additional variant to handle the case where the option value needs
1233 * to be some kind of integer, but not a specific size.
1234 * In addition to their use here, these functions are also called by the
1235 * protocol-level pr_ctloutput() routines.
1238 sooptcopyin(struct sockopt *sopt, void *buf, size_t len, size_t minlen)
1240 return soopt_to_kbuf(sopt, buf, len, minlen);
1244 soopt_to_kbuf(struct sockopt *sopt, void *buf, size_t len, size_t minlen)
1248 KKASSERT(kva_p(sopt->sopt_val));
1249 KKASSERT(kva_p(buf));
1252 * If the user gives us more than we wanted, we ignore it,
1253 * but if we don't get the minimum length the caller
1254 * wants, we return EINVAL. On success, sopt->sopt_valsize
1255 * is set to however much we actually retrieved.
1257 if ((valsize = sopt->sopt_valsize) < minlen)
1260 sopt->sopt_valsize = valsize = len;
1262 bcopy(sopt->sopt_val, buf, valsize);
1268 sosetopt(struct socket *so, struct sockopt *sopt)
1276 sopt->sopt_dir = SOPT_SET;
1277 if (sopt->sopt_level != SOL_SOCKET) {
1278 if (so->so_proto && so->so_proto->pr_ctloutput) {
1279 return (so_pru_ctloutput(so, sopt));
1281 error = ENOPROTOOPT;
1283 switch (sopt->sopt_name) {
1285 case SO_ACCEPTFILTER:
1286 error = do_setopt_accept_filter(so, sopt);
1292 error = sooptcopyin(sopt, &l, sizeof l, sizeof l);
1296 so->so_linger = l.l_linger;
1298 so->so_options |= SO_LINGER;
1300 so->so_options &= ~SO_LINGER;
1306 case SO_USELOOPBACK:
1312 error = sooptcopyin(sopt, &optval, sizeof optval,
1317 so->so_options |= sopt->sopt_name;
1319 so->so_options &= ~sopt->sopt_name;
1326 error = sooptcopyin(sopt, &optval, sizeof optval,
1332 * Values < 1 make no sense for any of these
1333 * options, so disallow them.
1340 switch (sopt->sopt_name) {
1343 if (ssb_reserve(sopt->sopt_name == SO_SNDBUF ?
1344 &so->so_snd : &so->so_rcv, (u_long)optval,
1346 &curproc->p_rlimit[RLIMIT_SBSIZE]) == 0) {
1353 * Make sure the low-water is never greater than
1357 so->so_snd.ssb_lowat =
1358 (optval > so->so_snd.ssb_hiwat) ?
1359 so->so_snd.ssb_hiwat : optval;
1362 so->so_rcv.ssb_lowat =
1363 (optval > so->so_rcv.ssb_hiwat) ?
1364 so->so_rcv.ssb_hiwat : optval;
1371 error = sooptcopyin(sopt, &tv, sizeof tv,
1376 /* assert(hz > 0); */
1377 if (tv.tv_sec < 0 || tv.tv_sec > SHRT_MAX / hz ||
1378 tv.tv_usec < 0 || tv.tv_usec >= 1000000) {
1382 /* assert(tick > 0); */
1383 /* assert(ULONG_MAX - SHRT_MAX >= 1000000); */
1384 val = (u_long)(tv.tv_sec * hz) + tv.tv_usec / tick;
1385 if (val > SHRT_MAX) {
1389 if (val == 0 && tv.tv_usec != 0)
1392 switch (sopt->sopt_name) {
1394 so->so_snd.ssb_timeo = val;
1397 so->so_rcv.ssb_timeo = val;
1402 error = ENOPROTOOPT;
1405 if (error == 0 && so->so_proto && so->so_proto->pr_ctloutput) {
1406 (void) so_pru_ctloutput(so, sopt);
1413 /* Helper routine for getsockopt */
1415 sooptcopyout(struct sockopt *sopt, const void *buf, size_t len)
1417 soopt_from_kbuf(sopt, buf, len);
1422 soopt_from_kbuf(struct sockopt *sopt, const void *buf, size_t len)
1426 KKASSERT(kva_p(sopt->sopt_val));
1427 KKASSERT(kva_p(buf));
1430 * Documented get behavior is that we always return a value,
1431 * possibly truncated to fit in the user's buffer.
1432 * Traditional behavior is that we always tell the user
1433 * precisely how much we copied, rather than something useful
1434 * like the total amount we had available for her.
1435 * Note that this interface is not idempotent; the entire answer must
1436 * generated ahead of time.
1438 valsize = min(len, sopt->sopt_valsize);
1439 sopt->sopt_valsize = valsize;
1440 if (sopt->sopt_val != 0) {
1441 bcopy(buf, sopt->sopt_val, valsize);
1446 sogetopt(struct socket *so, struct sockopt *sopt)
1452 struct accept_filter_arg *afap;
1456 sopt->sopt_dir = SOPT_GET;
1457 if (sopt->sopt_level != SOL_SOCKET) {
1458 if (so->so_proto && so->so_proto->pr_ctloutput) {
1459 return (so_pru_ctloutput(so, sopt));
1461 return (ENOPROTOOPT);
1463 switch (sopt->sopt_name) {
1465 case SO_ACCEPTFILTER:
1466 if ((so->so_options & SO_ACCEPTCONN) == 0)
1468 MALLOC(afap, struct accept_filter_arg *, sizeof(*afap),
1469 M_TEMP, M_WAITOK | M_ZERO);
1470 if ((so->so_options & SO_ACCEPTFILTER) != 0) {
1471 strcpy(afap->af_name, so->so_accf->so_accept_filter->accf_name);
1472 if (so->so_accf->so_accept_filter_str != NULL)
1473 strcpy(afap->af_arg, so->so_accf->so_accept_filter_str);
1475 error = sooptcopyout(sopt, afap, sizeof(*afap));
1481 l.l_onoff = so->so_options & SO_LINGER;
1482 l.l_linger = so->so_linger;
1483 error = sooptcopyout(sopt, &l, sizeof l);
1486 case SO_USELOOPBACK:
1495 optval = so->so_options & sopt->sopt_name;
1497 error = sooptcopyout(sopt, &optval, sizeof optval);
1501 optval = so->so_type;
1505 optval = so->so_error;
1510 optval = so->so_snd.ssb_hiwat;
1514 optval = so->so_rcv.ssb_hiwat;
1518 optval = so->so_snd.ssb_lowat;
1522 optval = so->so_rcv.ssb_lowat;
1527 optval = (sopt->sopt_name == SO_SNDTIMEO ?
1528 so->so_snd.ssb_timeo : so->so_rcv.ssb_timeo);
1530 tv.tv_sec = optval / hz;
1531 tv.tv_usec = (optval % hz) * tick;
1532 error = sooptcopyout(sopt, &tv, sizeof tv);
1536 error = ENOPROTOOPT;
1543 /* XXX; prepare mbuf for (__FreeBSD__ < 3) routines. */
1545 soopt_getm(struct sockopt *sopt, struct mbuf **mp)
1547 struct mbuf *m, *m_prev;
1548 int sopt_size = sopt->sopt_valsize, msize;
1550 m = m_getl(sopt_size, sopt->sopt_td ? MB_WAIT : MB_DONTWAIT, MT_DATA,
1554 m->m_len = min(msize, sopt_size);
1555 sopt_size -= m->m_len;
1559 while (sopt_size > 0) {
1560 m = m_getl(sopt_size, sopt->sopt_td ? MB_WAIT : MB_DONTWAIT,
1561 MT_DATA, 0, &msize);
1566 m->m_len = min(msize, sopt_size);
1567 sopt_size -= m->m_len;
1574 /* XXX; copyin sopt data into mbuf chain for (__FreeBSD__ < 3) routines. */
1576 soopt_mcopyin(struct sockopt *sopt, struct mbuf *m)
1578 soopt_to_mbuf(sopt, m);
1583 soopt_to_mbuf(struct sockopt *sopt, struct mbuf *m)
1585 struct mbuf *m0 = m;
1589 KKASSERT(kva_p(sopt->sopt_val));
1591 if (sopt->sopt_val == NULL)
1593 val = sopt->sopt_val;
1594 valsize = sopt->sopt_valsize;
1595 while (m != NULL && valsize >= m->m_len) {
1596 bcopy(val, mtod(m, char *), m->m_len);
1597 valsize -= m->m_len;
1598 val = (caddr_t)val + m->m_len;
1601 if (m != NULL) /* should be allocated enoughly at ip6_sooptmcopyin() */
1602 panic("ip6_sooptmcopyin");
1605 /* XXX; copyout mbuf chain data into soopt for (__FreeBSD__ < 3) routines. */
1607 soopt_mcopyout(struct sockopt *sopt, struct mbuf *m)
1609 return soopt_from_mbuf(sopt, m);
1613 soopt_from_mbuf(struct sockopt *sopt, struct mbuf *m)
1615 struct mbuf *m0 = m;
1620 KKASSERT(kva_p(sopt->sopt_val));
1622 if (sopt->sopt_val == NULL)
1624 val = sopt->sopt_val;
1625 maxsize = sopt->sopt_valsize;
1626 while (m != NULL && maxsize >= m->m_len) {
1627 bcopy(mtod(m, char *), val, m->m_len);
1628 maxsize -= m->m_len;
1629 val = (caddr_t)val + m->m_len;
1630 valsize += m->m_len;
1634 /* enough soopt buffer should be given from user-land */
1638 sopt->sopt_valsize = valsize;
1643 sohasoutofband(struct socket *so)
1645 if (so->so_sigio != NULL)
1646 pgsigio(so->so_sigio, SIGURG, 0);
1647 selwakeup(&so->so_rcv.ssb_sel);
1651 sopoll(struct socket *so, int events, struct ucred *cred, struct thread *td)
1657 if (events & (POLLIN | POLLRDNORM))
1659 revents |= events & (POLLIN | POLLRDNORM);
1661 if (events & POLLINIGNEOF)
1662 if (so->so_rcv.ssb_cc >= so->so_rcv.ssb_lowat ||
1663 !TAILQ_EMPTY(&so->so_comp) || so->so_error)
1664 revents |= POLLINIGNEOF;
1666 if (events & (POLLOUT | POLLWRNORM))
1667 if (sowriteable(so))
1668 revents |= events & (POLLOUT | POLLWRNORM);
1670 if (events & (POLLPRI | POLLRDBAND))
1671 if (so->so_oobmark || (so->so_state & SS_RCVATMARK))
1672 revents |= events & (POLLPRI | POLLRDBAND);
1676 (POLLIN | POLLINIGNEOF | POLLPRI | POLLRDNORM |
1678 selrecord(td, &so->so_rcv.ssb_sel);
1679 so->so_rcv.ssb_flags |= SSB_SEL;
1682 if (events & (POLLOUT | POLLWRNORM)) {
1683 selrecord(td, &so->so_snd.ssb_sel);
1684 so->so_snd.ssb_flags |= SSB_SEL;
1693 sokqfilter(struct file *fp, struct knote *kn)
1695 struct socket *so = (struct socket *)kn->kn_fp->f_data;
1696 struct signalsockbuf *ssb;
1698 switch (kn->kn_filter) {
1700 if (so->so_options & SO_ACCEPTCONN)
1701 kn->kn_fop = &solisten_filtops;
1703 kn->kn_fop = &soread_filtops;
1707 kn->kn_fop = &sowrite_filtops;
1715 SLIST_INSERT_HEAD(&ssb->ssb_sel.si_note, kn, kn_selnext);
1716 ssb->ssb_flags |= SSB_KNOTE;
1722 filt_sordetach(struct knote *kn)
1724 struct socket *so = (struct socket *)kn->kn_fp->f_data;
1727 SLIST_REMOVE(&so->so_rcv.ssb_sel.si_note, kn, knote, kn_selnext);
1728 if (SLIST_EMPTY(&so->so_rcv.ssb_sel.si_note))
1729 so->so_rcv.ssb_flags &= ~SSB_KNOTE;
1735 filt_soread(struct knote *kn, long hint)
1737 struct socket *so = (struct socket *)kn->kn_fp->f_data;
1739 kn->kn_data = so->so_rcv.ssb_cc;
1740 if (so->so_state & SS_CANTRCVMORE) {
1741 kn->kn_flags |= EV_EOF;
1742 kn->kn_fflags = so->so_error;
1745 if (so->so_error) /* temporary udp error */
1747 if (kn->kn_sfflags & NOTE_LOWAT)
1748 return (kn->kn_data >= kn->kn_sdata);
1749 return (kn->kn_data >= so->so_rcv.ssb_lowat);
1753 filt_sowdetach(struct knote *kn)
1755 struct socket *so = (struct socket *)kn->kn_fp->f_data;
1758 SLIST_REMOVE(&so->so_snd.ssb_sel.si_note, kn, knote, kn_selnext);
1759 if (SLIST_EMPTY(&so->so_snd.ssb_sel.si_note))
1760 so->so_snd.ssb_flags &= ~SSB_KNOTE;
1766 filt_sowrite(struct knote *kn, long hint)
1768 struct socket *so = (struct socket *)kn->kn_fp->f_data;
1770 kn->kn_data = ssb_space(&so->so_snd);
1771 if (so->so_state & SS_CANTSENDMORE) {
1772 kn->kn_flags |= EV_EOF;
1773 kn->kn_fflags = so->so_error;
1776 if (so->so_error) /* temporary udp error */
1778 if (((so->so_state & SS_ISCONNECTED) == 0) &&
1779 (so->so_proto->pr_flags & PR_CONNREQUIRED))
1781 if (kn->kn_sfflags & NOTE_LOWAT)
1782 return (kn->kn_data >= kn->kn_sdata);
1783 return (kn->kn_data >= so->so_snd.ssb_lowat);
1788 filt_solisten(struct knote *kn, long hint)
1790 struct socket *so = (struct socket *)kn->kn_fp->f_data;
1792 kn->kn_data = so->so_qlen;
1793 return (! TAILQ_EMPTY(&so->so_comp));