Change mbug allocation flags from M_ to MB_ to avoid confusion with malloc
[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.21 2004/06/02 14:42:57 eirikn 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                                             mp0 == 0);
848                 if (flags & MSG_PEEK) {
849                         m = m->m_next;
850                 } else {
851                         sbfree(&so->so_rcv, m);
852                         so->so_rcv.sb_mb = m_free(m);
853                         m = so->so_rcv.sb_mb;
854                 }
855         }
856         while (m && m->m_type == MT_CONTROL && error == 0) {
857                 if (flags & MSG_PEEK) {
858                         if (controlp)
859                                 *controlp = m_copy(m, 0, m->m_len);
860                         m = m->m_next;
861                 } else {
862                         sbfree(&so->so_rcv, m);
863                         if (controlp) {
864                                 if (pr->pr_domain->dom_externalize &&
865                                     mtod(m, struct cmsghdr *)->cmsg_type ==
866                                     SCM_RIGHTS)
867                                    error = (*pr->pr_domain->dom_externalize)(m);
868                                 *controlp = m;
869                                 so->so_rcv.sb_mb = m->m_next;
870                                 m->m_next = 0;
871                                 m = so->so_rcv.sb_mb;
872                         } else {
873                                 so->so_rcv.sb_mb = m_free(m);
874                                 m = so->so_rcv.sb_mb;
875                         }
876                 }
877                 if (controlp) {
878                         orig_resid = 0;
879                         controlp = &(*controlp)->m_next;
880                 }
881         }
882         if (m) {
883                 if ((flags & MSG_PEEK) == 0)
884                         m->m_nextpkt = nextrecord;
885                 type = m->m_type;
886                 if (type == MT_OOBDATA)
887                         flags |= MSG_OOB;
888         }
889         moff = 0;
890         offset = 0;
891         while (m && uio->uio_resid > 0 && error == 0) {
892                 if (m->m_type == MT_OOBDATA) {
893                         if (type != MT_OOBDATA)
894                                 break;
895                 } else if (type == MT_OOBDATA)
896                         break;
897                 else
898                     KASSERT(m->m_type == MT_DATA || m->m_type == MT_HEADER,
899                         ("receive 3"));
900                 so->so_state &= ~SS_RCVATMARK;
901                 len = uio->uio_resid;
902                 if (so->so_oobmark && len > so->so_oobmark - offset)
903                         len = so->so_oobmark - offset;
904                 if (len > m->m_len - moff)
905                         len = m->m_len - moff;
906                 /*
907                  * If mp is set, just pass back the mbufs.
908                  * Otherwise copy them out via the uio, then free.
909                  * Sockbuf must be consistent here (points to current mbuf,
910                  * it points to next record) when we drop priority;
911                  * we must note any additions to the sockbuf when we
912                  * block interrupts again.
913                  */
914                 if (mp == 0) {
915                         splx(s);
916                         error = uiomove(mtod(m, caddr_t) + moff, (int)len, uio);
917                         s = splnet();
918                         if (error)
919                                 goto release;
920                 } else
921                         uio->uio_resid -= len;
922                 if (len == m->m_len - moff) {
923                         if (m->m_flags & M_EOR)
924                                 flags |= MSG_EOR;
925                         if (flags & MSG_PEEK) {
926                                 m = m->m_next;
927                                 moff = 0;
928                         } else {
929                                 nextrecord = m->m_nextpkt;
930                                 sbfree(&so->so_rcv, m);
931                                 if (mp) {
932                                         *mp = m;
933                                         mp = &m->m_next;
934                                         so->so_rcv.sb_mb = m = m->m_next;
935                                         *mp = (struct mbuf *)0;
936                                 } else {
937                                         so->so_rcv.sb_mb = m = m_free(m);
938                                 }
939                                 if (m)
940                                         m->m_nextpkt = nextrecord;
941                         }
942                 } else {
943                         if (flags & MSG_PEEK)
944                                 moff += len;
945                         else {
946                                 if (mp)
947                                         *mp = m_copym(m, 0, len, MB_WAIT);
948                                 m->m_data += len;
949                                 m->m_len -= len;
950                                 so->so_rcv.sb_cc -= len;
951                         }
952                 }
953                 if (so->so_oobmark) {
954                         if ((flags & MSG_PEEK) == 0) {
955                                 so->so_oobmark -= len;
956                                 if (so->so_oobmark == 0) {
957                                         so->so_state |= SS_RCVATMARK;
958                                         break;
959                                 }
960                         } else {
961                                 offset += len;
962                                 if (offset == so->so_oobmark)
963                                         break;
964                         }
965                 }
966                 if (flags & MSG_EOR)
967                         break;
968                 /*
969                  * If the MSG_WAITALL flag is set (for non-atomic socket),
970                  * we must not quit until "uio->uio_resid == 0" or an error
971                  * termination.  If a signal/timeout occurs, return
972                  * with a short count but without error.
973                  * Keep sockbuf locked against other readers.
974                  */
975                 while (flags & MSG_WAITALL && m == 0 && uio->uio_resid > 0 &&
976                     !sosendallatonce(so) && !nextrecord) {
977                         if (so->so_error || so->so_state & SS_CANTRCVMORE)
978                                 break;
979                         /*
980                          * The window might have closed to zero, make
981                          * sure we send an ack now that we've drained
982                          * the buffer or we might end up blocking until
983                          * the idle takes over (5 seconds).
984                          */
985                         if (pr->pr_flags & PR_WANTRCVD && so->so_pcb)
986                                 so_pru_rcvd(so, flags);
987                         error = sbwait(&so->so_rcv);
988                         if (error) {
989                                 sbunlock(&so->so_rcv);
990                                 splx(s);
991                                 return (0);
992                         }
993                         m = so->so_rcv.sb_mb;
994                         if (m)
995                                 nextrecord = m->m_nextpkt;
996                 }
997         }
998
999         if (m && pr->pr_flags & PR_ATOMIC) {
1000                 flags |= MSG_TRUNC;
1001                 if ((flags & MSG_PEEK) == 0)
1002                         (void) sbdroprecord(&so->so_rcv);
1003         }
1004         if ((flags & MSG_PEEK) == 0) {
1005                 if (m == 0)
1006                         so->so_rcv.sb_mb = nextrecord;
1007                 if (pr->pr_flags & PR_WANTRCVD && so->so_pcb)
1008                         so_pru_rcvd(so, flags);
1009         }
1010         if (orig_resid == uio->uio_resid && orig_resid &&
1011             (flags & MSG_EOR) == 0 && (so->so_state & SS_CANTRCVMORE) == 0) {
1012                 sbunlock(&so->so_rcv);
1013                 splx(s);
1014                 goto restart;
1015         }
1016
1017         if (flagsp)
1018                 *flagsp |= flags;
1019 release:
1020         sbunlock(&so->so_rcv);
1021         splx(s);
1022         return (error);
1023 }
1024
1025 int
1026 soshutdown(so, how)
1027         struct socket *so;
1028         int how;
1029 {
1030         if (!(how == SHUT_RD || how == SHUT_WR || how == SHUT_RDWR))
1031                 return (EINVAL);
1032
1033         if (how != SHUT_WR)
1034                 sorflush(so);
1035         if (how != SHUT_RD)
1036                 return (so_pru_shutdown(so));
1037         return (0);
1038 }
1039
1040 void
1041 sorflush(so)
1042         struct socket *so;
1043 {
1044         struct sockbuf *sb = &so->so_rcv;
1045         struct protosw *pr = so->so_proto;
1046         int s;
1047         struct sockbuf asb;
1048
1049         sb->sb_flags |= SB_NOINTR;
1050         (void) sblock(sb, M_WAITOK);
1051         s = splimp();
1052         socantrcvmore(so);
1053         sbunlock(sb);
1054         asb = *sb;
1055         bzero((caddr_t)sb, sizeof (*sb));
1056         if (asb.sb_flags & SB_KNOTE) {
1057                 sb->sb_sel.si_note = asb.sb_sel.si_note;
1058                 sb->sb_flags = SB_KNOTE;
1059         }
1060         splx(s);
1061         if (pr->pr_flags & PR_RIGHTS && pr->pr_domain->dom_dispose)
1062                 (*pr->pr_domain->dom_dispose)(asb.sb_mb);
1063         sbrelease(&asb, so);
1064 }
1065
1066 #ifdef INET
1067 static int
1068 do_setopt_accept_filter(so, sopt)
1069         struct  socket *so;
1070         struct  sockopt *sopt;
1071 {
1072         struct accept_filter_arg        *afap = NULL;
1073         struct accept_filter    *afp;
1074         struct so_accf  *af = so->so_accf;
1075         int     error = 0;
1076
1077         /* do not set/remove accept filters on non listen sockets */
1078         if ((so->so_options & SO_ACCEPTCONN) == 0) {
1079                 error = EINVAL;
1080                 goto out;
1081         }
1082
1083         /* removing the filter */
1084         if (sopt == NULL) {
1085                 if (af != NULL) {
1086                         if (af->so_accept_filter != NULL && 
1087                                 af->so_accept_filter->accf_destroy != NULL) {
1088                                 af->so_accept_filter->accf_destroy(so);
1089                         }
1090                         if (af->so_accept_filter_str != NULL) {
1091                                 FREE(af->so_accept_filter_str, M_ACCF);
1092                         }
1093                         FREE(af, M_ACCF);
1094                         so->so_accf = NULL;
1095                 }
1096                 so->so_options &= ~SO_ACCEPTFILTER;
1097                 return (0);
1098         }
1099         /* adding a filter */
1100         /* must remove previous filter first */
1101         if (af != NULL) {
1102                 error = EINVAL;
1103                 goto out;
1104         }
1105         /* don't put large objects on the kernel stack */
1106         MALLOC(afap, struct accept_filter_arg *, sizeof(*afap), M_TEMP, M_WAITOK);
1107         error = sooptcopyin(sopt, afap, sizeof *afap, sizeof *afap);
1108         afap->af_name[sizeof(afap->af_name)-1] = '\0';
1109         afap->af_arg[sizeof(afap->af_arg)-1] = '\0';
1110         if (error)
1111                 goto out;
1112         afp = accept_filt_get(afap->af_name);
1113         if (afp == NULL) {
1114                 error = ENOENT;
1115                 goto out;
1116         }
1117         MALLOC(af, struct so_accf *, sizeof(*af), M_ACCF, M_WAITOK);
1118         bzero(af, sizeof(*af));
1119         if (afp->accf_create != NULL) {
1120                 if (afap->af_name[0] != '\0') {
1121                         int len = strlen(afap->af_name) + 1;
1122
1123                         MALLOC(af->so_accept_filter_str, char *, len, M_ACCF, M_WAITOK);
1124                         strcpy(af->so_accept_filter_str, afap->af_name);
1125                 }
1126                 af->so_accept_filter_arg = afp->accf_create(so, afap->af_arg);
1127                 if (af->so_accept_filter_arg == NULL) {
1128                         FREE(af->so_accept_filter_str, M_ACCF);
1129                         FREE(af, M_ACCF);
1130                         so->so_accf = NULL;
1131                         error = EINVAL;
1132                         goto out;
1133                 }
1134         }
1135         af->so_accept_filter = afp;
1136         so->so_accf = af;
1137         so->so_options |= SO_ACCEPTFILTER;
1138 out:
1139         if (afap != NULL)
1140                 FREE(afap, M_TEMP);
1141         return (error);
1142 }
1143 #endif /* INET */
1144
1145 /*
1146  * Perhaps this routine, and sooptcopyout(), below, ought to come in
1147  * an additional variant to handle the case where the option value needs
1148  * to be some kind of integer, but not a specific size.
1149  * In addition to their use here, these functions are also called by the
1150  * protocol-level pr_ctloutput() routines.
1151  */
1152 int
1153 sooptcopyin(sopt, buf, len, minlen)
1154         struct  sockopt *sopt;
1155         void    *buf;
1156         size_t  len;
1157         size_t  minlen;
1158 {
1159         size_t  valsize;
1160
1161         /*
1162          * If the user gives us more than we wanted, we ignore it,
1163          * but if we don't get the minimum length the caller
1164          * wants, we return EINVAL.  On success, sopt->sopt_valsize
1165          * is set to however much we actually retrieved.
1166          */
1167         if ((valsize = sopt->sopt_valsize) < minlen)
1168                 return EINVAL;
1169         if (valsize > len)
1170                 sopt->sopt_valsize = valsize = len;
1171
1172         if (sopt->sopt_td != NULL)
1173                 return (copyin(sopt->sopt_val, buf, valsize));
1174
1175         bcopy(sopt->sopt_val, buf, valsize);
1176         return 0;
1177 }
1178
1179 int
1180 sosetopt(so, sopt)
1181         struct socket *so;
1182         struct sockopt *sopt;
1183 {
1184         int     error, optval;
1185         struct  linger l;
1186         struct  timeval tv;
1187         u_long  val;
1188
1189         error = 0;
1190         if (sopt->sopt_level != SOL_SOCKET) {
1191                 if (so->so_proto && so->so_proto->pr_ctloutput) {
1192                         return (so_pr_ctloutput(so, sopt));
1193                 }
1194                 error = ENOPROTOOPT;
1195         } else {
1196                 switch (sopt->sopt_name) {
1197 #ifdef INET
1198                 case SO_ACCEPTFILTER:
1199                         error = do_setopt_accept_filter(so, sopt);
1200                         if (error)
1201                                 goto bad;
1202                         break;
1203 #endif /* INET */
1204                 case SO_LINGER:
1205                         error = sooptcopyin(sopt, &l, sizeof l, sizeof l);
1206                         if (error)
1207                                 goto bad;
1208
1209                         so->so_linger = l.l_linger;
1210                         if (l.l_onoff)
1211                                 so->so_options |= SO_LINGER;
1212                         else
1213                                 so->so_options &= ~SO_LINGER;
1214                         break;
1215
1216                 case SO_DEBUG:
1217                 case SO_KEEPALIVE:
1218                 case SO_DONTROUTE:
1219                 case SO_USELOOPBACK:
1220                 case SO_BROADCAST:
1221                 case SO_REUSEADDR:
1222                 case SO_REUSEPORT:
1223                 case SO_OOBINLINE:
1224                 case SO_TIMESTAMP:
1225                         error = sooptcopyin(sopt, &optval, sizeof optval,
1226                                             sizeof optval);
1227                         if (error)
1228                                 goto bad;
1229                         if (optval)
1230                                 so->so_options |= sopt->sopt_name;
1231                         else
1232                                 so->so_options &= ~sopt->sopt_name;
1233                         break;
1234
1235                 case SO_SNDBUF:
1236                 case SO_RCVBUF:
1237                 case SO_SNDLOWAT:
1238                 case SO_RCVLOWAT:
1239                         error = sooptcopyin(sopt, &optval, sizeof optval,
1240                                             sizeof optval);
1241                         if (error)
1242                                 goto bad;
1243
1244                         /*
1245                          * Values < 1 make no sense for any of these
1246                          * options, so disallow them.
1247                          */
1248                         if (optval < 1) {
1249                                 error = EINVAL;
1250                                 goto bad;
1251                         }
1252
1253                         switch (sopt->sopt_name) {
1254                         case SO_SNDBUF:
1255                         case SO_RCVBUF:
1256                                 if (sbreserve(sopt->sopt_name == SO_SNDBUF ?
1257                                     &so->so_snd : &so->so_rcv, (u_long)optval,
1258                                     so,
1259                                     &curproc->p_rlimit[RLIMIT_SBSIZE]) == 0) {
1260                                         error = ENOBUFS;
1261                                         goto bad;
1262                                 }
1263                                 break;
1264
1265                         /*
1266                          * Make sure the low-water is never greater than
1267                          * the high-water.
1268                          */
1269                         case SO_SNDLOWAT:
1270                                 so->so_snd.sb_lowat =
1271                                     (optval > so->so_snd.sb_hiwat) ?
1272                                     so->so_snd.sb_hiwat : optval;
1273                                 break;
1274                         case SO_RCVLOWAT:
1275                                 so->so_rcv.sb_lowat =
1276                                     (optval > so->so_rcv.sb_hiwat) ?
1277                                     so->so_rcv.sb_hiwat : optval;
1278                                 break;
1279                         }
1280                         break;
1281
1282                 case SO_SNDTIMEO:
1283                 case SO_RCVTIMEO:
1284                         error = sooptcopyin(sopt, &tv, sizeof tv,
1285                                             sizeof tv);
1286                         if (error)
1287                                 goto bad;
1288
1289                         /* assert(hz > 0); */
1290                         if (tv.tv_sec < 0 || tv.tv_sec > SHRT_MAX / hz ||
1291                             tv.tv_usec < 0 || tv.tv_usec >= 1000000) {
1292                                 error = EDOM;
1293                                 goto bad;
1294                         }
1295                         /* assert(tick > 0); */
1296                         /* assert(ULONG_MAX - SHRT_MAX >= 1000000); */
1297                         val = (u_long)(tv.tv_sec * hz) + tv.tv_usec / tick;
1298                         if (val > SHRT_MAX) {
1299                                 error = EDOM;
1300                                 goto bad;
1301                         }
1302                         if (val == 0 && tv.tv_usec != 0)
1303                                 val = 1;
1304
1305                         switch (sopt->sopt_name) {
1306                         case SO_SNDTIMEO:
1307                                 so->so_snd.sb_timeo = val;
1308                                 break;
1309                         case SO_RCVTIMEO:
1310                                 so->so_rcv.sb_timeo = val;
1311                                 break;
1312                         }
1313                         break;
1314                 default:
1315                         error = ENOPROTOOPT;
1316                         break;
1317                 }
1318                 if (error == 0 && so->so_proto && so->so_proto->pr_ctloutput) {
1319                         (void) so_pr_ctloutput(so, sopt);
1320                 }
1321         }
1322 bad:
1323         return (error);
1324 }
1325
1326 /* Helper routine for getsockopt */
1327 int
1328 sooptcopyout(struct sockopt *sopt, const void *buf, size_t len)
1329 {
1330         int     error;
1331         size_t  valsize;
1332
1333         error = 0;
1334
1335         /*
1336          * Documented get behavior is that we always return a value,
1337          * possibly truncated to fit in the user's buffer.
1338          * Traditional behavior is that we always tell the user
1339          * precisely how much we copied, rather than something useful
1340          * like the total amount we had available for her.
1341          * Note that this interface is not idempotent; the entire answer must
1342          * generated ahead of time.
1343          */
1344         valsize = min(len, sopt->sopt_valsize);
1345         sopt->sopt_valsize = valsize;
1346         if (sopt->sopt_val != 0) {
1347                 if (sopt->sopt_td != NULL)
1348                         error = copyout(buf, sopt->sopt_val, valsize);
1349                 else
1350                         bcopy(buf, sopt->sopt_val, valsize);
1351         }
1352         return error;
1353 }
1354
1355 int
1356 sogetopt(so, sopt)
1357         struct socket *so;
1358         struct sockopt *sopt;
1359 {
1360         int     error, optval;
1361         struct  linger l;
1362         struct  timeval tv;
1363 #ifdef INET
1364         struct accept_filter_arg *afap;
1365 #endif
1366
1367         error = 0;
1368         if (sopt->sopt_level != SOL_SOCKET) {
1369                 if (so->so_proto && so->so_proto->pr_ctloutput) {
1370                         return (so_pr_ctloutput(so, sopt));
1371                 } else
1372                         return (ENOPROTOOPT);
1373         } else {
1374                 switch (sopt->sopt_name) {
1375 #ifdef INET
1376                 case SO_ACCEPTFILTER:
1377                         if ((so->so_options & SO_ACCEPTCONN) == 0)
1378                                 return (EINVAL);
1379                         MALLOC(afap, struct accept_filter_arg *, sizeof(*afap),
1380                                 M_TEMP, M_WAITOK);
1381                         bzero(afap, sizeof(*afap));
1382                         if ((so->so_options & SO_ACCEPTFILTER) != 0) {
1383                                 strcpy(afap->af_name, so->so_accf->so_accept_filter->accf_name);
1384                                 if (so->so_accf->so_accept_filter_str != NULL)
1385                                         strcpy(afap->af_arg, so->so_accf->so_accept_filter_str);
1386                         }
1387                         error = sooptcopyout(sopt, afap, sizeof(*afap));
1388                         FREE(afap, M_TEMP);
1389                         break;
1390 #endif /* INET */
1391                         
1392                 case SO_LINGER:
1393                         l.l_onoff = so->so_options & SO_LINGER;
1394                         l.l_linger = so->so_linger;
1395                         error = sooptcopyout(sopt, &l, sizeof l);
1396                         break;
1397
1398                 case SO_USELOOPBACK:
1399                 case SO_DONTROUTE:
1400                 case SO_DEBUG:
1401                 case SO_KEEPALIVE:
1402                 case SO_REUSEADDR:
1403                 case SO_REUSEPORT:
1404                 case SO_BROADCAST:
1405                 case SO_OOBINLINE:
1406                 case SO_TIMESTAMP:
1407                         optval = so->so_options & sopt->sopt_name;
1408 integer:
1409                         error = sooptcopyout(sopt, &optval, sizeof optval);
1410                         break;
1411
1412                 case SO_TYPE:
1413                         optval = so->so_type;
1414                         goto integer;
1415
1416                 case SO_ERROR:
1417                         optval = so->so_error;
1418                         so->so_error = 0;
1419                         goto integer;
1420
1421                 case SO_SNDBUF:
1422                         optval = so->so_snd.sb_hiwat;
1423                         goto integer;
1424
1425                 case SO_RCVBUF:
1426                         optval = so->so_rcv.sb_hiwat;
1427                         goto integer;
1428
1429                 case SO_SNDLOWAT:
1430                         optval = so->so_snd.sb_lowat;
1431                         goto integer;
1432
1433                 case SO_RCVLOWAT:
1434                         optval = so->so_rcv.sb_lowat;
1435                         goto integer;
1436
1437                 case SO_SNDTIMEO:
1438                 case SO_RCVTIMEO:
1439                         optval = (sopt->sopt_name == SO_SNDTIMEO ?
1440                                   so->so_snd.sb_timeo : so->so_rcv.sb_timeo);
1441
1442                         tv.tv_sec = optval / hz;
1443                         tv.tv_usec = (optval % hz) * tick;
1444                         error = sooptcopyout(sopt, &tv, sizeof tv);
1445                         break;                  
1446
1447                 default:
1448                         error = ENOPROTOOPT;
1449                         break;
1450                 }
1451                 return (error);
1452         }
1453 }
1454
1455 /* XXX; prepare mbuf for (__FreeBSD__ < 3) routines. */
1456 int
1457 soopt_getm(struct sockopt *sopt, struct mbuf **mp)
1458 {
1459         struct mbuf *m, *m_prev;
1460         int sopt_size = sopt->sopt_valsize;
1461
1462         MGET(m, sopt->sopt_td ? MB_WAIT : MB_DONTWAIT, MT_DATA);
1463         if (m == 0)
1464                 return ENOBUFS;
1465         if (sopt_size > MLEN) {
1466                 MCLGET(m, sopt->sopt_td ? MB_WAIT : MB_DONTWAIT);
1467                 if ((m->m_flags & M_EXT) == 0) {
1468                         m_free(m);
1469                         return ENOBUFS;
1470                 }
1471                 m->m_len = min(MCLBYTES, sopt_size);
1472         } else {
1473                 m->m_len = min(MLEN, sopt_size);
1474         }
1475         sopt_size -= m->m_len;
1476         *mp = m;
1477         m_prev = m;
1478
1479         while (sopt_size) {
1480                 MGET(m, sopt->sopt_td ? MB_WAIT : MB_DONTWAIT, MT_DATA);
1481                 if (m == 0) {
1482                         m_freem(*mp);
1483                         return ENOBUFS;
1484                 }
1485                 if (sopt_size > MLEN) {
1486                         MCLGET(m, sopt->sopt_td ? MB_WAIT : MB_DONTWAIT);
1487                         if ((m->m_flags & M_EXT) == 0) {
1488                                 m_freem(*mp);
1489                                 return ENOBUFS;
1490                         }
1491                         m->m_len = min(MCLBYTES, sopt_size);
1492                 } else {
1493                         m->m_len = min(MLEN, sopt_size);
1494                 }
1495                 sopt_size -= m->m_len;
1496                 m_prev->m_next = m;
1497                 m_prev = m;
1498         }
1499         return 0;
1500 }
1501
1502 /* XXX; copyin sopt data into mbuf chain for (__FreeBSD__ < 3) routines. */
1503 int
1504 soopt_mcopyin(struct sockopt *sopt, struct mbuf *m)
1505 {
1506         struct mbuf *m0 = m;
1507
1508         if (sopt->sopt_val == NULL)
1509                 return 0;
1510         while (m != NULL && sopt->sopt_valsize >= m->m_len) {
1511                 if (sopt->sopt_td != NULL) {
1512                         int error;
1513
1514                         error = copyin(sopt->sopt_val, mtod(m, char *),
1515                                        m->m_len);
1516                         if (error != 0) {
1517                                 m_freem(m0);
1518                                 return(error);
1519                         }
1520                 } else
1521                         bcopy(sopt->sopt_val, mtod(m, char *), m->m_len);
1522                 sopt->sopt_valsize -= m->m_len;
1523                 (caddr_t)sopt->sopt_val += m->m_len;
1524                 m = m->m_next;
1525         }
1526         if (m != NULL) /* should be allocated enoughly at ip6_sooptmcopyin() */
1527                 panic("ip6_sooptmcopyin");
1528         return 0;
1529 }
1530
1531 /* XXX; copyout mbuf chain data into soopt for (__FreeBSD__ < 3) routines. */
1532 int
1533 soopt_mcopyout(struct sockopt *sopt, struct mbuf *m)
1534 {
1535         struct mbuf *m0 = m;
1536         size_t valsize = 0;
1537
1538         if (sopt->sopt_val == NULL)
1539                 return 0;
1540         while (m != NULL && sopt->sopt_valsize >= m->m_len) {
1541                 if (sopt->sopt_td != NULL) {
1542                         int error;
1543
1544                         error = copyout(mtod(m, char *), sopt->sopt_val,
1545                                        m->m_len);
1546                         if (error != 0) {
1547                                 m_freem(m0);
1548                                 return(error);
1549                         }
1550                 } else
1551                         bcopy(mtod(m, char *), sopt->sopt_val, m->m_len);
1552                sopt->sopt_valsize -= m->m_len;
1553                (caddr_t)sopt->sopt_val += m->m_len;
1554                valsize += m->m_len;
1555                m = m->m_next;
1556         }
1557         if (m != NULL) {
1558                 /* enough soopt buffer should be given from user-land */
1559                 m_freem(m0);
1560                 return(EINVAL);
1561         }
1562         sopt->sopt_valsize = valsize;
1563         return 0;
1564 }
1565
1566 void
1567 sohasoutofband(so)
1568         struct socket *so;
1569 {
1570         if (so->so_sigio != NULL)
1571                 pgsigio(so->so_sigio, SIGURG, 0);
1572         selwakeup(&so->so_rcv.sb_sel);
1573 }
1574
1575 int
1576 sopoll(struct socket *so, int events, struct ucred *cred, struct thread *td)
1577 {
1578         int revents = 0;
1579         int s = splnet();
1580
1581         if (events & (POLLIN | POLLRDNORM))
1582                 if (soreadable(so))
1583                         revents |= events & (POLLIN | POLLRDNORM);
1584
1585         if (events & POLLINIGNEOF)
1586                 if (so->so_rcv.sb_cc >= so->so_rcv.sb_lowat ||
1587                         !TAILQ_EMPTY(&so->so_comp) || so->so_error)
1588                         revents |= POLLINIGNEOF;
1589
1590         if (events & (POLLOUT | POLLWRNORM))
1591                 if (sowriteable(so))
1592                         revents |= events & (POLLOUT | POLLWRNORM);
1593
1594         if (events & (POLLPRI | POLLRDBAND))
1595                 if (so->so_oobmark || (so->so_state & SS_RCVATMARK))
1596                         revents |= events & (POLLPRI | POLLRDBAND);
1597
1598         if (revents == 0) {
1599                 if (events &
1600                         (POLLIN | POLLINIGNEOF | POLLPRI | POLLRDNORM |
1601                          POLLRDBAND)) {
1602                         selrecord(td, &so->so_rcv.sb_sel);
1603                         so->so_rcv.sb_flags |= SB_SEL;
1604                 }
1605
1606                 if (events & (POLLOUT | POLLWRNORM)) {
1607                         selrecord(td, &so->so_snd.sb_sel);
1608                         so->so_snd.sb_flags |= SB_SEL;
1609                 }
1610         }
1611
1612         splx(s);
1613         return (revents);
1614 }
1615
1616 int
1617 sokqfilter(struct file *fp, struct knote *kn)
1618 {
1619         struct socket *so = (struct socket *)kn->kn_fp->f_data;
1620         struct sockbuf *sb;
1621         int s;
1622
1623         switch (kn->kn_filter) {
1624         case EVFILT_READ:
1625                 if (so->so_options & SO_ACCEPTCONN)
1626                         kn->kn_fop = &solisten_filtops;
1627                 else
1628                         kn->kn_fop = &soread_filtops;
1629                 sb = &so->so_rcv;
1630                 break;
1631         case EVFILT_WRITE:
1632                 kn->kn_fop = &sowrite_filtops;
1633                 sb = &so->so_snd;
1634                 break;
1635         default:
1636                 return (1);
1637         }
1638
1639         s = splnet();
1640         SLIST_INSERT_HEAD(&sb->sb_sel.si_note, kn, kn_selnext);
1641         sb->sb_flags |= SB_KNOTE;
1642         splx(s);
1643         return (0);
1644 }
1645
1646 static void
1647 filt_sordetach(struct knote *kn)
1648 {
1649         struct socket *so = (struct socket *)kn->kn_fp->f_data;
1650         int s = splnet();
1651
1652         SLIST_REMOVE(&so->so_rcv.sb_sel.si_note, kn, knote, kn_selnext);
1653         if (SLIST_EMPTY(&so->so_rcv.sb_sel.si_note))
1654                 so->so_rcv.sb_flags &= ~SB_KNOTE;
1655         splx(s);
1656 }
1657
1658 /*ARGSUSED*/
1659 static int
1660 filt_soread(struct knote *kn, long hint)
1661 {
1662         struct socket *so = (struct socket *)kn->kn_fp->f_data;
1663
1664         kn->kn_data = so->so_rcv.sb_cc;
1665         if (so->so_state & SS_CANTRCVMORE) {
1666                 kn->kn_flags |= EV_EOF; 
1667                 kn->kn_fflags = so->so_error;
1668                 return (1);
1669         }
1670         if (so->so_error)       /* temporary udp error */
1671                 return (1);
1672         if (kn->kn_sfflags & NOTE_LOWAT)
1673                 return (kn->kn_data >= kn->kn_sdata);
1674         return (kn->kn_data >= so->so_rcv.sb_lowat);
1675 }
1676
1677 static void
1678 filt_sowdetach(struct knote *kn)
1679 {
1680         struct socket *so = (struct socket *)kn->kn_fp->f_data;
1681         int s = splnet();
1682
1683         SLIST_REMOVE(&so->so_snd.sb_sel.si_note, kn, knote, kn_selnext);
1684         if (SLIST_EMPTY(&so->so_snd.sb_sel.si_note))
1685                 so->so_snd.sb_flags &= ~SB_KNOTE;
1686         splx(s);
1687 }
1688
1689 /*ARGSUSED*/
1690 static int
1691 filt_sowrite(struct knote *kn, long hint)
1692 {
1693         struct socket *so = (struct socket *)kn->kn_fp->f_data;
1694
1695         kn->kn_data = sbspace(&so->so_snd);
1696         if (so->so_state & SS_CANTSENDMORE) {
1697                 kn->kn_flags |= EV_EOF; 
1698                 kn->kn_fflags = so->so_error;
1699                 return (1);
1700         }
1701         if (so->so_error)       /* temporary udp error */
1702                 return (1);
1703         if (((so->so_state & SS_ISCONNECTED) == 0) &&
1704             (so->so_proto->pr_flags & PR_CONNREQUIRED))
1705                 return (0);
1706         if (kn->kn_sfflags & NOTE_LOWAT)
1707                 return (kn->kn_data >= kn->kn_sdata);
1708         return (kn->kn_data >= so->so_snd.sb_lowat);
1709 }
1710
1711 /*ARGSUSED*/
1712 static int
1713 filt_solisten(struct knote *kn, long hint)
1714 {
1715         struct socket *so = (struct socket *)kn->kn_fp->f_data;
1716
1717         kn->kn_data = so->so_qlen;
1718         return (! TAILQ_EMPTY(&so->so_comp));
1719 }