]> CyberLeo.Net >> Repos - FreeBSD/FreeBSD.git/blob - sys/kern/uipc_socket.c
This commit was generated by cvs2svn to compensate for changes in r52894,
[FreeBSD/FreeBSD.git] / sys / kern / uipc_socket.c
1 /*
2  * Copyright (c) 1982, 1986, 1988, 1990, 1993
3  *      The Regents of the University of California.  All rights reserved.
4  *
5  * Redistribution and use in source and binary forms, with or without
6  * modification, are permitted provided that the following conditions
7  * are met:
8  * 1. Redistributions of source code must retain the above copyright
9  *    notice, this list of conditions and the following disclaimer.
10  * 2. Redistributions in binary form must reproduce the above copyright
11  *    notice, this list of conditions and the following disclaimer in the
12  *    documentation and/or other materials provided with the distribution.
13  * 3. All advertising materials mentioning features or use of this software
14  *    must display the following acknowledgement:
15  *      This product includes software developed by the University of
16  *      California, Berkeley and its contributors.
17  * 4. Neither the name of the University nor the names of its contributors
18  *    may be used to endorse or promote products derived from this software
19  *    without specific prior written permission.
20  *
21  * THIS SOFTWARE IS PROVIDED BY THE REGENTS AND CONTRIBUTORS ``AS IS'' AND
22  * ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
23  * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE
24  * ARE DISCLAIMED.  IN NO EVENT SHALL THE REGENTS OR CONTRIBUTORS BE LIABLE
25  * FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL
26  * DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS
27  * OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION)
28  * HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT
29  * LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY
30  * OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF
31  * SUCH DAMAGE.
32  *
33  *      @(#)uipc_socket.c       8.3 (Berkeley) 4/15/94
34  * $FreeBSD$
35  */
36
37 #include <sys/param.h>
38 #include <sys/systm.h>
39 #include <sys/fcntl.h>
40 #include <sys/malloc.h>
41 #include <sys/mbuf.h>
42 #include <sys/domain.h>
43 #include <sys/kernel.h>
44 #include <sys/malloc.h>
45 #include <sys/poll.h>
46 #include <sys/proc.h>
47 #include <sys/protosw.h>
48 #include <sys/socket.h>
49 #include <sys/socketvar.h>
50 #include <sys/resourcevar.h>
51 #include <sys/signalvar.h>
52 #include <sys/sysctl.h>
53 #include <sys/uio.h>
54 #include <vm/vm_zone.h>
55
56 #include <machine/limits.h>
57
58 struct  vm_zone *socket_zone;
59 so_gen_t        so_gencnt;      /* generation count for sockets */
60
61 MALLOC_DEFINE(M_SONAME, "soname", "socket name");
62 MALLOC_DEFINE(M_PCB, "pcb", "protocol control block");
63
64 SYSCTL_DECL(_kern_ipc);
65
66 static int somaxconn = SOMAXCONN;
67 SYSCTL_INT(_kern_ipc, KIPC_SOMAXCONN, somaxconn, CTLFLAG_RW, 
68     &somaxconn, 0, "Maximum pending socket connection queue size");
69
70 /*
71  * Socket operation routines.
72  * These routines are called by the routines in
73  * sys_socket.c or from a system process, and
74  * implement the semantics of socket operations by
75  * switching out to the protocol specific routines.
76  */
77
78 /*
79  * Get a socket structure from our zone, and initialize it.
80  * We don't implement `waitok' yet (see comments in uipc_domain.c).
81  * Note that it would probably be better to allocate socket
82  * and PCB at the same time, but I'm not convinced that all
83  * the protocols can be easily modified to do this.
84  */
85 struct socket *
86 soalloc(waitok)
87         int waitok;
88 {
89         struct socket *so;
90
91         so = zalloci(socket_zone);
92         if (so) {
93                 /* XXX race condition for reentrant kernel */
94                 bzero(so, sizeof *so);
95                 so->so_gencnt = ++so_gencnt;
96                 so->so_zone = socket_zone;
97         }
98         return so;
99 }
100
101 int
102 socreate(dom, aso, type, proto, p)
103         int dom;
104         struct socket **aso;
105         register int type;
106         int proto;
107         struct proc *p;
108 {
109         register struct protosw *prp;
110         register struct socket *so;
111         register int error;
112
113         if (proto)
114                 prp = pffindproto(dom, proto, type);
115         else
116                 prp = pffindtype(dom, type);
117         if (prp == 0 || prp->pr_usrreqs->pru_attach == 0)
118                 return (EPROTONOSUPPORT);
119         if (prp->pr_type != type)
120                 return (EPROTOTYPE);
121         so = soalloc(p != 0);
122         if (so == 0)
123                 return (ENOBUFS);
124
125         TAILQ_INIT(&so->so_incomp);
126         TAILQ_INIT(&so->so_comp);
127         so->so_type = type;
128         so->so_cred = p->p_ucred;
129         crhold(so->so_cred);
130         so->so_proto = prp;
131         error = (*prp->pr_usrreqs->pru_attach)(so, proto, p);
132         if (error) {
133                 so->so_state |= SS_NOFDREF;
134                 sofree(so);
135                 return (error);
136         }
137         *aso = so;
138         return (0);
139 }
140
141 int
142 sobind(so, nam, p)
143         struct socket *so;
144         struct sockaddr *nam;
145         struct proc *p;
146 {
147         int s = splnet();
148         int error;
149
150         error = (*so->so_proto->pr_usrreqs->pru_bind)(so, nam, p);
151         splx(s);
152         return (error);
153 }
154
155 void
156 sodealloc(so)
157         struct socket *so;
158 {
159
160         so->so_gencnt = ++so_gencnt;
161         if (so->so_rcv.sb_hiwat)
162                 (void)chgsbsize(so->so_cred->cr_uid,
163                     -(rlim_t)so->so_rcv.sb_hiwat);
164         if (so->so_snd.sb_hiwat)
165                 (void)chgsbsize(so->so_cred->cr_uid,
166                     -(rlim_t)so->so_snd.sb_hiwat);
167         crfree(so->so_cred);
168         zfreei(so->so_zone, so);
169 }
170
171 int
172 solisten(so, backlog, p)
173         register struct socket *so;
174         int backlog;
175         struct proc *p;
176 {
177         int s, error;
178
179         s = splnet();
180         error = (*so->so_proto->pr_usrreqs->pru_listen)(so, p);
181         if (error) {
182                 splx(s);
183                 return (error);
184         }
185         if (so->so_comp.tqh_first == NULL)
186                 so->so_options |= SO_ACCEPTCONN;
187         if (backlog < 0 || backlog > somaxconn)
188                 backlog = somaxconn;
189         so->so_qlimit = backlog;
190         splx(s);
191         return (0);
192 }
193
194 void
195 sofree(so)
196         register struct socket *so;
197 {
198         struct socket *head = so->so_head;
199
200         if (so->so_pcb || (so->so_state & SS_NOFDREF) == 0)
201                 return;
202         if (head != NULL) {
203                 if (so->so_state & SS_INCOMP) {
204                         TAILQ_REMOVE(&head->so_incomp, so, so_list);
205                         head->so_incqlen--;
206                 } else if (so->so_state & SS_COMP) {
207                         /*
208                          * We must not decommission a socket that's
209                          * on the accept(2) queue.  If we do, then
210                          * accept(2) may hang after select(2) indicated
211                          * that the listening socket was ready.
212                          */
213                         return;
214                 } else {
215                         panic("sofree: not queued");
216                 }
217                 head->so_qlen--;
218                 so->so_state &= ~SS_INCOMP;
219                 so->so_head = NULL;
220         }
221         sbrelease(&so->so_snd, so);
222         sorflush(so);
223         sodealloc(so);
224 }
225
226 /*
227  * Close a socket on last file table reference removal.
228  * Initiate disconnect if connected.
229  * Free socket when disconnect complete.
230  */
231 int
232 soclose(so)
233         register struct socket *so;
234 {
235         int s = splnet();               /* conservative */
236         int error = 0;
237
238         funsetown(so->so_sigio);
239         if (so->so_options & SO_ACCEPTCONN) {
240                 struct socket *sp, *sonext;
241
242                 for (sp = so->so_incomp.tqh_first; sp != NULL; sp = sonext) {
243                         sonext = sp->so_list.tqe_next;
244                         (void) soabort(sp);
245                 }
246                 for (sp = so->so_comp.tqh_first; sp != NULL; sp = sonext) {
247                         sonext = sp->so_list.tqe_next;
248                         /* Dequeue from so_comp since sofree() won't do it */
249                         TAILQ_REMOVE(&so->so_comp, sp, so_list);
250                         so->so_qlen--;
251                         sp->so_state &= ~SS_COMP;
252                         sp->so_head = NULL;
253                         (void) soabort(sp);
254                 }
255         }
256         if (so->so_pcb == 0)
257                 goto discard;
258         if (so->so_state & SS_ISCONNECTED) {
259                 if ((so->so_state & SS_ISDISCONNECTING) == 0) {
260                         error = sodisconnect(so);
261                         if (error)
262                                 goto drop;
263                 }
264                 if (so->so_options & SO_LINGER) {
265                         if ((so->so_state & SS_ISDISCONNECTING) &&
266                             (so->so_state & SS_NBIO))
267                                 goto drop;
268                         while (so->so_state & SS_ISCONNECTED) {
269                                 error = tsleep((caddr_t)&so->so_timeo,
270                                     PSOCK | PCATCH, "soclos", so->so_linger * hz);
271                                 if (error)
272                                         break;
273                         }
274                 }
275         }
276 drop:
277         if (so->so_pcb) {
278                 int error2 = (*so->so_proto->pr_usrreqs->pru_detach)(so);
279                 if (error == 0)
280                         error = error2;
281         }
282 discard:
283         if (so->so_state & SS_NOFDREF)
284                 panic("soclose: NOFDREF");
285         so->so_state |= SS_NOFDREF;
286         sofree(so);
287         splx(s);
288         return (error);
289 }
290
291 /*
292  * Must be called at splnet...
293  */
294 int
295 soabort(so)
296         struct socket *so;
297 {
298
299         return (*so->so_proto->pr_usrreqs->pru_abort)(so);
300 }
301
302 int
303 soaccept(so, nam)
304         register struct socket *so;
305         struct sockaddr **nam;
306 {
307         int s = splnet();
308         int error;
309
310         if ((so->so_state & SS_NOFDREF) == 0)
311                 panic("soaccept: !NOFDREF");
312         so->so_state &= ~SS_NOFDREF;
313         if ((so->so_state & SS_ISDISCONNECTED) == 0)
314                 error = (*so->so_proto->pr_usrreqs->pru_accept)(so, nam);
315         else {
316                 if (nam)
317                         *nam = 0;
318                 error = 0;
319         }
320         splx(s);
321         return (error);
322 }
323
324 int
325 soconnect(so, nam, p)
326         register struct socket *so;
327         struct sockaddr *nam;
328         struct proc *p;
329 {
330         int s;
331         int error;
332
333         if (so->so_options & SO_ACCEPTCONN)
334                 return (EOPNOTSUPP);
335         s = splnet();
336         /*
337          * If protocol is connection-based, can only connect once.
338          * Otherwise, if connected, try to disconnect first.
339          * This allows user to disconnect by connecting to, e.g.,
340          * a null address.
341          */
342         if (so->so_state & (SS_ISCONNECTED|SS_ISCONNECTING) &&
343             ((so->so_proto->pr_flags & PR_CONNREQUIRED) ||
344             (error = sodisconnect(so))))
345                 error = EISCONN;
346         else
347                 error = (*so->so_proto->pr_usrreqs->pru_connect)(so, nam, p);
348         splx(s);
349         return (error);
350 }
351
352 int
353 soconnect2(so1, so2)
354         register struct socket *so1;
355         struct socket *so2;
356 {
357         int s = splnet();
358         int error;
359
360         error = (*so1->so_proto->pr_usrreqs->pru_connect2)(so1, so2);
361         splx(s);
362         return (error);
363 }
364
365 int
366 sodisconnect(so)
367         register struct socket *so;
368 {
369         int s = splnet();
370         int error;
371
372         if ((so->so_state & SS_ISCONNECTED) == 0) {
373                 error = ENOTCONN;
374                 goto bad;
375         }
376         if (so->so_state & SS_ISDISCONNECTING) {
377                 error = EALREADY;
378                 goto bad;
379         }
380         error = (*so->so_proto->pr_usrreqs->pru_disconnect)(so);
381 bad:
382         splx(s);
383         return (error);
384 }
385
386 #define SBLOCKWAIT(f)   (((f) & MSG_DONTWAIT) ? M_NOWAIT : M_WAITOK)
387 /*
388  * Send on a socket.
389  * If send must go all at once and message is larger than
390  * send buffering, then hard error.
391  * Lock against other senders.
392  * If must go all at once and not enough room now, then
393  * inform user that this would block and do nothing.
394  * Otherwise, if nonblocking, send as much as possible.
395  * The data to be sent is described by "uio" if nonzero,
396  * otherwise by the mbuf chain "top" (which must be null
397  * if uio is not).  Data provided in mbuf chain must be small
398  * enough to send all at once.
399  *
400  * Returns nonzero on error, timeout or signal; callers
401  * must check for short counts if EINTR/ERESTART are returned.
402  * Data and control buffers are freed on return.
403  */
404 int
405 sosend(so, addr, uio, top, control, flags, p)
406         register struct socket *so;
407         struct sockaddr *addr;
408         struct uio *uio;
409         struct mbuf *top;
410         struct mbuf *control;
411         int flags;
412         struct proc *p;
413 {
414         struct mbuf **mp;
415         register struct mbuf *m;
416         register long space, len, resid;
417         int clen = 0, error, s, dontroute, mlen;
418         int atomic = sosendallatonce(so) || top;
419
420         if (uio)
421                 resid = uio->uio_resid;
422         else
423                 resid = top->m_pkthdr.len;
424         /*
425          * In theory resid should be unsigned.
426          * However, space must be signed, as it might be less than 0
427          * if we over-committed, and we must use a signed comparison
428          * of space and resid.  On the other hand, a negative resid
429          * causes us to loop sending 0-length segments to the protocol.
430          *
431          * Also check to make sure that MSG_EOR isn't used on SOCK_STREAM
432          * type sockets since that's an error.
433          */
434         if (resid < 0 || (so->so_type == SOCK_STREAM && (flags & MSG_EOR))) {
435                 error = EINVAL;
436                 goto out;
437         }
438
439         dontroute =
440             (flags & MSG_DONTROUTE) && (so->so_options & SO_DONTROUTE) == 0 &&
441             (so->so_proto->pr_flags & PR_ATOMIC);
442         if (p)
443                 p->p_stats->p_ru.ru_msgsnd++;
444         if (control)
445                 clen = control->m_len;
446 #define snderr(errno)   { error = errno; splx(s); goto release; }
447
448 restart:
449         error = sblock(&so->so_snd, SBLOCKWAIT(flags));
450         if (error)
451                 goto out;
452         do {
453                 s = splnet();
454                 if (so->so_state & SS_CANTSENDMORE)
455                         snderr(EPIPE);
456                 if (so->so_error) {
457                         error = so->so_error;
458                         so->so_error = 0;
459                         splx(s);
460                         goto release;
461                 }
462                 if ((so->so_state & SS_ISCONNECTED) == 0) {
463                         /*
464                          * `sendto' and `sendmsg' is allowed on a connection-
465                          * based socket if it supports implied connect.
466                          * Return ENOTCONN if not connected and no address is
467                          * supplied.
468                          */
469                         if ((so->so_proto->pr_flags & PR_CONNREQUIRED) &&
470                             (so->so_proto->pr_flags & PR_IMPLOPCL) == 0) {
471                                 if ((so->so_state & SS_ISCONFIRMING) == 0 &&
472                                     !(resid == 0 && clen != 0))
473                                         snderr(ENOTCONN);
474                         } else if (addr == 0)
475                             snderr(so->so_proto->pr_flags & PR_CONNREQUIRED ?
476                                    ENOTCONN : EDESTADDRREQ);
477                 }
478                 space = sbspace(&so->so_snd);
479                 if (flags & MSG_OOB)
480                         space += 1024;
481                 if ((atomic && resid > so->so_snd.sb_hiwat) ||
482                     clen > so->so_snd.sb_hiwat)
483                         snderr(EMSGSIZE);
484                 if (space < resid + clen && uio &&
485                     (atomic || space < so->so_snd.sb_lowat || space < clen)) {
486                         if (so->so_state & SS_NBIO)
487                                 snderr(EWOULDBLOCK);
488                         sbunlock(&so->so_snd);
489                         error = sbwait(&so->so_snd);
490                         splx(s);
491                         if (error)
492                                 goto out;
493                         goto restart;
494                 }
495                 splx(s);
496                 mp = &top;
497                 space -= clen;
498                 do {
499                     if (uio == NULL) {
500                         /*
501                          * Data is prepackaged in "top".
502                          */
503                         resid = 0;
504                         if (flags & MSG_EOR)
505                                 top->m_flags |= M_EOR;
506                     } else do {
507                         if (top == 0) {
508                                 MGETHDR(m, M_WAIT, MT_DATA);
509                                 mlen = MHLEN;
510                                 m->m_pkthdr.len = 0;
511                                 m->m_pkthdr.rcvif = (struct ifnet *)0;
512                         } else {
513                                 MGET(m, M_WAIT, MT_DATA);
514                                 mlen = MLEN;
515                         }
516                         if (resid >= MINCLSIZE) {
517                                 MCLGET(m, M_WAIT);
518                                 if ((m->m_flags & M_EXT) == 0)
519                                         goto nopages;
520                                 mlen = MCLBYTES;
521                                 len = min(min(mlen, resid), space);
522                         } else {
523 nopages:
524                                 len = min(min(mlen, resid), space);
525                                 /*
526                                  * For datagram protocols, leave room
527                                  * for protocol headers in first mbuf.
528                                  */
529                                 if (atomic && top == 0 && len < mlen)
530                                         MH_ALIGN(m, len);
531                         }
532                         space -= len;
533                         error = uiomove(mtod(m, caddr_t), (int)len, uio);
534                         resid = uio->uio_resid;
535                         m->m_len = len;
536                         *mp = m;
537                         top->m_pkthdr.len += len;
538                         if (error)
539                                 goto release;
540                         mp = &m->m_next;
541                         if (resid <= 0) {
542                                 if (flags & MSG_EOR)
543                                         top->m_flags |= M_EOR;
544                                 break;
545                         }
546                     } while (space > 0 && atomic);
547                     if (dontroute)
548                             so->so_options |= SO_DONTROUTE;
549                     s = splnet();                               /* XXX */
550                     /*
551                      * XXX all the SS_CANTSENDMORE checks previously
552                      * done could be out of date.  We could have recieved
553                      * a reset packet in an interrupt or maybe we slept
554                      * while doing page faults in uiomove() etc. We could
555                      * probably recheck again inside the splnet() protection
556                      * here, but there are probably other places that this
557                      * also happens.  We must rethink this.
558                      */
559                     error = (*so->so_proto->pr_usrreqs->pru_send)(so,
560                         (flags & MSG_OOB) ? PRUS_OOB :
561                         /*
562                          * If the user set MSG_EOF, the protocol
563                          * understands this flag and nothing left to
564                          * send then use PRU_SEND_EOF instead of PRU_SEND.
565                          */
566                         ((flags & MSG_EOF) &&
567                          (so->so_proto->pr_flags & PR_IMPLOPCL) &&
568                          (resid <= 0)) ?
569                                 PRUS_EOF :
570                         /* If there is more to send set PRUS_MORETOCOME */
571                         (resid > 0 && space > 0) ? PRUS_MORETOCOME : 0,
572                         top, addr, control, p);
573                     splx(s);
574                     if (dontroute)
575                             so->so_options &= ~SO_DONTROUTE;
576                     clen = 0;
577                     control = 0;
578                     top = 0;
579                     mp = &top;
580                     if (error)
581                         goto release;
582                 } while (resid && space > 0);
583         } while (resid);
584
585 release:
586         sbunlock(&so->so_snd);
587 out:
588         if (top)
589                 m_freem(top);
590         if (control)
591                 m_freem(control);
592         return (error);
593 }
594
595 /*
596  * Implement receive operations on a socket.
597  * We depend on the way that records are added to the sockbuf
598  * by sbappend*.  In particular, each record (mbufs linked through m_next)
599  * must begin with an address if the protocol so specifies,
600  * followed by an optional mbuf or mbufs containing ancillary data,
601  * and then zero or more mbufs of data.
602  * In order to avoid blocking network interrupts for the entire time here,
603  * we splx() while doing the actual copy to user space.
604  * Although the sockbuf is locked, new data may still be appended,
605  * and thus we must maintain consistency of the sockbuf during that time.
606  *
607  * The caller may receive the data as a single mbuf chain by supplying
608  * an mbuf **mp0 for use in returning the chain.  The uio is then used
609  * only for the count in uio_resid.
610  */
611 int
612 soreceive(so, psa, uio, mp0, controlp, flagsp)
613         register struct socket *so;
614         struct sockaddr **psa;
615         struct uio *uio;
616         struct mbuf **mp0;
617         struct mbuf **controlp;
618         int *flagsp;
619 {
620         register struct mbuf *m, **mp;
621         register int flags, len, error, s, offset;
622         struct protosw *pr = so->so_proto;
623         struct mbuf *nextrecord;
624         int moff, type = 0;
625         int orig_resid = uio->uio_resid;
626
627         mp = mp0;
628         if (psa)
629                 *psa = 0;
630         if (controlp)
631                 *controlp = 0;
632         if (flagsp)
633                 flags = *flagsp &~ MSG_EOR;
634         else
635                 flags = 0;
636         if (flags & MSG_OOB) {
637                 m = m_get(M_WAIT, MT_DATA);
638                 error = (*pr->pr_usrreqs->pru_rcvoob)(so, m, flags & MSG_PEEK);
639                 if (error)
640                         goto bad;
641                 do {
642                         error = uiomove(mtod(m, caddr_t),
643                             (int) min(uio->uio_resid, m->m_len), uio);
644                         m = m_free(m);
645                 } while (uio->uio_resid && error == 0 && m);
646 bad:
647                 if (m)
648                         m_freem(m);
649                 return (error);
650         }
651         if (mp)
652                 *mp = (struct mbuf *)0;
653         if (so->so_state & SS_ISCONFIRMING && uio->uio_resid)
654                 (*pr->pr_usrreqs->pru_rcvd)(so, 0);
655
656 restart:
657         error = sblock(&so->so_rcv, SBLOCKWAIT(flags));
658         if (error)
659                 return (error);
660         s = splnet();
661
662         m = so->so_rcv.sb_mb;
663         /*
664          * If we have less data than requested, block awaiting more
665          * (subject to any timeout) if:
666          *   1. the current count is less than the low water mark, or
667          *   2. MSG_WAITALL is set, and it is possible to do the entire
668          *      receive operation at once if we block (resid <= hiwat).
669          *   3. MSG_DONTWAIT is not set
670          * If MSG_WAITALL is set but resid is larger than the receive buffer,
671          * we have to do the receive in sections, and thus risk returning
672          * a short count if a timeout or signal occurs after we start.
673          */
674         if (m == 0 || (((flags & MSG_DONTWAIT) == 0 &&
675             so->so_rcv.sb_cc < uio->uio_resid) &&
676             (so->so_rcv.sb_cc < so->so_rcv.sb_lowat ||
677             ((flags & MSG_WAITALL) && uio->uio_resid <= so->so_rcv.sb_hiwat)) &&
678             m->m_nextpkt == 0 && (pr->pr_flags & PR_ATOMIC) == 0)) {
679                 KASSERT(m != 0 || !so->so_rcv.sb_cc, ("receive 1"));
680                 if (so->so_error) {
681                         if (m)
682                                 goto dontblock;
683                         error = so->so_error;
684                         if ((flags & MSG_PEEK) == 0)
685                                 so->so_error = 0;
686                         goto release;
687                 }
688                 if (so->so_state & SS_CANTRCVMORE) {
689                         if (m)
690                                 goto dontblock;
691                         else
692                                 goto release;
693                 }
694                 for (; m; m = m->m_next)
695                         if (m->m_type == MT_OOBDATA  || (m->m_flags & M_EOR)) {
696                                 m = so->so_rcv.sb_mb;
697                                 goto dontblock;
698                         }
699                 if ((so->so_state & (SS_ISCONNECTED|SS_ISCONNECTING)) == 0 &&
700                     (so->so_proto->pr_flags & PR_CONNREQUIRED)) {
701                         error = ENOTCONN;
702                         goto release;
703                 }
704                 if (uio->uio_resid == 0)
705                         goto release;
706                 if ((so->so_state & SS_NBIO) || (flags & MSG_DONTWAIT)) {
707                         error = EWOULDBLOCK;
708                         goto release;
709                 }
710                 sbunlock(&so->so_rcv);
711                 error = sbwait(&so->so_rcv);
712                 splx(s);
713                 if (error)
714                         return (error);
715                 goto restart;
716         }
717 dontblock:
718         if (uio->uio_procp)
719                 uio->uio_procp->p_stats->p_ru.ru_msgrcv++;
720         nextrecord = m->m_nextpkt;
721         if (pr->pr_flags & PR_ADDR) {
722                 KASSERT(m->m_type == MT_SONAME, ("receive 1a"));
723                 orig_resid = 0;
724                 if (psa)
725                         *psa = dup_sockaddr(mtod(m, struct sockaddr *),
726                                             mp0 == 0);
727                 if (flags & MSG_PEEK) {
728                         m = m->m_next;
729                 } else {
730                         sbfree(&so->so_rcv, m);
731                         MFREE(m, so->so_rcv.sb_mb);
732                         m = so->so_rcv.sb_mb;
733                 }
734         }
735         while (m && m->m_type == MT_CONTROL && error == 0) {
736                 if (flags & MSG_PEEK) {
737                         if (controlp)
738                                 *controlp = m_copy(m, 0, m->m_len);
739                         m = m->m_next;
740                 } else {
741                         sbfree(&so->so_rcv, m);
742                         if (controlp) {
743                                 if (pr->pr_domain->dom_externalize &&
744                                     mtod(m, struct cmsghdr *)->cmsg_type ==
745                                     SCM_RIGHTS)
746                                    error = (*pr->pr_domain->dom_externalize)(m);
747                                 *controlp = m;
748                                 so->so_rcv.sb_mb = m->m_next;
749                                 m->m_next = 0;
750                                 m = so->so_rcv.sb_mb;
751                         } else {
752                                 MFREE(m, so->so_rcv.sb_mb);
753                                 m = so->so_rcv.sb_mb;
754                         }
755                 }
756                 if (controlp) {
757                         orig_resid = 0;
758                         controlp = &(*controlp)->m_next;
759                 }
760         }
761         if (m) {
762                 if ((flags & MSG_PEEK) == 0)
763                         m->m_nextpkt = nextrecord;
764                 type = m->m_type;
765                 if (type == MT_OOBDATA)
766                         flags |= MSG_OOB;
767         }
768         moff = 0;
769         offset = 0;
770         while (m && uio->uio_resid > 0 && error == 0) {
771                 if (m->m_type == MT_OOBDATA) {
772                         if (type != MT_OOBDATA)
773                                 break;
774                 } else if (type == MT_OOBDATA)
775                         break;
776                 else
777                     KASSERT(m->m_type == MT_DATA || m->m_type == MT_HEADER,
778                         ("receive 3"));
779                 so->so_state &= ~SS_RCVATMARK;
780                 len = uio->uio_resid;
781                 if (so->so_oobmark && len > so->so_oobmark - offset)
782                         len = so->so_oobmark - offset;
783                 if (len > m->m_len - moff)
784                         len = m->m_len - moff;
785                 /*
786                  * If mp is set, just pass back the mbufs.
787                  * Otherwise copy them out via the uio, then free.
788                  * Sockbuf must be consistent here (points to current mbuf,
789                  * it points to next record) when we drop priority;
790                  * we must note any additions to the sockbuf when we
791                  * block interrupts again.
792                  */
793                 if (mp == 0) {
794                         splx(s);
795                         error = uiomove(mtod(m, caddr_t) + moff, (int)len, uio);
796                         s = splnet();
797                         if (error)
798                                 goto release;
799                 } else
800                         uio->uio_resid -= len;
801                 if (len == m->m_len - moff) {
802                         if (m->m_flags & M_EOR)
803                                 flags |= MSG_EOR;
804                         if (flags & MSG_PEEK) {
805                                 m = m->m_next;
806                                 moff = 0;
807                         } else {
808                                 nextrecord = m->m_nextpkt;
809                                 sbfree(&so->so_rcv, m);
810                                 if (mp) {
811                                         *mp = m;
812                                         mp = &m->m_next;
813                                         so->so_rcv.sb_mb = m = m->m_next;
814                                         *mp = (struct mbuf *)0;
815                                 } else {
816                                         MFREE(m, so->so_rcv.sb_mb);
817                                         m = so->so_rcv.sb_mb;
818                                 }
819                                 if (m)
820                                         m->m_nextpkt = nextrecord;
821                         }
822                 } else {
823                         if (flags & MSG_PEEK)
824                                 moff += len;
825                         else {
826                                 if (mp)
827                                         *mp = m_copym(m, 0, len, M_WAIT);
828                                 m->m_data += len;
829                                 m->m_len -= len;
830                                 so->so_rcv.sb_cc -= len;
831                         }
832                 }
833                 if (so->so_oobmark) {
834                         if ((flags & MSG_PEEK) == 0) {
835                                 so->so_oobmark -= len;
836                                 if (so->so_oobmark == 0) {
837                                         so->so_state |= SS_RCVATMARK;
838                                         break;
839                                 }
840                         } else {
841                                 offset += len;
842                                 if (offset == so->so_oobmark)
843                                         break;
844                         }
845                 }
846                 if (flags & MSG_EOR)
847                         break;
848                 /*
849                  * If the MSG_WAITALL flag is set (for non-atomic socket),
850                  * we must not quit until "uio->uio_resid == 0" or an error
851                  * termination.  If a signal/timeout occurs, return
852                  * with a short count but without error.
853                  * Keep sockbuf locked against other readers.
854                  */
855                 while (flags & MSG_WAITALL && m == 0 && uio->uio_resid > 0 &&
856                     !sosendallatonce(so) && !nextrecord) {
857                         if (so->so_error || so->so_state & SS_CANTRCVMORE)
858                                 break;
859                         error = sbwait(&so->so_rcv);
860                         if (error) {
861                                 sbunlock(&so->so_rcv);
862                                 splx(s);
863                                 return (0);
864                         }
865                         m = so->so_rcv.sb_mb;
866                         if (m)
867                                 nextrecord = m->m_nextpkt;
868                 }
869         }
870
871         if (m && pr->pr_flags & PR_ATOMIC) {
872                 flags |= MSG_TRUNC;
873                 if ((flags & MSG_PEEK) == 0)
874                         (void) sbdroprecord(&so->so_rcv);
875         }
876         if ((flags & MSG_PEEK) == 0) {
877                 if (m == 0)
878                         so->so_rcv.sb_mb = nextrecord;
879                 if (pr->pr_flags & PR_WANTRCVD && so->so_pcb)
880                         (*pr->pr_usrreqs->pru_rcvd)(so, flags);
881         }
882         if (orig_resid == uio->uio_resid && orig_resid &&
883             (flags & MSG_EOR) == 0 && (so->so_state & SS_CANTRCVMORE) == 0) {
884                 sbunlock(&so->so_rcv);
885                 splx(s);
886                 goto restart;
887         }
888
889         if (flagsp)
890                 *flagsp |= flags;
891 release:
892         sbunlock(&so->so_rcv);
893         splx(s);
894         return (error);
895 }
896
897 int
898 soshutdown(so, how)
899         register struct socket *so;
900         register int how;
901 {
902         register struct protosw *pr = so->so_proto;
903
904         how++;
905         if (how & FREAD)
906                 sorflush(so);
907         if (how & FWRITE)
908                 return ((*pr->pr_usrreqs->pru_shutdown)(so));
909         return (0);
910 }
911
912 void
913 sorflush(so)
914         register struct socket *so;
915 {
916         register struct sockbuf *sb = &so->so_rcv;
917         register struct protosw *pr = so->so_proto;
918         register int s;
919         struct sockbuf asb;
920
921         sb->sb_flags |= SB_NOINTR;
922         (void) sblock(sb, M_WAITOK);
923         s = splimp();
924         socantrcvmore(so);
925         sbunlock(sb);
926         asb = *sb;
927         bzero((caddr_t)sb, sizeof (*sb));
928         splx(s);
929         if (pr->pr_flags & PR_RIGHTS && pr->pr_domain->dom_dispose)
930                 (*pr->pr_domain->dom_dispose)(asb.sb_mb);
931         sbrelease(&asb, so);
932 }
933
934 /*
935  * Perhaps this routine, and sooptcopyout(), below, ought to come in
936  * an additional variant to handle the case where the option value needs
937  * to be some kind of integer, but not a specific size.
938  * In addition to their use here, these functions are also called by the
939  * protocol-level pr_ctloutput() routines.
940  */
941 int
942 sooptcopyin(sopt, buf, len, minlen)
943         struct  sockopt *sopt;
944         void    *buf;
945         size_t  len;
946         size_t  minlen;
947 {
948         size_t  valsize;
949
950         /*
951          * If the user gives us more than we wanted, we ignore it,
952          * but if we don't get the minimum length the caller
953          * wants, we return EINVAL.  On success, sopt->sopt_valsize
954          * is set to however much we actually retrieved.
955          */
956         if ((valsize = sopt->sopt_valsize) < minlen)
957                 return EINVAL;
958         if (valsize > len)
959                 sopt->sopt_valsize = valsize = len;
960
961         if (sopt->sopt_p != 0)
962                 return (copyin(sopt->sopt_val, buf, valsize));
963
964         bcopy(sopt->sopt_val, buf, valsize);
965         return 0;
966 }
967
968 int
969 sosetopt(so, sopt)
970         struct socket *so;
971         struct sockopt *sopt;
972 {
973         int     error, optval;
974         struct  linger l;
975         struct  timeval tv;
976         u_long  val;
977
978         error = 0;
979         if (sopt->sopt_level != SOL_SOCKET) {
980                 if (so->so_proto && so->so_proto->pr_ctloutput)
981                         return ((*so->so_proto->pr_ctloutput)
982                                   (so, sopt));
983                 error = ENOPROTOOPT;
984         } else {
985                 switch (sopt->sopt_name) {
986                 case SO_LINGER:
987                         error = sooptcopyin(sopt, &l, sizeof l, sizeof l);
988                         if (error)
989                                 goto bad;
990
991                         so->so_linger = l.l_linger;
992                         if (l.l_onoff)
993                                 so->so_options |= SO_LINGER;
994                         else
995                                 so->so_options &= ~SO_LINGER;
996                         break;
997
998                 case SO_DEBUG:
999                 case SO_KEEPALIVE:
1000                 case SO_DONTROUTE:
1001                 case SO_USELOOPBACK:
1002                 case SO_BROADCAST:
1003                 case SO_REUSEADDR:
1004                 case SO_REUSEPORT:
1005                 case SO_OOBINLINE:
1006                 case SO_TIMESTAMP:
1007                         error = sooptcopyin(sopt, &optval, sizeof optval,
1008                                             sizeof optval);
1009                         if (error)
1010                                 goto bad;
1011                         if (optval)
1012                                 so->so_options |= sopt->sopt_name;
1013                         else
1014                                 so->so_options &= ~sopt->sopt_name;
1015                         break;
1016
1017                 case SO_SNDBUF:
1018                 case SO_RCVBUF:
1019                 case SO_SNDLOWAT:
1020                 case SO_RCVLOWAT:
1021                         error = sooptcopyin(sopt, &optval, sizeof optval,
1022                                             sizeof optval);
1023                         if (error)
1024                                 goto bad;
1025
1026                         /*
1027                          * Values < 1 make no sense for any of these
1028                          * options, so disallow them.
1029                          */
1030                         if (optval < 1) {
1031                                 error = EINVAL;
1032                                 goto bad;
1033                         }
1034
1035                         switch (sopt->sopt_name) {
1036                         case SO_SNDBUF:
1037                         case SO_RCVBUF:
1038                                 if (sbreserve(sopt->sopt_name == SO_SNDBUF ?
1039                                     &so->so_snd : &so->so_rcv, (u_long)optval,
1040                                     so, curproc) == 0) {
1041                                         error = ENOBUFS;
1042                                         goto bad;
1043                                 }
1044                                 break;
1045
1046                         /*
1047                          * Make sure the low-water is never greater than
1048                          * the high-water.
1049                          */
1050                         case SO_SNDLOWAT:
1051                                 so->so_snd.sb_lowat =
1052                                     (optval > so->so_snd.sb_hiwat) ?
1053                                     so->so_snd.sb_hiwat : optval;
1054                                 break;
1055                         case SO_RCVLOWAT:
1056                                 so->so_rcv.sb_lowat =
1057                                     (optval > so->so_rcv.sb_hiwat) ?
1058                                     so->so_rcv.sb_hiwat : optval;
1059                                 break;
1060                         }
1061                         break;
1062
1063                 case SO_SNDTIMEO:
1064                 case SO_RCVTIMEO:
1065                         error = sooptcopyin(sopt, &tv, sizeof tv,
1066                                             sizeof tv);
1067                         if (error)
1068                                 goto bad;
1069
1070                         /* assert(hz > 0); */
1071                         if (tv.tv_sec < 0 || tv.tv_sec > SHRT_MAX / hz ||
1072                             tv.tv_usec < 0 || tv.tv_usec >= 1000000) {
1073                                 error = EDOM;
1074                                 goto bad;
1075                         }
1076                         /* assert(tick > 0); */
1077                         /* assert(ULONG_MAX - SHRT_MAX >= 1000000); */
1078                         val = (u_long)(tv.tv_sec * hz) + tv.tv_usec / tick;
1079                         if (val > SHRT_MAX) {
1080                                 error = EDOM;
1081                                 goto bad;
1082                         }
1083
1084                         switch (sopt->sopt_name) {
1085                         case SO_SNDTIMEO:
1086                                 so->so_snd.sb_timeo = val;
1087                                 break;
1088                         case SO_RCVTIMEO:
1089                                 so->so_rcv.sb_timeo = val;
1090                                 break;
1091                         }
1092                         break;
1093
1094                 default:
1095                         error = ENOPROTOOPT;
1096                         break;
1097                 }
1098                 if (error == 0 && so->so_proto && so->so_proto->pr_ctloutput) {
1099                         (void) ((*so->so_proto->pr_ctloutput)
1100                                   (so, sopt));
1101                 }
1102         }
1103 bad:
1104         return (error);
1105 }
1106
1107 /* Helper routine for getsockopt */
1108 int
1109 sooptcopyout(sopt, buf, len)
1110         struct  sockopt *sopt;
1111         void    *buf;
1112         size_t  len;
1113 {
1114         int     error;
1115         size_t  valsize;
1116
1117         error = 0;
1118
1119         /*
1120          * Documented get behavior is that we always return a value,
1121          * possibly truncated to fit in the user's buffer.
1122          * Traditional behavior is that we always tell the user
1123          * precisely how much we copied, rather than something useful
1124          * like the total amount we had available for her.
1125          * Note that this interface is not idempotent; the entire answer must
1126          * generated ahead of time.
1127          */
1128         valsize = min(len, sopt->sopt_valsize);
1129         sopt->sopt_valsize = valsize;
1130         if (sopt->sopt_val != 0) {
1131                 if (sopt->sopt_p != 0)
1132                         error = copyout(buf, sopt->sopt_val, valsize);
1133                 else
1134                         bcopy(buf, sopt->sopt_val, valsize);
1135         }
1136         return error;
1137 }
1138
1139 int
1140 sogetopt(so, sopt)
1141         struct socket *so;
1142         struct sockopt *sopt;
1143 {
1144         int     error, optval;
1145         struct  linger l;
1146         struct  timeval tv;
1147
1148         error = 0;
1149         if (sopt->sopt_level != SOL_SOCKET) {
1150                 if (so->so_proto && so->so_proto->pr_ctloutput) {
1151                         return ((*so->so_proto->pr_ctloutput)
1152                                   (so, sopt));
1153                 } else
1154                         return (ENOPROTOOPT);
1155         } else {
1156                 switch (sopt->sopt_name) {
1157                 case SO_LINGER:
1158                         l.l_onoff = so->so_options & SO_LINGER;
1159                         l.l_linger = so->so_linger;
1160                         error = sooptcopyout(sopt, &l, sizeof l);
1161                         break;
1162
1163                 case SO_USELOOPBACK:
1164                 case SO_DONTROUTE:
1165                 case SO_DEBUG:
1166                 case SO_KEEPALIVE:
1167                 case SO_REUSEADDR:
1168                 case SO_REUSEPORT:
1169                 case SO_BROADCAST:
1170                 case SO_OOBINLINE:
1171                 case SO_TIMESTAMP:
1172                         optval = so->so_options & sopt->sopt_name;
1173 integer:
1174                         error = sooptcopyout(sopt, &optval, sizeof optval);
1175                         break;
1176
1177                 case SO_TYPE:
1178                         optval = so->so_type;
1179                         goto integer;
1180
1181                 case SO_ERROR:
1182                         optval = so->so_error;
1183                         so->so_error = 0;
1184                         goto integer;
1185
1186                 case SO_SNDBUF:
1187                         optval = so->so_snd.sb_hiwat;
1188                         goto integer;
1189
1190                 case SO_RCVBUF:
1191                         optval = so->so_rcv.sb_hiwat;
1192                         goto integer;
1193
1194                 case SO_SNDLOWAT:
1195                         optval = so->so_snd.sb_lowat;
1196                         goto integer;
1197
1198                 case SO_RCVLOWAT:
1199                         optval = so->so_rcv.sb_lowat;
1200                         goto integer;
1201
1202                 case SO_SNDTIMEO:
1203                 case SO_RCVTIMEO:
1204                         optval = (sopt->sopt_name == SO_SNDTIMEO ?
1205                                   so->so_snd.sb_timeo : so->so_rcv.sb_timeo);
1206
1207                         tv.tv_sec = optval / hz;
1208                         tv.tv_usec = (optval % hz) * tick;
1209                         error = sooptcopyout(sopt, &tv, sizeof tv);
1210                         break;                  
1211
1212                 default:
1213                         error = ENOPROTOOPT;
1214                         break;
1215                 }
1216                 return (error);
1217         }
1218 }
1219
1220 void
1221 sohasoutofband(so)
1222         register struct socket *so;
1223 {
1224         if (so->so_sigio != NULL)
1225                 pgsigio(so->so_sigio, SIGURG, 0);
1226         selwakeup(&so->so_rcv.sb_sel);
1227 }
1228
1229 int
1230 sopoll(struct socket *so, int events, struct ucred *cred, struct proc *p)
1231 {
1232         int revents = 0;
1233         int s = splnet();
1234
1235         if (events & (POLLIN | POLLRDNORM))
1236                 if (soreadable(so))
1237                         revents |= events & (POLLIN | POLLRDNORM);
1238
1239         if (events & (POLLOUT | POLLWRNORM))
1240                 if (sowriteable(so))
1241                         revents |= events & (POLLOUT | POLLWRNORM);
1242
1243         if (events & (POLLPRI | POLLRDBAND))
1244                 if (so->so_oobmark || (so->so_state & SS_RCVATMARK))
1245                         revents |= events & (POLLPRI | POLLRDBAND);
1246
1247         if (revents == 0) {
1248                 if (events & (POLLIN | POLLPRI | POLLRDNORM | POLLRDBAND)) {
1249                         selrecord(p, &so->so_rcv.sb_sel);
1250                         so->so_rcv.sb_flags |= SB_SEL;
1251                 }
1252
1253                 if (events & (POLLOUT | POLLWRNORM)) {
1254                         selrecord(p, &so->so_snd.sb_sel);
1255                         so->so_snd.sb_flags |= SB_SEL;
1256                 }
1257         }
1258
1259         splx(s);
1260         return (revents);
1261 }