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