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