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