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