]> CyberLeo.Net >> Repos - FreeBSD/FreeBSD.git/blob - sys/kern/uipc_syscalls.c
- Use m_get2() instead of hand allocating.
[FreeBSD/FreeBSD.git] / sys / kern / uipc_syscalls.c
1 /*-
2  * Copyright (c) 1982, 1986, 1989, 1990, 1993
3  *      The Regents of the University of California.  All rights reserved.
4  *
5  * sendfile(2) and related extensions:
6  * Copyright (c) 1998, David Greenman. All rights reserved.
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  * 4. Neither the name of the University nor the names of its contributors
17  *    may be used to endorse or promote products derived from this software
18  *    without specific prior written permission.
19  *
20  * THIS SOFTWARE IS PROVIDED BY THE REGENTS AND CONTRIBUTORS ``AS IS'' AND
21  * ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
22  * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE
23  * ARE DISCLAIMED.  IN NO EVENT SHALL THE REGENTS OR CONTRIBUTORS BE LIABLE
24  * FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL
25  * DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS
26  * OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION)
27  * HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT
28  * LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY
29  * OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF
30  * SUCH DAMAGE.
31  *
32  *      @(#)uipc_syscalls.c     8.4 (Berkeley) 2/21/94
33  */
34
35 #include <sys/cdefs.h>
36 __FBSDID("$FreeBSD$");
37
38 #include "opt_capsicum.h"
39 #include "opt_inet.h"
40 #include "opt_inet6.h"
41 #include "opt_sctp.h"
42 #include "opt_compat.h"
43 #include "opt_ktrace.h"
44
45 #include <sys/param.h>
46 #include <sys/systm.h>
47 #include <sys/capability.h>
48 #include <sys/kernel.h>
49 #include <sys/lock.h>
50 #include <sys/mutex.h>
51 #include <sys/sysproto.h>
52 #include <sys/malloc.h>
53 #include <sys/filedesc.h>
54 #include <sys/event.h>
55 #include <sys/proc.h>
56 #include <sys/fcntl.h>
57 #include <sys/file.h>
58 #include <sys/filio.h>
59 #include <sys/jail.h>
60 #include <sys/mount.h>
61 #include <sys/mbuf.h>
62 #include <sys/protosw.h>
63 #include <sys/rwlock.h>
64 #include <sys/sf_buf.h>
65 #include <sys/sysent.h>
66 #include <sys/socket.h>
67 #include <sys/socketvar.h>
68 #include <sys/signalvar.h>
69 #include <sys/syscallsubr.h>
70 #include <sys/sysctl.h>
71 #include <sys/uio.h>
72 #include <sys/vnode.h>
73 #ifdef KTRACE
74 #include <sys/ktrace.h>
75 #endif
76 #ifdef COMPAT_FREEBSD32
77 #include <compat/freebsd32/freebsd32_util.h>
78 #endif
79
80 #include <net/vnet.h>
81
82 #include <security/audit/audit.h>
83 #include <security/mac/mac_framework.h>
84
85 #include <vm/vm.h>
86 #include <vm/vm_param.h>
87 #include <vm/vm_object.h>
88 #include <vm/vm_page.h>
89 #include <vm/vm_pageout.h>
90 #include <vm/vm_kern.h>
91 #include <vm/vm_extern.h>
92
93 #if defined(INET) || defined(INET6)
94 #ifdef SCTP
95 #include <netinet/sctp.h>
96 #include <netinet/sctp_peeloff.h>
97 #endif /* SCTP */
98 #endif /* INET || INET6 */
99
100 static int sendit(struct thread *td, int s, struct msghdr *mp, int flags);
101 static int recvit(struct thread *td, int s, struct msghdr *mp, void *namelenp);
102
103 static int accept1(struct thread *td, struct accept_args *uap, int compat);
104 static int do_sendfile(struct thread *td, struct sendfile_args *uap, int compat);
105 static int getsockname1(struct thread *td, struct getsockname_args *uap,
106                         int compat);
107 static int getpeername1(struct thread *td, struct getpeername_args *uap,
108                         int compat);
109
110 /*
111  * NSFBUFS-related variables and associated sysctls
112  */
113 int nsfbufs;
114 int nsfbufspeak;
115 int nsfbufsused;
116
117 SYSCTL_INT(_kern_ipc, OID_AUTO, nsfbufs, CTLFLAG_RDTUN, &nsfbufs, 0,
118     "Maximum number of sendfile(2) sf_bufs available");
119 SYSCTL_INT(_kern_ipc, OID_AUTO, nsfbufspeak, CTLFLAG_RD, &nsfbufspeak, 0,
120     "Number of sendfile(2) sf_bufs at peak usage");
121 SYSCTL_INT(_kern_ipc, OID_AUTO, nsfbufsused, CTLFLAG_RD, &nsfbufsused, 0,
122     "Number of sendfile(2) sf_bufs in use");
123
124 /*
125  * Convert a user file descriptor to a kernel file entry and check if required
126  * capability rights are present.
127  * A reference on the file entry is held upon returning.
128  */
129 static int
130 getsock_cap(struct filedesc *fdp, int fd, cap_rights_t rights,
131     struct file **fpp, u_int *fflagp)
132 {
133         struct file *fp;
134         int error;
135
136         error = fget_unlocked(fdp, fd, rights, 0, &fp, NULL);
137         if (error != 0)
138                 return (error);
139         if (fp->f_type != DTYPE_SOCKET) {
140                 fdrop(fp, curthread);
141                 return (ENOTSOCK);
142         }
143         if (fflagp != NULL)
144                 *fflagp = fp->f_flag;
145         *fpp = fp;
146         return (0);
147 }
148
149 /*
150  * System call interface to the socket abstraction.
151  */
152 #if defined(COMPAT_43)
153 #define COMPAT_OLDSOCK
154 #endif
155
156 int
157 sys_socket(td, uap)
158         struct thread *td;
159         struct socket_args /* {
160                 int     domain;
161                 int     type;
162                 int     protocol;
163         } */ *uap;
164 {
165         struct socket *so;
166         struct file *fp;
167         int fd, error;
168
169         AUDIT_ARG_SOCKET(uap->domain, uap->type, uap->protocol);
170 #ifdef MAC
171         error = mac_socket_check_create(td->td_ucred, uap->domain, uap->type,
172             uap->protocol);
173         if (error)
174                 return (error);
175 #endif
176         error = falloc(td, &fp, &fd, 0);
177         if (error)
178                 return (error);
179         /* An extra reference on `fp' has been held for us by falloc(). */
180         error = socreate(uap->domain, &so, uap->type, uap->protocol,
181             td->td_ucred, td);
182         if (error) {
183                 fdclose(td->td_proc->p_fd, fp, fd, td);
184         } else {
185                 finit(fp, FREAD | FWRITE, DTYPE_SOCKET, so, &socketops);
186                 td->td_retval[0] = fd;
187         }
188         fdrop(fp, td);
189         return (error);
190 }
191
192 /* ARGSUSED */
193 int
194 sys_bind(td, uap)
195         struct thread *td;
196         struct bind_args /* {
197                 int     s;
198                 caddr_t name;
199                 int     namelen;
200         } */ *uap;
201 {
202         struct sockaddr *sa;
203         int error;
204
205         error = getsockaddr(&sa, uap->name, uap->namelen);
206         if (error == 0) {
207                 error = kern_bind(td, uap->s, sa);
208                 free(sa, M_SONAME);
209         }
210         return (error);
211 }
212
213 static int
214 kern_bindat(struct thread *td, int dirfd, int fd, struct sockaddr *sa)
215 {
216         struct socket *so;
217         struct file *fp;
218         int error;
219
220         AUDIT_ARG_FD(fd);
221         AUDIT_ARG_SOCKADDR(td, dirfd, sa);
222         error = getsock_cap(td->td_proc->p_fd, fd, CAP_BIND, &fp, NULL);
223         if (error)
224                 return (error);
225         so = fp->f_data;
226 #ifdef KTRACE
227         if (KTRPOINT(td, KTR_STRUCT))
228                 ktrsockaddr(sa);
229 #endif
230 #ifdef MAC
231         error = mac_socket_check_bind(td->td_ucred, so, sa);
232         if (error == 0) {
233 #endif
234                 if (dirfd == AT_FDCWD)
235                         error = sobind(so, sa, td);
236                 else
237                         error = sobindat(dirfd, so, sa, td);
238 #ifdef MAC
239         }
240 #endif
241         fdrop(fp, td);
242         return (error);
243 }
244
245 int
246 kern_bind(struct thread *td, int fd, struct sockaddr *sa)
247 {
248
249         return (kern_bindat(td, AT_FDCWD, fd, sa));
250 }
251
252 /* ARGSUSED */
253 int
254 sys_bindat(td, uap)
255         struct thread *td;
256         struct bindat_args /* {
257                 int     fd;
258                 int     s;
259                 caddr_t name;
260                 int     namelen;
261         } */ *uap;
262 {
263         struct sockaddr *sa;
264         int error;
265
266         error = getsockaddr(&sa, uap->name, uap->namelen);
267         if (error == 0) {
268                 error = kern_bindat(td, uap->fd, uap->s, sa);
269                 free(sa, M_SONAME);
270         }
271         return (error);
272 }
273
274 /* ARGSUSED */
275 int
276 sys_listen(td, uap)
277         struct thread *td;
278         struct listen_args /* {
279                 int     s;
280                 int     backlog;
281         } */ *uap;
282 {
283         struct socket *so;
284         struct file *fp;
285         int error;
286
287         AUDIT_ARG_FD(uap->s);
288         error = getsock_cap(td->td_proc->p_fd, uap->s, CAP_LISTEN, &fp, NULL);
289         if (error == 0) {
290                 so = fp->f_data;
291 #ifdef MAC
292                 error = mac_socket_check_listen(td->td_ucred, so);
293                 if (error == 0)
294 #endif
295                         error = solisten(so, uap->backlog, td);
296                 fdrop(fp, td);
297         }
298         return(error);
299 }
300
301 /*
302  * accept1()
303  */
304 static int
305 accept1(td, uap, compat)
306         struct thread *td;
307         struct accept_args /* {
308                 int     s;
309                 struct sockaddr * __restrict name;
310                 socklen_t       * __restrict anamelen;
311         } */ *uap;
312         int compat;
313 {
314         struct sockaddr *name;
315         socklen_t namelen;
316         struct file *fp;
317         int error;
318
319         if (uap->name == NULL)
320                 return (kern_accept(td, uap->s, NULL, NULL, NULL));
321
322         error = copyin(uap->anamelen, &namelen, sizeof (namelen));
323         if (error)
324                 return (error);
325
326         error = kern_accept(td, uap->s, &name, &namelen, &fp);
327
328         /*
329          * return a namelen of zero for older code which might
330          * ignore the return value from accept.
331          */
332         if (error) {
333                 (void) copyout(&namelen,
334                     uap->anamelen, sizeof(*uap->anamelen));
335                 return (error);
336         }
337
338         if (error == 0 && name != NULL) {
339 #ifdef COMPAT_OLDSOCK
340                 if (compat)
341                         ((struct osockaddr *)name)->sa_family =
342                             name->sa_family;
343 #endif
344                 error = copyout(name, uap->name, namelen);
345         }
346         if (error == 0)
347                 error = copyout(&namelen, uap->anamelen,
348                     sizeof(namelen));
349         if (error)
350                 fdclose(td->td_proc->p_fd, fp, td->td_retval[0], td);
351         fdrop(fp, td);
352         free(name, M_SONAME);
353         return (error);
354 }
355
356 int
357 kern_accept(struct thread *td, int s, struct sockaddr **name,
358     socklen_t *namelen, struct file **fp)
359 {
360         struct filedesc *fdp;
361         struct file *headfp, *nfp = NULL;
362         struct sockaddr *sa = NULL;
363         int error;
364         struct socket *head, *so;
365         int fd;
366         u_int fflag;
367         pid_t pgid;
368         int tmp;
369
370         if (name) {
371                 *name = NULL;
372                 if (*namelen < 0)
373                         return (EINVAL);
374         }
375
376         AUDIT_ARG_FD(s);
377         fdp = td->td_proc->p_fd;
378         error = getsock_cap(fdp, s, CAP_ACCEPT, &headfp, &fflag);
379         if (error)
380                 return (error);
381         head = headfp->f_data;
382         if ((head->so_options & SO_ACCEPTCONN) == 0) {
383                 error = EINVAL;
384                 goto done;
385         }
386 #ifdef MAC
387         error = mac_socket_check_accept(td->td_ucred, head);
388         if (error != 0)
389                 goto done;
390 #endif
391         error = falloc(td, &nfp, &fd, 0);
392         if (error)
393                 goto done;
394         ACCEPT_LOCK();
395         if ((head->so_state & SS_NBIO) && TAILQ_EMPTY(&head->so_comp)) {
396                 ACCEPT_UNLOCK();
397                 error = EWOULDBLOCK;
398                 goto noconnection;
399         }
400         while (TAILQ_EMPTY(&head->so_comp) && head->so_error == 0) {
401                 if (head->so_rcv.sb_state & SBS_CANTRCVMORE) {
402                         head->so_error = ECONNABORTED;
403                         break;
404                 }
405                 error = msleep(&head->so_timeo, &accept_mtx, PSOCK | PCATCH,
406                     "accept", 0);
407                 if (error) {
408                         ACCEPT_UNLOCK();
409                         goto noconnection;
410                 }
411         }
412         if (head->so_error) {
413                 error = head->so_error;
414                 head->so_error = 0;
415                 ACCEPT_UNLOCK();
416                 goto noconnection;
417         }
418         so = TAILQ_FIRST(&head->so_comp);
419         KASSERT(!(so->so_qstate & SQ_INCOMP), ("accept1: so SQ_INCOMP"));
420         KASSERT(so->so_qstate & SQ_COMP, ("accept1: so not SQ_COMP"));
421
422         /*
423          * Before changing the flags on the socket, we have to bump the
424          * reference count.  Otherwise, if the protocol calls sofree(),
425          * the socket will be released due to a zero refcount.
426          */
427         SOCK_LOCK(so);                  /* soref() and so_state update */
428         soref(so);                      /* file descriptor reference */
429
430         TAILQ_REMOVE(&head->so_comp, so, so_list);
431         head->so_qlen--;
432         so->so_state |= (head->so_state & SS_NBIO);
433         so->so_qstate &= ~SQ_COMP;
434         so->so_head = NULL;
435
436         SOCK_UNLOCK(so);
437         ACCEPT_UNLOCK();
438
439         /* An extra reference on `nfp' has been held for us by falloc(). */
440         td->td_retval[0] = fd;
441
442         /* connection has been removed from the listen queue */
443         KNOTE_UNLOCKED(&head->so_rcv.sb_sel.si_note, 0);
444
445         pgid = fgetown(&head->so_sigio);
446         if (pgid != 0)
447                 fsetown(pgid, &so->so_sigio);
448
449         finit(nfp, fflag, DTYPE_SOCKET, so, &socketops);
450         /* Sync socket nonblocking/async state with file flags */
451         tmp = fflag & FNONBLOCK;
452         (void) fo_ioctl(nfp, FIONBIO, &tmp, td->td_ucred, td);
453         tmp = fflag & FASYNC;
454         (void) fo_ioctl(nfp, FIOASYNC, &tmp, td->td_ucred, td);
455         sa = 0;
456         error = soaccept(so, &sa);
457         if (error) {
458                 /*
459                  * return a namelen of zero for older code which might
460                  * ignore the return value from accept.
461                  */
462                 if (name)
463                         *namelen = 0;
464                 goto noconnection;
465         }
466         if (sa == NULL) {
467                 if (name)
468                         *namelen = 0;
469                 goto done;
470         }
471         AUDIT_ARG_SOCKADDR(td, AT_FDCWD, sa);
472         if (name) {
473                 /* check sa_len before it is destroyed */
474                 if (*namelen > sa->sa_len)
475                         *namelen = sa->sa_len;
476 #ifdef KTRACE
477                 if (KTRPOINT(td, KTR_STRUCT))
478                         ktrsockaddr(sa);
479 #endif
480                 *name = sa;
481                 sa = NULL;
482         }
483 noconnection:
484         if (sa)
485                 free(sa, M_SONAME);
486
487         /*
488          * close the new descriptor, assuming someone hasn't ripped it
489          * out from under us.
490          */
491         if (error)
492                 fdclose(fdp, nfp, fd, td);
493
494         /*
495          * Release explicitly held references before returning.  We return
496          * a reference on nfp to the caller on success if they request it.
497          */
498 done:
499         if (fp != NULL) {
500                 if (error == 0) {
501                         *fp = nfp;
502                         nfp = NULL;
503                 } else
504                         *fp = NULL;
505         }
506         if (nfp != NULL)
507                 fdrop(nfp, td);
508         fdrop(headfp, td);
509         return (error);
510 }
511
512 int
513 sys_accept(td, uap)
514         struct thread *td;
515         struct accept_args *uap;
516 {
517
518         return (accept1(td, uap, 0));
519 }
520
521 #ifdef COMPAT_OLDSOCK
522 int
523 oaccept(td, uap)
524         struct thread *td;
525         struct accept_args *uap;
526 {
527
528         return (accept1(td, uap, 1));
529 }
530 #endif /* COMPAT_OLDSOCK */
531
532 /* ARGSUSED */
533 int
534 sys_connect(td, uap)
535         struct thread *td;
536         struct connect_args /* {
537                 int     s;
538                 caddr_t name;
539                 int     namelen;
540         } */ *uap;
541 {
542         struct sockaddr *sa;
543         int error;
544
545         error = getsockaddr(&sa, uap->name, uap->namelen);
546         if (error == 0) {
547                 error = kern_connect(td, uap->s, sa);
548                 free(sa, M_SONAME);
549         }
550         return (error);
551 }
552
553 static int
554 kern_connectat(struct thread *td, int dirfd, int fd, struct sockaddr *sa)
555 {
556         struct socket *so;
557         struct file *fp;
558         int error;
559         int interrupted = 0;
560
561         AUDIT_ARG_FD(fd);
562         AUDIT_ARG_SOCKADDR(td, dirfd, sa);
563         error = getsock_cap(td->td_proc->p_fd, fd, CAP_CONNECT, &fp, NULL);
564         if (error)
565                 return (error);
566         so = fp->f_data;
567         if (so->so_state & SS_ISCONNECTING) {
568                 error = EALREADY;
569                 goto done1;
570         }
571 #ifdef KTRACE
572         if (KTRPOINT(td, KTR_STRUCT))
573                 ktrsockaddr(sa);
574 #endif
575 #ifdef MAC
576         error = mac_socket_check_connect(td->td_ucred, so, sa);
577         if (error)
578                 goto bad;
579 #endif
580         if (dirfd == AT_FDCWD)
581                 error = soconnect(so, sa, td);
582         else
583                 error = soconnectat(dirfd, so, sa, td);
584         if (error)
585                 goto bad;
586         if ((so->so_state & SS_NBIO) && (so->so_state & SS_ISCONNECTING)) {
587                 error = EINPROGRESS;
588                 goto done1;
589         }
590         SOCK_LOCK(so);
591         while ((so->so_state & SS_ISCONNECTING) && so->so_error == 0) {
592                 error = msleep(&so->so_timeo, SOCK_MTX(so), PSOCK | PCATCH,
593                     "connec", 0);
594                 if (error) {
595                         if (error == EINTR || error == ERESTART)
596                                 interrupted = 1;
597                         break;
598                 }
599         }
600         if (error == 0) {
601                 error = so->so_error;
602                 so->so_error = 0;
603         }
604         SOCK_UNLOCK(so);
605 bad:
606         if (!interrupted)
607                 so->so_state &= ~SS_ISCONNECTING;
608         if (error == ERESTART)
609                 error = EINTR;
610 done1:
611         fdrop(fp, td);
612         return (error);
613 }
614
615 int
616 kern_connect(struct thread *td, int fd, struct sockaddr *sa)
617 {
618
619         return (kern_connectat(td, AT_FDCWD, fd, sa));
620 }
621
622 /* ARGSUSED */
623 int
624 sys_connectat(td, uap)
625         struct thread *td;
626         struct connectat_args /* {
627                 int     fd;
628                 int     s;
629                 caddr_t name;
630                 int     namelen;
631         } */ *uap;
632 {
633         struct sockaddr *sa;
634         int error;
635
636         error = getsockaddr(&sa, uap->name, uap->namelen);
637         if (error == 0) {
638                 error = kern_connectat(td, uap->fd, uap->s, sa);
639                 free(sa, M_SONAME);
640         }
641         return (error);
642 }
643
644 int
645 kern_socketpair(struct thread *td, int domain, int type, int protocol,
646     int *rsv)
647 {
648         struct filedesc *fdp = td->td_proc->p_fd;
649         struct file *fp1, *fp2;
650         struct socket *so1, *so2;
651         int fd, error;
652
653         AUDIT_ARG_SOCKET(domain, type, protocol);
654 #ifdef MAC
655         /* We might want to have a separate check for socket pairs. */
656         error = mac_socket_check_create(td->td_ucred, domain, type,
657             protocol);
658         if (error)
659                 return (error);
660 #endif
661         error = socreate(domain, &so1, type, protocol, td->td_ucred, td);
662         if (error)
663                 return (error);
664         error = socreate(domain, &so2, type, protocol, td->td_ucred, td);
665         if (error)
666                 goto free1;
667         /* On success extra reference to `fp1' and 'fp2' is set by falloc. */
668         error = falloc(td, &fp1, &fd, 0);
669         if (error)
670                 goto free2;
671         rsv[0] = fd;
672         fp1->f_data = so1;      /* so1 already has ref count */
673         error = falloc(td, &fp2, &fd, 0);
674         if (error)
675                 goto free3;
676         fp2->f_data = so2;      /* so2 already has ref count */
677         rsv[1] = fd;
678         error = soconnect2(so1, so2);
679         if (error)
680                 goto free4;
681         if (type == SOCK_DGRAM) {
682                 /*
683                  * Datagram socket connection is asymmetric.
684                  */
685                  error = soconnect2(so2, so1);
686                  if (error)
687                         goto free4;
688         }
689         finit(fp1, FREAD | FWRITE, DTYPE_SOCKET, fp1->f_data, &socketops);
690         finit(fp2, FREAD | FWRITE, DTYPE_SOCKET, fp2->f_data, &socketops);
691         fdrop(fp1, td);
692         fdrop(fp2, td);
693         return (0);
694 free4:
695         fdclose(fdp, fp2, rsv[1], td);
696         fdrop(fp2, td);
697 free3:
698         fdclose(fdp, fp1, rsv[0], td);
699         fdrop(fp1, td);
700 free2:
701         if (so2 != NULL)
702                 (void)soclose(so2);
703 free1:
704         if (so1 != NULL)
705                 (void)soclose(so1);
706         return (error);
707 }
708
709 int
710 sys_socketpair(struct thread *td, struct socketpair_args *uap)
711 {
712         int error, sv[2];
713
714         error = kern_socketpair(td, uap->domain, uap->type,
715             uap->protocol, sv);
716         if (error)
717                 return (error);
718         error = copyout(sv, uap->rsv, 2 * sizeof(int));
719         if (error) {
720                 (void)kern_close(td, sv[0]);
721                 (void)kern_close(td, sv[1]);
722         }
723         return (error);
724 }
725
726 static int
727 sendit(td, s, mp, flags)
728         struct thread *td;
729         int s;
730         struct msghdr *mp;
731         int flags;
732 {
733         struct mbuf *control;
734         struct sockaddr *to;
735         int error;
736
737 #ifdef CAPABILITY_MODE
738         if (IN_CAPABILITY_MODE(td) && (mp->msg_name != NULL))
739                 return (ECAPMODE);
740 #endif
741
742         if (mp->msg_name != NULL) {
743                 error = getsockaddr(&to, mp->msg_name, mp->msg_namelen);
744                 if (error) {
745                         to = NULL;
746                         goto bad;
747                 }
748                 mp->msg_name = to;
749         } else {
750                 to = NULL;
751         }
752
753         if (mp->msg_control) {
754                 if (mp->msg_controllen < sizeof(struct cmsghdr)
755 #ifdef COMPAT_OLDSOCK
756                     && mp->msg_flags != MSG_COMPAT
757 #endif
758                 ) {
759                         error = EINVAL;
760                         goto bad;
761                 }
762                 error = sockargs(&control, mp->msg_control,
763                     mp->msg_controllen, MT_CONTROL);
764                 if (error)
765                         goto bad;
766 #ifdef COMPAT_OLDSOCK
767                 if (mp->msg_flags == MSG_COMPAT) {
768                         struct cmsghdr *cm;
769
770                         M_PREPEND(control, sizeof(*cm), M_WAITOK);
771                         cm = mtod(control, struct cmsghdr *);
772                         cm->cmsg_len = control->m_len;
773                         cm->cmsg_level = SOL_SOCKET;
774                         cm->cmsg_type = SCM_RIGHTS;
775                 }
776 #endif
777         } else {
778                 control = NULL;
779         }
780
781         error = kern_sendit(td, s, mp, flags, control, UIO_USERSPACE);
782
783 bad:
784         if (to)
785                 free(to, M_SONAME);
786         return (error);
787 }
788
789 int
790 kern_sendit(td, s, mp, flags, control, segflg)
791         struct thread *td;
792         int s;
793         struct msghdr *mp;
794         int flags;
795         struct mbuf *control;
796         enum uio_seg segflg;
797 {
798         struct file *fp;
799         struct uio auio;
800         struct iovec *iov;
801         struct socket *so;
802         int i, error;
803         ssize_t len;
804         cap_rights_t rights;
805 #ifdef KTRACE
806         struct uio *ktruio = NULL;
807 #endif
808
809         AUDIT_ARG_FD(s);
810         rights = CAP_SEND;
811         if (mp->msg_name != NULL) {
812                 AUDIT_ARG_SOCKADDR(td, AT_FDCWD, mp->msg_name);
813                 rights |= CAP_CONNECT;
814         }
815         error = getsock_cap(td->td_proc->p_fd, s, rights, &fp, NULL);
816         if (error)
817                 return (error);
818         so = (struct socket *)fp->f_data;
819
820 #ifdef KTRACE
821         if (mp->msg_name != NULL && KTRPOINT(td, KTR_STRUCT))
822                 ktrsockaddr(mp->msg_name);
823 #endif
824 #ifdef MAC
825         if (mp->msg_name != NULL) {
826                 error = mac_socket_check_connect(td->td_ucred, so,
827                     mp->msg_name);
828                 if (error)
829                         goto bad;
830         }
831         error = mac_socket_check_send(td->td_ucred, so);
832         if (error)
833                 goto bad;
834 #endif
835
836         auio.uio_iov = mp->msg_iov;
837         auio.uio_iovcnt = mp->msg_iovlen;
838         auio.uio_segflg = segflg;
839         auio.uio_rw = UIO_WRITE;
840         auio.uio_td = td;
841         auio.uio_offset = 0;                    /* XXX */
842         auio.uio_resid = 0;
843         iov = mp->msg_iov;
844         for (i = 0; i < mp->msg_iovlen; i++, iov++) {
845                 if ((auio.uio_resid += iov->iov_len) < 0) {
846                         error = EINVAL;
847                         goto bad;
848                 }
849         }
850 #ifdef KTRACE
851         if (KTRPOINT(td, KTR_GENIO))
852                 ktruio = cloneuio(&auio);
853 #endif
854         len = auio.uio_resid;
855         error = sosend(so, mp->msg_name, &auio, 0, control, flags, td);
856         if (error) {
857                 if (auio.uio_resid != len && (error == ERESTART ||
858                     error == EINTR || error == EWOULDBLOCK))
859                         error = 0;
860                 /* Generation of SIGPIPE can be controlled per socket */
861                 if (error == EPIPE && !(so->so_options & SO_NOSIGPIPE) &&
862                     !(flags & MSG_NOSIGNAL)) {
863                         PROC_LOCK(td->td_proc);
864                         tdsignal(td, SIGPIPE);
865                         PROC_UNLOCK(td->td_proc);
866                 }
867         }
868         if (error == 0)
869                 td->td_retval[0] = len - auio.uio_resid;
870 #ifdef KTRACE
871         if (ktruio != NULL) {
872                 ktruio->uio_resid = td->td_retval[0];
873                 ktrgenio(s, UIO_WRITE, ktruio, error);
874         }
875 #endif
876 bad:
877         fdrop(fp, td);
878         return (error);
879 }
880
881 int
882 sys_sendto(td, uap)
883         struct thread *td;
884         struct sendto_args /* {
885                 int     s;
886                 caddr_t buf;
887                 size_t  len;
888                 int     flags;
889                 caddr_t to;
890                 int     tolen;
891         } */ *uap;
892 {
893         struct msghdr msg;
894         struct iovec aiov;
895         int error;
896
897         msg.msg_name = uap->to;
898         msg.msg_namelen = uap->tolen;
899         msg.msg_iov = &aiov;
900         msg.msg_iovlen = 1;
901         msg.msg_control = 0;
902 #ifdef COMPAT_OLDSOCK
903         msg.msg_flags = 0;
904 #endif
905         aiov.iov_base = uap->buf;
906         aiov.iov_len = uap->len;
907         error = sendit(td, uap->s, &msg, uap->flags);
908         return (error);
909 }
910
911 #ifdef COMPAT_OLDSOCK
912 int
913 osend(td, uap)
914         struct thread *td;
915         struct osend_args /* {
916                 int     s;
917                 caddr_t buf;
918                 int     len;
919                 int     flags;
920         } */ *uap;
921 {
922         struct msghdr msg;
923         struct iovec aiov;
924         int error;
925
926         msg.msg_name = 0;
927         msg.msg_namelen = 0;
928         msg.msg_iov = &aiov;
929         msg.msg_iovlen = 1;
930         aiov.iov_base = uap->buf;
931         aiov.iov_len = uap->len;
932         msg.msg_control = 0;
933         msg.msg_flags = 0;
934         error = sendit(td, uap->s, &msg, uap->flags);
935         return (error);
936 }
937
938 int
939 osendmsg(td, uap)
940         struct thread *td;
941         struct osendmsg_args /* {
942                 int     s;
943                 caddr_t msg;
944                 int     flags;
945         } */ *uap;
946 {
947         struct msghdr msg;
948         struct iovec *iov;
949         int error;
950
951         error = copyin(uap->msg, &msg, sizeof (struct omsghdr));
952         if (error)
953                 return (error);
954         error = copyiniov(msg.msg_iov, msg.msg_iovlen, &iov, EMSGSIZE);
955         if (error)
956                 return (error);
957         msg.msg_iov = iov;
958         msg.msg_flags = MSG_COMPAT;
959         error = sendit(td, uap->s, &msg, uap->flags);
960         free(iov, M_IOV);
961         return (error);
962 }
963 #endif
964
965 int
966 sys_sendmsg(td, uap)
967         struct thread *td;
968         struct sendmsg_args /* {
969                 int     s;
970                 caddr_t msg;
971                 int     flags;
972         } */ *uap;
973 {
974         struct msghdr msg;
975         struct iovec *iov;
976         int error;
977
978         error = copyin(uap->msg, &msg, sizeof (msg));
979         if (error)
980                 return (error);
981         error = copyiniov(msg.msg_iov, msg.msg_iovlen, &iov, EMSGSIZE);
982         if (error)
983                 return (error);
984         msg.msg_iov = iov;
985 #ifdef COMPAT_OLDSOCK
986         msg.msg_flags = 0;
987 #endif
988         error = sendit(td, uap->s, &msg, uap->flags);
989         free(iov, M_IOV);
990         return (error);
991 }
992
993 int
994 kern_recvit(td, s, mp, fromseg, controlp)
995         struct thread *td;
996         int s;
997         struct msghdr *mp;
998         enum uio_seg fromseg;
999         struct mbuf **controlp;
1000 {
1001         struct uio auio;
1002         struct iovec *iov;
1003         int i;
1004         ssize_t len;
1005         int error;
1006         struct mbuf *m, *control = NULL;
1007         caddr_t ctlbuf;
1008         struct file *fp;
1009         struct socket *so;
1010         struct sockaddr *fromsa = NULL;
1011 #ifdef KTRACE
1012         struct uio *ktruio = NULL;
1013 #endif
1014
1015         if (controlp != NULL)
1016                 *controlp = NULL;
1017
1018         AUDIT_ARG_FD(s);
1019         error = getsock_cap(td->td_proc->p_fd, s, CAP_RECV, &fp, NULL);
1020         if (error)
1021                 return (error);
1022         so = fp->f_data;
1023
1024 #ifdef MAC
1025         error = mac_socket_check_receive(td->td_ucred, so);
1026         if (error) {
1027                 fdrop(fp, td);
1028                 return (error);
1029         }
1030 #endif
1031
1032         auio.uio_iov = mp->msg_iov;
1033         auio.uio_iovcnt = mp->msg_iovlen;
1034         auio.uio_segflg = UIO_USERSPACE;
1035         auio.uio_rw = UIO_READ;
1036         auio.uio_td = td;
1037         auio.uio_offset = 0;                    /* XXX */
1038         auio.uio_resid = 0;
1039         iov = mp->msg_iov;
1040         for (i = 0; i < mp->msg_iovlen; i++, iov++) {
1041                 if ((auio.uio_resid += iov->iov_len) < 0) {
1042                         fdrop(fp, td);
1043                         return (EINVAL);
1044                 }
1045         }
1046 #ifdef KTRACE
1047         if (KTRPOINT(td, KTR_GENIO))
1048                 ktruio = cloneuio(&auio);
1049 #endif
1050         len = auio.uio_resid;
1051         error = soreceive(so, &fromsa, &auio, NULL,
1052             (mp->msg_control || controlp) ? &control : NULL,
1053             &mp->msg_flags);
1054         if (error) {
1055                 if (auio.uio_resid != len && (error == ERESTART ||
1056                     error == EINTR || error == EWOULDBLOCK))
1057                         error = 0;
1058         }
1059         if (fromsa != NULL)
1060                 AUDIT_ARG_SOCKADDR(td, AT_FDCWD, fromsa);
1061 #ifdef KTRACE
1062         if (ktruio != NULL) {
1063                 ktruio->uio_resid = len - auio.uio_resid;
1064                 ktrgenio(s, UIO_READ, ktruio, error);
1065         }
1066 #endif
1067         if (error)
1068                 goto out;
1069         td->td_retval[0] = len - auio.uio_resid;
1070         if (mp->msg_name) {
1071                 len = mp->msg_namelen;
1072                 if (len <= 0 || fromsa == NULL)
1073                         len = 0;
1074                 else {
1075                         /* save sa_len before it is destroyed by MSG_COMPAT */
1076                         len = MIN(len, fromsa->sa_len);
1077 #ifdef COMPAT_OLDSOCK
1078                         if (mp->msg_flags & MSG_COMPAT)
1079                                 ((struct osockaddr *)fromsa)->sa_family =
1080                                     fromsa->sa_family;
1081 #endif
1082                         if (fromseg == UIO_USERSPACE) {
1083                                 error = copyout(fromsa, mp->msg_name,
1084                                     (unsigned)len);
1085                                 if (error)
1086                                         goto out;
1087                         } else
1088                                 bcopy(fromsa, mp->msg_name, len);
1089                 }
1090                 mp->msg_namelen = len;
1091         }
1092         if (mp->msg_control && controlp == NULL) {
1093 #ifdef COMPAT_OLDSOCK
1094                 /*
1095                  * We assume that old recvmsg calls won't receive access
1096                  * rights and other control info, esp. as control info
1097                  * is always optional and those options didn't exist in 4.3.
1098                  * If we receive rights, trim the cmsghdr; anything else
1099                  * is tossed.
1100                  */
1101                 if (control && mp->msg_flags & MSG_COMPAT) {
1102                         if (mtod(control, struct cmsghdr *)->cmsg_level !=
1103                             SOL_SOCKET ||
1104                             mtod(control, struct cmsghdr *)->cmsg_type !=
1105                             SCM_RIGHTS) {
1106                                 mp->msg_controllen = 0;
1107                                 goto out;
1108                         }
1109                         control->m_len -= sizeof (struct cmsghdr);
1110                         control->m_data += sizeof (struct cmsghdr);
1111                 }
1112 #endif
1113                 len = mp->msg_controllen;
1114                 m = control;
1115                 mp->msg_controllen = 0;
1116                 ctlbuf = mp->msg_control;
1117
1118                 while (m && len > 0) {
1119                         unsigned int tocopy;
1120
1121                         if (len >= m->m_len)
1122                                 tocopy = m->m_len;
1123                         else {
1124                                 mp->msg_flags |= MSG_CTRUNC;
1125                                 tocopy = len;
1126                         }
1127
1128                         if ((error = copyout(mtod(m, caddr_t),
1129                                         ctlbuf, tocopy)) != 0)
1130                                 goto out;
1131
1132                         ctlbuf += tocopy;
1133                         len -= tocopy;
1134                         m = m->m_next;
1135                 }
1136                 mp->msg_controllen = ctlbuf - (caddr_t)mp->msg_control;
1137         }
1138 out:
1139         fdrop(fp, td);
1140 #ifdef KTRACE
1141         if (fromsa && KTRPOINT(td, KTR_STRUCT))
1142                 ktrsockaddr(fromsa);
1143 #endif
1144         if (fromsa)
1145                 free(fromsa, M_SONAME);
1146
1147         if (error == 0 && controlp != NULL)
1148                 *controlp = control;
1149         else  if (control)
1150                 m_freem(control);
1151
1152         return (error);
1153 }
1154
1155 static int
1156 recvit(td, s, mp, namelenp)
1157         struct thread *td;
1158         int s;
1159         struct msghdr *mp;
1160         void *namelenp;
1161 {
1162         int error;
1163
1164         error = kern_recvit(td, s, mp, UIO_USERSPACE, NULL);
1165         if (error)
1166                 return (error);
1167         if (namelenp) {
1168                 error = copyout(&mp->msg_namelen, namelenp, sizeof (socklen_t));
1169 #ifdef COMPAT_OLDSOCK
1170                 if (mp->msg_flags & MSG_COMPAT)
1171                         error = 0;      /* old recvfrom didn't check */
1172 #endif
1173         }
1174         return (error);
1175 }
1176
1177 int
1178 sys_recvfrom(td, uap)
1179         struct thread *td;
1180         struct recvfrom_args /* {
1181                 int     s;
1182                 caddr_t buf;
1183                 size_t  len;
1184                 int     flags;
1185                 struct sockaddr * __restrict    from;
1186                 socklen_t * __restrict fromlenaddr;
1187         } */ *uap;
1188 {
1189         struct msghdr msg;
1190         struct iovec aiov;
1191         int error;
1192
1193         if (uap->fromlenaddr) {
1194                 error = copyin(uap->fromlenaddr,
1195                     &msg.msg_namelen, sizeof (msg.msg_namelen));
1196                 if (error)
1197                         goto done2;
1198         } else {
1199                 msg.msg_namelen = 0;
1200         }
1201         msg.msg_name = uap->from;
1202         msg.msg_iov = &aiov;
1203         msg.msg_iovlen = 1;
1204         aiov.iov_base = uap->buf;
1205         aiov.iov_len = uap->len;
1206         msg.msg_control = 0;
1207         msg.msg_flags = uap->flags;
1208         error = recvit(td, uap->s, &msg, uap->fromlenaddr);
1209 done2:
1210         return(error);
1211 }
1212
1213 #ifdef COMPAT_OLDSOCK
1214 int
1215 orecvfrom(td, uap)
1216         struct thread *td;
1217         struct recvfrom_args *uap;
1218 {
1219
1220         uap->flags |= MSG_COMPAT;
1221         return (sys_recvfrom(td, uap));
1222 }
1223 #endif
1224
1225 #ifdef COMPAT_OLDSOCK
1226 int
1227 orecv(td, uap)
1228         struct thread *td;
1229         struct orecv_args /* {
1230                 int     s;
1231                 caddr_t buf;
1232                 int     len;
1233                 int     flags;
1234         } */ *uap;
1235 {
1236         struct msghdr msg;
1237         struct iovec aiov;
1238         int error;
1239
1240         msg.msg_name = 0;
1241         msg.msg_namelen = 0;
1242         msg.msg_iov = &aiov;
1243         msg.msg_iovlen = 1;
1244         aiov.iov_base = uap->buf;
1245         aiov.iov_len = uap->len;
1246         msg.msg_control = 0;
1247         msg.msg_flags = uap->flags;
1248         error = recvit(td, uap->s, &msg, NULL);
1249         return (error);
1250 }
1251
1252 /*
1253  * Old recvmsg.  This code takes advantage of the fact that the old msghdr
1254  * overlays the new one, missing only the flags, and with the (old) access
1255  * rights where the control fields are now.
1256  */
1257 int
1258 orecvmsg(td, uap)
1259         struct thread *td;
1260         struct orecvmsg_args /* {
1261                 int     s;
1262                 struct  omsghdr *msg;
1263                 int     flags;
1264         } */ *uap;
1265 {
1266         struct msghdr msg;
1267         struct iovec *iov;
1268         int error;
1269
1270         error = copyin(uap->msg, &msg, sizeof (struct omsghdr));
1271         if (error)
1272                 return (error);
1273         error = copyiniov(msg.msg_iov, msg.msg_iovlen, &iov, EMSGSIZE);
1274         if (error)
1275                 return (error);
1276         msg.msg_flags = uap->flags | MSG_COMPAT;
1277         msg.msg_iov = iov;
1278         error = recvit(td, uap->s, &msg, &uap->msg->msg_namelen);
1279         if (msg.msg_controllen && error == 0)
1280                 error = copyout(&msg.msg_controllen,
1281                     &uap->msg->msg_accrightslen, sizeof (int));
1282         free(iov, M_IOV);
1283         return (error);
1284 }
1285 #endif
1286
1287 int
1288 sys_recvmsg(td, uap)
1289         struct thread *td;
1290         struct recvmsg_args /* {
1291                 int     s;
1292                 struct  msghdr *msg;
1293                 int     flags;
1294         } */ *uap;
1295 {
1296         struct msghdr msg;
1297         struct iovec *uiov, *iov;
1298         int error;
1299
1300         error = copyin(uap->msg, &msg, sizeof (msg));
1301         if (error)
1302                 return (error);
1303         error = copyiniov(msg.msg_iov, msg.msg_iovlen, &iov, EMSGSIZE);
1304         if (error)
1305                 return (error);
1306         msg.msg_flags = uap->flags;
1307 #ifdef COMPAT_OLDSOCK
1308         msg.msg_flags &= ~MSG_COMPAT;
1309 #endif
1310         uiov = msg.msg_iov;
1311         msg.msg_iov = iov;
1312         error = recvit(td, uap->s, &msg, NULL);
1313         if (error == 0) {
1314                 msg.msg_iov = uiov;
1315                 error = copyout(&msg, uap->msg, sizeof(msg));
1316         }
1317         free(iov, M_IOV);
1318         return (error);
1319 }
1320
1321 /* ARGSUSED */
1322 int
1323 sys_shutdown(td, uap)
1324         struct thread *td;
1325         struct shutdown_args /* {
1326                 int     s;
1327                 int     how;
1328         } */ *uap;
1329 {
1330         struct socket *so;
1331         struct file *fp;
1332         int error;
1333
1334         AUDIT_ARG_FD(uap->s);
1335         error = getsock_cap(td->td_proc->p_fd, uap->s, CAP_SHUTDOWN, &fp,
1336             NULL);
1337         if (error == 0) {
1338                 so = fp->f_data;
1339                 error = soshutdown(so, uap->how);
1340                 fdrop(fp, td);
1341         }
1342         return (error);
1343 }
1344
1345 /* ARGSUSED */
1346 int
1347 sys_setsockopt(td, uap)
1348         struct thread *td;
1349         struct setsockopt_args /* {
1350                 int     s;
1351                 int     level;
1352                 int     name;
1353                 caddr_t val;
1354                 int     valsize;
1355         } */ *uap;
1356 {
1357
1358         return (kern_setsockopt(td, uap->s, uap->level, uap->name,
1359             uap->val, UIO_USERSPACE, uap->valsize));
1360 }
1361
1362 int
1363 kern_setsockopt(td, s, level, name, val, valseg, valsize)
1364         struct thread *td;
1365         int s;
1366         int level;
1367         int name;
1368         void *val;
1369         enum uio_seg valseg;
1370         socklen_t valsize;
1371 {
1372         int error;
1373         struct socket *so;
1374         struct file *fp;
1375         struct sockopt sopt;
1376
1377         if (val == NULL && valsize != 0)
1378                 return (EFAULT);
1379         if ((int)valsize < 0)
1380                 return (EINVAL);
1381
1382         sopt.sopt_dir = SOPT_SET;
1383         sopt.sopt_level = level;
1384         sopt.sopt_name = name;
1385         sopt.sopt_val = val;
1386         sopt.sopt_valsize = valsize;
1387         switch (valseg) {
1388         case UIO_USERSPACE:
1389                 sopt.sopt_td = td;
1390                 break;
1391         case UIO_SYSSPACE:
1392                 sopt.sopt_td = NULL;
1393                 break;
1394         default:
1395                 panic("kern_setsockopt called with bad valseg");
1396         }
1397
1398         AUDIT_ARG_FD(s);
1399         error = getsock_cap(td->td_proc->p_fd, s, CAP_SETSOCKOPT, &fp, NULL);
1400         if (error == 0) {
1401                 so = fp->f_data;
1402                 error = sosetopt(so, &sopt);
1403                 fdrop(fp, td);
1404         }
1405         return(error);
1406 }
1407
1408 /* ARGSUSED */
1409 int
1410 sys_getsockopt(td, uap)
1411         struct thread *td;
1412         struct getsockopt_args /* {
1413                 int     s;
1414                 int     level;
1415                 int     name;
1416                 void * __restrict       val;
1417                 socklen_t * __restrict avalsize;
1418         } */ *uap;
1419 {
1420         socklen_t valsize;
1421         int     error;
1422
1423         if (uap->val) {
1424                 error = copyin(uap->avalsize, &valsize, sizeof (valsize));
1425                 if (error)
1426                         return (error);
1427         }
1428
1429         error = kern_getsockopt(td, uap->s, uap->level, uap->name,
1430             uap->val, UIO_USERSPACE, &valsize);
1431
1432         if (error == 0)
1433                 error = copyout(&valsize, uap->avalsize, sizeof (valsize));
1434         return (error);
1435 }
1436
1437 /*
1438  * Kernel version of getsockopt.
1439  * optval can be a userland or userspace. optlen is always a kernel pointer.
1440  */
1441 int
1442 kern_getsockopt(td, s, level, name, val, valseg, valsize)
1443         struct thread *td;
1444         int s;
1445         int level;
1446         int name;
1447         void *val;
1448         enum uio_seg valseg;
1449         socklen_t *valsize;
1450 {
1451         int error;
1452         struct  socket *so;
1453         struct file *fp;
1454         struct  sockopt sopt;
1455
1456         if (val == NULL)
1457                 *valsize = 0;
1458         if ((int)*valsize < 0)
1459                 return (EINVAL);
1460
1461         sopt.sopt_dir = SOPT_GET;
1462         sopt.sopt_level = level;
1463         sopt.sopt_name = name;
1464         sopt.sopt_val = val;
1465         sopt.sopt_valsize = (size_t)*valsize; /* checked non-negative above */
1466         switch (valseg) {
1467         case UIO_USERSPACE:
1468                 sopt.sopt_td = td;
1469                 break;
1470         case UIO_SYSSPACE:
1471                 sopt.sopt_td = NULL;
1472                 break;
1473         default:
1474                 panic("kern_getsockopt called with bad valseg");
1475         }
1476
1477         AUDIT_ARG_FD(s);
1478         error = getsock_cap(td->td_proc->p_fd, s, CAP_GETSOCKOPT, &fp, NULL);
1479         if (error == 0) {
1480                 so = fp->f_data;
1481                 error = sogetopt(so, &sopt);
1482                 *valsize = sopt.sopt_valsize;
1483                 fdrop(fp, td);
1484         }
1485         return (error);
1486 }
1487
1488 /*
1489  * getsockname1() - Get socket name.
1490  */
1491 /* ARGSUSED */
1492 static int
1493 getsockname1(td, uap, compat)
1494         struct thread *td;
1495         struct getsockname_args /* {
1496                 int     fdes;
1497                 struct sockaddr * __restrict asa;
1498                 socklen_t * __restrict alen;
1499         } */ *uap;
1500         int compat;
1501 {
1502         struct sockaddr *sa;
1503         socklen_t len;
1504         int error;
1505
1506         error = copyin(uap->alen, &len, sizeof(len));
1507         if (error)
1508                 return (error);
1509
1510         error = kern_getsockname(td, uap->fdes, &sa, &len);
1511         if (error)
1512                 return (error);
1513
1514         if (len != 0) {
1515 #ifdef COMPAT_OLDSOCK
1516                 if (compat)
1517                         ((struct osockaddr *)sa)->sa_family = sa->sa_family;
1518 #endif
1519                 error = copyout(sa, uap->asa, (u_int)len);
1520         }
1521         free(sa, M_SONAME);
1522         if (error == 0)
1523                 error = copyout(&len, uap->alen, sizeof(len));
1524         return (error);
1525 }
1526
1527 int
1528 kern_getsockname(struct thread *td, int fd, struct sockaddr **sa,
1529     socklen_t *alen)
1530 {
1531         struct socket *so;
1532         struct file *fp;
1533         socklen_t len;
1534         int error;
1535
1536         if (*alen < 0)
1537                 return (EINVAL);
1538
1539         AUDIT_ARG_FD(fd);
1540         error = getsock_cap(td->td_proc->p_fd, fd, CAP_GETSOCKNAME, &fp, NULL);
1541         if (error)
1542                 return (error);
1543         so = fp->f_data;
1544         *sa = NULL;
1545         CURVNET_SET(so->so_vnet);
1546         error = (*so->so_proto->pr_usrreqs->pru_sockaddr)(so, sa);
1547         CURVNET_RESTORE();
1548         if (error)
1549                 goto bad;
1550         if (*sa == NULL)
1551                 len = 0;
1552         else
1553                 len = MIN(*alen, (*sa)->sa_len);
1554         *alen = len;
1555 #ifdef KTRACE
1556         if (KTRPOINT(td, KTR_STRUCT))
1557                 ktrsockaddr(*sa);
1558 #endif
1559 bad:
1560         fdrop(fp, td);
1561         if (error && *sa) {
1562                 free(*sa, M_SONAME);
1563                 *sa = NULL;
1564         }
1565         return (error);
1566 }
1567
1568 int
1569 sys_getsockname(td, uap)
1570         struct thread *td;
1571         struct getsockname_args *uap;
1572 {
1573
1574         return (getsockname1(td, uap, 0));
1575 }
1576
1577 #ifdef COMPAT_OLDSOCK
1578 int
1579 ogetsockname(td, uap)
1580         struct thread *td;
1581         struct getsockname_args *uap;
1582 {
1583
1584         return (getsockname1(td, uap, 1));
1585 }
1586 #endif /* COMPAT_OLDSOCK */
1587
1588 /*
1589  * getpeername1() - Get name of peer for connected socket.
1590  */
1591 /* ARGSUSED */
1592 static int
1593 getpeername1(td, uap, compat)
1594         struct thread *td;
1595         struct getpeername_args /* {
1596                 int     fdes;
1597                 struct sockaddr * __restrict    asa;
1598                 socklen_t * __restrict  alen;
1599         } */ *uap;
1600         int compat;
1601 {
1602         struct sockaddr *sa;
1603         socklen_t len;
1604         int error;
1605
1606         error = copyin(uap->alen, &len, sizeof (len));
1607         if (error)
1608                 return (error);
1609
1610         error = kern_getpeername(td, uap->fdes, &sa, &len);
1611         if (error)
1612                 return (error);
1613
1614         if (len != 0) {
1615 #ifdef COMPAT_OLDSOCK
1616                 if (compat)
1617                         ((struct osockaddr *)sa)->sa_family = sa->sa_family;
1618 #endif
1619                 error = copyout(sa, uap->asa, (u_int)len);
1620         }
1621         free(sa, M_SONAME);
1622         if (error == 0)
1623                 error = copyout(&len, uap->alen, sizeof(len));
1624         return (error);
1625 }
1626
1627 int
1628 kern_getpeername(struct thread *td, int fd, struct sockaddr **sa,
1629     socklen_t *alen)
1630 {
1631         struct socket *so;
1632         struct file *fp;
1633         socklen_t len;
1634         int error;
1635
1636         if (*alen < 0)
1637                 return (EINVAL);
1638
1639         AUDIT_ARG_FD(fd);
1640         error = getsock_cap(td->td_proc->p_fd, fd, CAP_GETPEERNAME, &fp, NULL);
1641         if (error)
1642                 return (error);
1643         so = fp->f_data;
1644         if ((so->so_state & (SS_ISCONNECTED|SS_ISCONFIRMING)) == 0) {
1645                 error = ENOTCONN;
1646                 goto done;
1647         }
1648         *sa = NULL;
1649         CURVNET_SET(so->so_vnet);
1650         error = (*so->so_proto->pr_usrreqs->pru_peeraddr)(so, sa);
1651         CURVNET_RESTORE();
1652         if (error)
1653                 goto bad;
1654         if (*sa == NULL)
1655                 len = 0;
1656         else
1657                 len = MIN(*alen, (*sa)->sa_len);
1658         *alen = len;
1659 #ifdef KTRACE
1660         if (KTRPOINT(td, KTR_STRUCT))
1661                 ktrsockaddr(*sa);
1662 #endif
1663 bad:
1664         if (error && *sa) {
1665                 free(*sa, M_SONAME);
1666                 *sa = NULL;
1667         }
1668 done:
1669         fdrop(fp, td);
1670         return (error);
1671 }
1672
1673 int
1674 sys_getpeername(td, uap)
1675         struct thread *td;
1676         struct getpeername_args *uap;
1677 {
1678
1679         return (getpeername1(td, uap, 0));
1680 }
1681
1682 #ifdef COMPAT_OLDSOCK
1683 int
1684 ogetpeername(td, uap)
1685         struct thread *td;
1686         struct ogetpeername_args *uap;
1687 {
1688
1689         /* XXX uap should have type `getpeername_args *' to begin with. */
1690         return (getpeername1(td, (struct getpeername_args *)uap, 1));
1691 }
1692 #endif /* COMPAT_OLDSOCK */
1693
1694 int
1695 sockargs(mp, buf, buflen, type)
1696         struct mbuf **mp;
1697         caddr_t buf;
1698         int buflen, type;
1699 {
1700         struct sockaddr *sa;
1701         struct mbuf *m;
1702         int error;
1703
1704         if (buflen > MLEN) {
1705 #ifdef COMPAT_OLDSOCK
1706                 if (type == MT_SONAME && buflen <= 112)
1707                         buflen = MLEN;          /* unix domain compat. hack */
1708                 else
1709 #endif
1710                         if (buflen > MCLBYTES)
1711                                 return (EINVAL);
1712         }
1713         m = m_get2(buflen, M_WAITOK, type, 0);
1714         m->m_len = buflen;
1715         error = copyin(buf, mtod(m, caddr_t), (u_int)buflen);
1716         if (error)
1717                 (void) m_free(m);
1718         else {
1719                 *mp = m;
1720                 if (type == MT_SONAME) {
1721                         sa = mtod(m, struct sockaddr *);
1722
1723 #if defined(COMPAT_OLDSOCK) && BYTE_ORDER != BIG_ENDIAN
1724                         if (sa->sa_family == 0 && sa->sa_len < AF_MAX)
1725                                 sa->sa_family = sa->sa_len;
1726 #endif
1727                         sa->sa_len = buflen;
1728                 }
1729         }
1730         return (error);
1731 }
1732
1733 int
1734 getsockaddr(namp, uaddr, len)
1735         struct sockaddr **namp;
1736         caddr_t uaddr;
1737         size_t len;
1738 {
1739         struct sockaddr *sa;
1740         int error;
1741
1742         if (len > SOCK_MAXADDRLEN)
1743                 return (ENAMETOOLONG);
1744         if (len < offsetof(struct sockaddr, sa_data[0]))
1745                 return (EINVAL);
1746         sa = malloc(len, M_SONAME, M_WAITOK);
1747         error = copyin(uaddr, sa, len);
1748         if (error) {
1749                 free(sa, M_SONAME);
1750         } else {
1751 #if defined(COMPAT_OLDSOCK) && BYTE_ORDER != BIG_ENDIAN
1752                 if (sa->sa_family == 0 && sa->sa_len < AF_MAX)
1753                         sa->sa_family = sa->sa_len;
1754 #endif
1755                 sa->sa_len = len;
1756                 *namp = sa;
1757         }
1758         return (error);
1759 }
1760
1761 #include <sys/condvar.h>
1762
1763 struct sendfile_sync {
1764         struct mtx      mtx;
1765         struct cv       cv;
1766         unsigned        count;
1767 };
1768
1769 /*
1770  * Detach mapped page and release resources back to the system.
1771  */
1772 void
1773 sf_buf_mext(void *addr, void *args)
1774 {
1775         vm_page_t m;
1776         struct sendfile_sync *sfs;
1777
1778         m = sf_buf_page(args);
1779         sf_buf_free(args);
1780         vm_page_lock(m);
1781         vm_page_unwire(m, 0);
1782         /*
1783          * Check for the object going away on us. This can
1784          * happen since we don't hold a reference to it.
1785          * If so, we're responsible for freeing the page.
1786          */
1787         if (m->wire_count == 0 && m->object == NULL)
1788                 vm_page_free(m);
1789         vm_page_unlock(m);
1790         if (addr == NULL)
1791                 return;
1792         sfs = addr;
1793         mtx_lock(&sfs->mtx);
1794         KASSERT(sfs->count> 0, ("Sendfile sync botchup count == 0"));
1795         if (--sfs->count == 0)
1796                 cv_signal(&sfs->cv);
1797         mtx_unlock(&sfs->mtx);
1798 }
1799
1800 /*
1801  * sendfile(2)
1802  *
1803  * int sendfile(int fd, int s, off_t offset, size_t nbytes,
1804  *       struct sf_hdtr *hdtr, off_t *sbytes, int flags)
1805  *
1806  * Send a file specified by 'fd' and starting at 'offset' to a socket
1807  * specified by 's'. Send only 'nbytes' of the file or until EOF if nbytes ==
1808  * 0.  Optionally add a header and/or trailer to the socket output.  If
1809  * specified, write the total number of bytes sent into *sbytes.
1810  */
1811 int
1812 sys_sendfile(struct thread *td, struct sendfile_args *uap)
1813 {
1814
1815         return (do_sendfile(td, uap, 0));
1816 }
1817
1818 static int
1819 do_sendfile(struct thread *td, struct sendfile_args *uap, int compat)
1820 {
1821         struct sf_hdtr hdtr;
1822         struct uio *hdr_uio, *trl_uio;
1823         int error;
1824
1825         hdr_uio = trl_uio = NULL;
1826
1827         if (uap->hdtr != NULL) {
1828                 error = copyin(uap->hdtr, &hdtr, sizeof(hdtr));
1829                 if (error)
1830                         goto out;
1831                 if (hdtr.headers != NULL) {
1832                         error = copyinuio(hdtr.headers, hdtr.hdr_cnt, &hdr_uio);
1833                         if (error)
1834                                 goto out;
1835                 }
1836                 if (hdtr.trailers != NULL) {
1837                         error = copyinuio(hdtr.trailers, hdtr.trl_cnt, &trl_uio);
1838                         if (error)
1839                                 goto out;
1840
1841                 }
1842         }
1843
1844         error = kern_sendfile(td, uap, hdr_uio, trl_uio, compat);
1845 out:
1846         if (hdr_uio)
1847                 free(hdr_uio, M_IOV);
1848         if (trl_uio)
1849                 free(trl_uio, M_IOV);
1850         return (error);
1851 }
1852
1853 #ifdef COMPAT_FREEBSD4
1854 int
1855 freebsd4_sendfile(struct thread *td, struct freebsd4_sendfile_args *uap)
1856 {
1857         struct sendfile_args args;
1858
1859         args.fd = uap->fd;
1860         args.s = uap->s;
1861         args.offset = uap->offset;
1862         args.nbytes = uap->nbytes;
1863         args.hdtr = uap->hdtr;
1864         args.sbytes = uap->sbytes;
1865         args.flags = uap->flags;
1866
1867         return (do_sendfile(td, &args, 1));
1868 }
1869 #endif /* COMPAT_FREEBSD4 */
1870
1871 int
1872 kern_sendfile(struct thread *td, struct sendfile_args *uap,
1873     struct uio *hdr_uio, struct uio *trl_uio, int compat)
1874 {
1875         struct file *sock_fp;
1876         struct vnode *vp;
1877         struct vm_object *obj = NULL;
1878         struct socket *so = NULL;
1879         struct mbuf *m = NULL;
1880         struct sf_buf *sf;
1881         struct vm_page *pg;
1882         off_t off, xfsize, fsbytes = 0, sbytes = 0, rem = 0;
1883         int error, hdrlen = 0, mnw = 0;
1884         struct sendfile_sync *sfs = NULL;
1885
1886         /*
1887          * The file descriptor must be a regular file and have a
1888          * backing VM object.
1889          * File offset must be positive.  If it goes beyond EOF
1890          * we send only the header/trailer and no payload data.
1891          */
1892         AUDIT_ARG_FD(uap->fd);
1893         /*
1894          * sendfile(2) can start at any offset within a file so we require
1895          * CAP_READ+CAP_SEEK = CAP_PREAD.
1896          */
1897         if ((error = fgetvp_read(td, uap->fd, CAP_PREAD, &vp)) != 0)
1898                 goto out;
1899         vn_lock(vp, LK_SHARED | LK_RETRY);
1900         if (vp->v_type == VREG) {
1901                 obj = vp->v_object;
1902                 if (obj != NULL) {
1903                         /*
1904                          * Temporarily increase the backing VM
1905                          * object's reference count so that a forced
1906                          * reclamation of its vnode does not
1907                          * immediately destroy it.
1908                          */
1909                         VM_OBJECT_WLOCK(obj);
1910                         if ((obj->flags & OBJ_DEAD) == 0) {
1911                                 vm_object_reference_locked(obj);
1912                                 VM_OBJECT_WUNLOCK(obj);
1913                         } else {
1914                                 VM_OBJECT_WUNLOCK(obj);
1915                                 obj = NULL;
1916                         }
1917                 }
1918         }
1919         VOP_UNLOCK(vp, 0);
1920         if (obj == NULL) {
1921                 error = EINVAL;
1922                 goto out;
1923         }
1924         if (uap->offset < 0) {
1925                 error = EINVAL;
1926                 goto out;
1927         }
1928
1929         /*
1930          * The socket must be a stream socket and connected.
1931          * Remember if it a blocking or non-blocking socket.
1932          */
1933         if ((error = getsock_cap(td->td_proc->p_fd, uap->s, CAP_SEND,
1934             &sock_fp, NULL)) != 0)
1935                 goto out;
1936         so = sock_fp->f_data;
1937         if (so->so_type != SOCK_STREAM) {
1938                 error = EINVAL;
1939                 goto out;
1940         }
1941         if ((so->so_state & SS_ISCONNECTED) == 0) {
1942                 error = ENOTCONN;
1943                 goto out;
1944         }
1945         /*
1946          * Do not wait on memory allocations but return ENOMEM for
1947          * caller to retry later.
1948          * XXX: Experimental.
1949          */
1950         if (uap->flags & SF_MNOWAIT)
1951                 mnw = 1;
1952
1953         if (uap->flags & SF_SYNC) {
1954                 sfs = malloc(sizeof *sfs, M_TEMP, M_WAITOK | M_ZERO);
1955                 mtx_init(&sfs->mtx, "sendfile", NULL, MTX_DEF);
1956                 cv_init(&sfs->cv, "sendfile");
1957         }
1958
1959 #ifdef MAC
1960         error = mac_socket_check_send(td->td_ucred, so);
1961         if (error)
1962                 goto out;
1963 #endif
1964
1965         /* If headers are specified copy them into mbufs. */
1966         if (hdr_uio != NULL) {
1967                 hdr_uio->uio_td = td;
1968                 hdr_uio->uio_rw = UIO_WRITE;
1969                 if (hdr_uio->uio_resid > 0) {
1970                         /*
1971                          * In FBSD < 5.0 the nbytes to send also included
1972                          * the header.  If compat is specified subtract the
1973                          * header size from nbytes.
1974                          */
1975                         if (compat) {
1976                                 if (uap->nbytes > hdr_uio->uio_resid)
1977                                         uap->nbytes -= hdr_uio->uio_resid;
1978                                 else
1979                                         uap->nbytes = 0;
1980                         }
1981                         m = m_uiotombuf(hdr_uio, (mnw ? M_NOWAIT : M_WAITOK),
1982                             0, 0, 0);
1983                         if (m == NULL) {
1984                                 error = mnw ? EAGAIN : ENOBUFS;
1985                                 goto out;
1986                         }
1987                         hdrlen = m_length(m, NULL);
1988                 }
1989         }
1990
1991         /*
1992          * Protect against multiple writers to the socket.
1993          *
1994          * XXXRW: Historically this has assumed non-interruptibility, so now
1995          * we implement that, but possibly shouldn't.
1996          */
1997         (void)sblock(&so->so_snd, SBL_WAIT | SBL_NOINTR);
1998
1999         /*
2000          * Loop through the pages of the file, starting with the requested
2001          * offset. Get a file page (do I/O if necessary), map the file page
2002          * into an sf_buf, attach an mbuf header to the sf_buf, and queue
2003          * it on the socket.
2004          * This is done in two loops.  The inner loop turns as many pages
2005          * as it can, up to available socket buffer space, without blocking
2006          * into mbufs to have it bulk delivered into the socket send buffer.
2007          * The outer loop checks the state and available space of the socket
2008          * and takes care of the overall progress.
2009          */
2010         for (off = uap->offset, rem = uap->nbytes; ; ) {
2011                 struct mbuf *mtail = NULL;
2012                 int loopbytes = 0;
2013                 int space = 0;
2014                 int done = 0;
2015
2016                 /*
2017                  * Check the socket state for ongoing connection,
2018                  * no errors and space in socket buffer.
2019                  * If space is low allow for the remainder of the
2020                  * file to be processed if it fits the socket buffer.
2021                  * Otherwise block in waiting for sufficient space
2022                  * to proceed, or if the socket is nonblocking, return
2023                  * to userland with EAGAIN while reporting how far
2024                  * we've come.
2025                  * We wait until the socket buffer has significant free
2026                  * space to do bulk sends.  This makes good use of file
2027                  * system read ahead and allows packet segmentation
2028                  * offloading hardware to take over lots of work.  If
2029                  * we were not careful here we would send off only one
2030                  * sfbuf at a time.
2031                  */
2032                 SOCKBUF_LOCK(&so->so_snd);
2033                 if (so->so_snd.sb_lowat < so->so_snd.sb_hiwat / 2)
2034                         so->so_snd.sb_lowat = so->so_snd.sb_hiwat / 2;
2035 retry_space:
2036                 if (so->so_snd.sb_state & SBS_CANTSENDMORE) {
2037                         error = EPIPE;
2038                         SOCKBUF_UNLOCK(&so->so_snd);
2039                         goto done;
2040                 } else if (so->so_error) {
2041                         error = so->so_error;
2042                         so->so_error = 0;
2043                         SOCKBUF_UNLOCK(&so->so_snd);
2044                         goto done;
2045                 }
2046                 space = sbspace(&so->so_snd);
2047                 if (space < rem &&
2048                     (space <= 0 ||
2049                      space < so->so_snd.sb_lowat)) {
2050                         if (so->so_state & SS_NBIO) {
2051                                 SOCKBUF_UNLOCK(&so->so_snd);
2052                                 error = EAGAIN;
2053                                 goto done;
2054                         }
2055                         /*
2056                          * sbwait drops the lock while sleeping.
2057                          * When we loop back to retry_space the
2058                          * state may have changed and we retest
2059                          * for it.
2060                          */
2061                         error = sbwait(&so->so_snd);
2062                         /*
2063                          * An error from sbwait usually indicates that we've
2064                          * been interrupted by a signal. If we've sent anything
2065                          * then return bytes sent, otherwise return the error.
2066                          */
2067                         if (error) {
2068                                 SOCKBUF_UNLOCK(&so->so_snd);
2069                                 goto done;
2070                         }
2071                         goto retry_space;
2072                 }
2073                 SOCKBUF_UNLOCK(&so->so_snd);
2074
2075                 /*
2076                  * Reduce space in the socket buffer by the size of
2077                  * the header mbuf chain.
2078                  * hdrlen is set to 0 after the first loop.
2079                  */
2080                 space -= hdrlen;
2081
2082                 /*
2083                  * Loop and construct maximum sized mbuf chain to be bulk
2084                  * dumped into socket buffer.
2085                  */
2086                 while (space > loopbytes) {
2087                         vm_pindex_t pindex;
2088                         vm_offset_t pgoff;
2089                         struct mbuf *m0;
2090
2091                         VM_OBJECT_WLOCK(obj);
2092                         /*
2093                          * Calculate the amount to transfer.
2094                          * Not to exceed a page, the EOF,
2095                          * or the passed in nbytes.
2096                          */
2097                         pgoff = (vm_offset_t)(off & PAGE_MASK);
2098                         xfsize = omin(PAGE_SIZE - pgoff,
2099                             obj->un_pager.vnp.vnp_size - uap->offset -
2100                             fsbytes - loopbytes);
2101                         if (uap->nbytes)
2102                                 rem = (uap->nbytes - fsbytes - loopbytes);
2103                         else
2104                                 rem = obj->un_pager.vnp.vnp_size -
2105                                     uap->offset - fsbytes - loopbytes;
2106                         xfsize = omin(rem, xfsize);
2107                         xfsize = omin(space - loopbytes, xfsize);
2108                         if (xfsize <= 0) {
2109                                 VM_OBJECT_WUNLOCK(obj);
2110                                 done = 1;               /* all data sent */
2111                                 break;
2112                         }
2113
2114                         /*
2115                          * Attempt to look up the page.  Allocate
2116                          * if not found or wait and loop if busy.
2117                          */
2118                         pindex = OFF_TO_IDX(off);
2119                         pg = vm_page_grab(obj, pindex, VM_ALLOC_NOBUSY |
2120                             VM_ALLOC_NORMAL | VM_ALLOC_WIRED | VM_ALLOC_RETRY);
2121
2122                         /*
2123                          * Check if page is valid for what we need,
2124                          * otherwise initiate I/O.
2125                          * If we already turned some pages into mbufs,
2126                          * send them off before we come here again and
2127                          * block.
2128                          */
2129                         if (pg->valid && vm_page_is_valid(pg, pgoff, xfsize))
2130                                 VM_OBJECT_WUNLOCK(obj);
2131                         else if (m != NULL)
2132                                 error = EAGAIN; /* send what we already got */
2133                         else if (uap->flags & SF_NODISKIO)
2134                                 error = EBUSY;
2135                         else {
2136                                 int bsize;
2137                                 ssize_t resid;
2138
2139                                 /*
2140                                  * Ensure that our page is still around
2141                                  * when the I/O completes.
2142                                  */
2143                                 vm_page_io_start(pg);
2144                                 VM_OBJECT_WUNLOCK(obj);
2145
2146                                 /*
2147                                  * Get the page from backing store.
2148                                  */
2149                                 error = vn_lock(vp, LK_SHARED);
2150                                 if (error != 0)
2151                                         goto after_read;
2152                                 bsize = vp->v_mount->mnt_stat.f_iosize;
2153
2154                                 /*
2155                                  * XXXMAC: Because we don't have fp->f_cred
2156                                  * here, we pass in NOCRED.  This is probably
2157                                  * wrong, but is consistent with our original
2158                                  * implementation.
2159                                  */
2160                                 error = vn_rdwr(UIO_READ, vp, NULL, MAXBSIZE,
2161                                     trunc_page(off), UIO_NOCOPY, IO_NODELOCKED |
2162                                     IO_VMIO | ((MAXBSIZE / bsize) << IO_SEQSHIFT),
2163                                     td->td_ucred, NOCRED, &resid, td);
2164                                 VOP_UNLOCK(vp, 0);
2165                         after_read:
2166                                 VM_OBJECT_WLOCK(obj);
2167                                 vm_page_io_finish(pg);
2168                                 if (!error)
2169                                         VM_OBJECT_WUNLOCK(obj);
2170                                 mbstat.sf_iocnt++;
2171                         }
2172                         if (error) {
2173                                 vm_page_lock(pg);
2174                                 vm_page_unwire(pg, 0);
2175                                 /*
2176                                  * See if anyone else might know about
2177                                  * this page.  If not and it is not valid,
2178                                  * then free it.
2179                                  */
2180                                 if (pg->wire_count == 0 && pg->valid == 0 &&
2181                                     pg->busy == 0 && !(pg->oflags & VPO_BUSY))
2182                                         vm_page_free(pg);
2183                                 vm_page_unlock(pg);
2184                                 VM_OBJECT_WUNLOCK(obj);
2185                                 if (error == EAGAIN)
2186                                         error = 0;      /* not a real error */
2187                                 break;
2188                         }
2189
2190                         /*
2191                          * Get a sendfile buf.  When allocating the
2192                          * first buffer for mbuf chain, we usually
2193                          * wait as long as necessary, but this wait
2194                          * can be interrupted.  For consequent
2195                          * buffers, do not sleep, since several
2196                          * threads might exhaust the buffers and then
2197                          * deadlock.
2198                          */
2199                         sf = sf_buf_alloc(pg, (mnw || m != NULL) ? SFB_NOWAIT :
2200                             SFB_CATCH);
2201                         if (sf == NULL) {
2202                                 mbstat.sf_allocfail++;
2203                                 vm_page_lock(pg);
2204                                 vm_page_unwire(pg, 0);
2205                                 KASSERT(pg->object != NULL,
2206                                     ("kern_sendfile: object disappeared"));
2207                                 vm_page_unlock(pg);
2208                                 if (m == NULL)
2209                                         error = (mnw ? EAGAIN : EINTR);
2210                                 break;
2211                         }
2212
2213                         /*
2214                          * Get an mbuf and set it up as having
2215                          * external storage.
2216                          */
2217                         m0 = m_get((mnw ? M_NOWAIT : M_WAITOK), MT_DATA);
2218                         if (m0 == NULL) {
2219                                 error = (mnw ? EAGAIN : ENOBUFS);
2220                                 sf_buf_mext((void *)sf_buf_kva(sf), sf);
2221                                 break;
2222                         }
2223                         if (m_extadd(m0, (caddr_t )sf_buf_kva(sf), PAGE_SIZE,
2224                             sf_buf_mext, sfs, sf, M_RDONLY, EXT_SFBUF,
2225                             (mnw ? M_NOWAIT : M_WAITOK)) != 0) {
2226                                 error = (mnw ? EAGAIN : ENOBUFS);
2227                                 sf_buf_mext((void *)sf_buf_kva(sf), sf);
2228                                 m_freem(m0);
2229                                 break;
2230                         }
2231                         m0->m_data = (char *)sf_buf_kva(sf) + pgoff;
2232                         m0->m_len = xfsize;
2233
2234                         /* Append to mbuf chain. */
2235                         if (mtail != NULL)
2236                                 mtail->m_next = m0;
2237                         else if (m != NULL)
2238                                 m_last(m)->m_next = m0;
2239                         else
2240                                 m = m0;
2241                         mtail = m0;
2242
2243                         /* Keep track of bits processed. */
2244                         loopbytes += xfsize;
2245                         off += xfsize;
2246
2247                         if (sfs != NULL) {
2248                                 mtx_lock(&sfs->mtx);
2249                                 sfs->count++;
2250                                 mtx_unlock(&sfs->mtx);
2251                         }
2252                 }
2253
2254                 /* Add the buffer chain to the socket buffer. */
2255                 if (m != NULL) {
2256                         int mlen, err;
2257
2258                         mlen = m_length(m, NULL);
2259                         SOCKBUF_LOCK(&so->so_snd);
2260                         if (so->so_snd.sb_state & SBS_CANTSENDMORE) {
2261                                 error = EPIPE;
2262                                 SOCKBUF_UNLOCK(&so->so_snd);
2263                                 goto done;
2264                         }
2265                         SOCKBUF_UNLOCK(&so->so_snd);
2266                         CURVNET_SET(so->so_vnet);
2267                         /* Avoid error aliasing. */
2268                         err = (*so->so_proto->pr_usrreqs->pru_send)
2269                                     (so, 0, m, NULL, NULL, td);
2270                         CURVNET_RESTORE();
2271                         if (err == 0) {
2272                                 /*
2273                                  * We need two counters to get the
2274                                  * file offset and nbytes to send
2275                                  * right:
2276                                  * - sbytes contains the total amount
2277                                  *   of bytes sent, including headers.
2278                                  * - fsbytes contains the total amount
2279                                  *   of bytes sent from the file.
2280                                  */
2281                                 sbytes += mlen;
2282                                 fsbytes += mlen;
2283                                 if (hdrlen) {
2284                                         fsbytes -= hdrlen;
2285                                         hdrlen = 0;
2286                                 }
2287                         } else if (error == 0)
2288                                 error = err;
2289                         m = NULL;       /* pru_send always consumes */
2290                 }
2291
2292                 /* Quit outer loop on error or when we're done. */
2293                 if (done)
2294                         break;
2295                 if (error)
2296                         goto done;
2297         }
2298
2299         /*
2300          * Send trailers. Wimp out and use writev(2).
2301          */
2302         if (trl_uio != NULL) {
2303                 sbunlock(&so->so_snd);
2304                 error = kern_writev(td, uap->s, trl_uio);
2305                 if (error == 0)
2306                         sbytes += td->td_retval[0];
2307                 goto out;
2308         }
2309
2310 done:
2311         sbunlock(&so->so_snd);
2312 out:
2313         /*
2314          * If there was no error we have to clear td->td_retval[0]
2315          * because it may have been set by writev.
2316          */
2317         if (error == 0) {
2318                 td->td_retval[0] = 0;
2319         }
2320         if (uap->sbytes != NULL) {
2321                 copyout(&sbytes, uap->sbytes, sizeof(off_t));
2322         }
2323         if (obj != NULL)
2324                 vm_object_deallocate(obj);
2325         if (vp != NULL)
2326                 vrele(vp);
2327         if (so)
2328                 fdrop(sock_fp, td);
2329         if (m)
2330                 m_freem(m);
2331
2332         if (sfs != NULL) {
2333                 mtx_lock(&sfs->mtx);
2334                 if (sfs->count != 0)
2335                         cv_wait(&sfs->cv, &sfs->mtx);
2336                 KASSERT(sfs->count == 0, ("sendfile sync still busy"));
2337                 cv_destroy(&sfs->cv);
2338                 mtx_destroy(&sfs->mtx);
2339                 free(sfs, M_TEMP);
2340         }
2341
2342         if (error == ERESTART)
2343                 error = EINTR;
2344
2345         return (error);
2346 }
2347
2348 /*
2349  * SCTP syscalls.
2350  * Functionality only compiled in if SCTP is defined in the kernel Makefile,
2351  * otherwise all return EOPNOTSUPP.
2352  * XXX: We should make this loadable one day.
2353  */
2354 int
2355 sys_sctp_peeloff(td, uap)
2356         struct thread *td;
2357         struct sctp_peeloff_args /* {
2358                 int     sd;
2359                 caddr_t name;
2360         } */ *uap;
2361 {
2362 #if (defined(INET) || defined(INET6)) && defined(SCTP)
2363         struct file *nfp = NULL;
2364         int error;
2365         struct socket *head, *so;
2366         int fd;
2367         u_int fflag;
2368
2369         AUDIT_ARG_FD(uap->sd);
2370         error = fgetsock(td, uap->sd, CAP_PEELOFF, &head, &fflag);
2371         if (error)
2372                 goto done2;
2373         if (head->so_proto->pr_protocol != IPPROTO_SCTP) {
2374                 error = EOPNOTSUPP;
2375                 goto done;
2376         }
2377         error = sctp_can_peel_off(head, (sctp_assoc_t)uap->name);
2378         if (error)
2379                 goto done;
2380         /*
2381          * At this point we know we do have a assoc to pull
2382          * we proceed to get the fd setup. This may block
2383          * but that is ok.
2384          */
2385
2386         error = falloc(td, &nfp, &fd, 0);
2387         if (error)
2388                 goto done;
2389         td->td_retval[0] = fd;
2390
2391         CURVNET_SET(head->so_vnet);
2392         so = sonewconn(head, SS_ISCONNECTED);
2393         if (so == NULL) {
2394                 error = ENOMEM;
2395                 goto noconnection;
2396         }
2397         /*
2398          * Before changing the flags on the socket, we have to bump the
2399          * reference count.  Otherwise, if the protocol calls sofree(),
2400          * the socket will be released due to a zero refcount.
2401          */
2402         SOCK_LOCK(so);
2403         soref(so);                      /* file descriptor reference */
2404         SOCK_UNLOCK(so);
2405
2406         ACCEPT_LOCK();
2407
2408         TAILQ_REMOVE(&head->so_comp, so, so_list);
2409         head->so_qlen--;
2410         so->so_state |= (head->so_state & SS_NBIO);
2411         so->so_state &= ~SS_NOFDREF;
2412         so->so_qstate &= ~SQ_COMP;
2413         so->so_head = NULL;
2414         ACCEPT_UNLOCK();
2415         finit(nfp, fflag, DTYPE_SOCKET, so, &socketops);
2416         error = sctp_do_peeloff(head, so, (sctp_assoc_t)uap->name);
2417         if (error)
2418                 goto noconnection;
2419         if (head->so_sigio != NULL)
2420                 fsetown(fgetown(&head->so_sigio), &so->so_sigio);
2421
2422 noconnection:
2423         /*
2424          * close the new descriptor, assuming someone hasn't ripped it
2425          * out from under us.
2426          */
2427         if (error)
2428                 fdclose(td->td_proc->p_fd, nfp, fd, td);
2429
2430         /*
2431          * Release explicitly held references before returning.
2432          */
2433         CURVNET_RESTORE();
2434 done:
2435         if (nfp != NULL)
2436                 fdrop(nfp, td);
2437         fputsock(head);
2438 done2:
2439         return (error);
2440 #else  /* SCTP */
2441         return (EOPNOTSUPP);
2442 #endif /* SCTP */
2443 }
2444
2445 int
2446 sys_sctp_generic_sendmsg (td, uap)
2447         struct thread *td;
2448         struct sctp_generic_sendmsg_args /* {
2449                 int sd,
2450                 caddr_t msg,
2451                 int mlen,
2452                 caddr_t to,
2453                 __socklen_t tolen,
2454                 struct sctp_sndrcvinfo *sinfo,
2455                 int flags
2456         } */ *uap;
2457 {
2458 #if (defined(INET) || defined(INET6)) && defined(SCTP)
2459         struct sctp_sndrcvinfo sinfo, *u_sinfo = NULL;
2460         struct socket *so;
2461         struct file *fp = NULL;
2462         int error = 0, len;
2463         struct sockaddr *to = NULL;
2464 #ifdef KTRACE
2465         struct uio *ktruio = NULL;
2466 #endif
2467         struct uio auio;
2468         struct iovec iov[1];
2469         cap_rights_t rights;
2470
2471         if (uap->sinfo) {
2472                 error = copyin(uap->sinfo, &sinfo, sizeof (sinfo));
2473                 if (error)
2474                         return (error);
2475                 u_sinfo = &sinfo;
2476         }
2477
2478         rights = CAP_SEND;
2479         if (uap->tolen) {
2480                 error = getsockaddr(&to, uap->to, uap->tolen);
2481                 if (error) {
2482                         to = NULL;
2483                         goto sctp_bad2;
2484                 }
2485                 rights |= CAP_CONNECT;
2486         }
2487
2488         AUDIT_ARG_FD(uap->sd);
2489         error = getsock_cap(td->td_proc->p_fd, uap->sd, rights, &fp, NULL);
2490         if (error)
2491                 goto sctp_bad;
2492 #ifdef KTRACE
2493         if (to && (KTRPOINT(td, KTR_STRUCT)))
2494                 ktrsockaddr(to);
2495 #endif
2496
2497         iov[0].iov_base = uap->msg;
2498         iov[0].iov_len = uap->mlen;
2499
2500         so = (struct socket *)fp->f_data;
2501         if (so->so_proto->pr_protocol != IPPROTO_SCTP) {
2502                 error = EOPNOTSUPP;
2503                 goto sctp_bad;
2504         }
2505 #ifdef MAC
2506         error = mac_socket_check_send(td->td_ucred, so);
2507         if (error)
2508                 goto sctp_bad;
2509 #endif /* MAC */
2510
2511         auio.uio_iov =  iov;
2512         auio.uio_iovcnt = 1;
2513         auio.uio_segflg = UIO_USERSPACE;
2514         auio.uio_rw = UIO_WRITE;
2515         auio.uio_td = td;
2516         auio.uio_offset = 0;                    /* XXX */
2517         auio.uio_resid = 0;
2518         len = auio.uio_resid = uap->mlen;
2519         CURVNET_SET(so->so_vnet);
2520         error = sctp_lower_sosend(so, to, &auio,
2521                     (struct mbuf *)NULL, (struct mbuf *)NULL,
2522                     uap->flags, u_sinfo, td);
2523         CURVNET_RESTORE();
2524         if (error) {
2525                 if (auio.uio_resid != len && (error == ERESTART ||
2526                     error == EINTR || error == EWOULDBLOCK))
2527                         error = 0;
2528                 /* Generation of SIGPIPE can be controlled per socket. */
2529                 if (error == EPIPE && !(so->so_options & SO_NOSIGPIPE) &&
2530                     !(uap->flags & MSG_NOSIGNAL)) {
2531                         PROC_LOCK(td->td_proc);
2532                         tdsignal(td, SIGPIPE);
2533                         PROC_UNLOCK(td->td_proc);
2534                 }
2535         }
2536         if (error == 0)
2537                 td->td_retval[0] = len - auio.uio_resid;
2538 #ifdef KTRACE
2539         if (ktruio != NULL) {
2540                 ktruio->uio_resid = td->td_retval[0];
2541                 ktrgenio(uap->sd, UIO_WRITE, ktruio, error);
2542         }
2543 #endif /* KTRACE */
2544 sctp_bad:
2545         if (fp)
2546                 fdrop(fp, td);
2547 sctp_bad2:
2548         if (to)
2549                 free(to, M_SONAME);
2550         return (error);
2551 #else  /* SCTP */
2552         return (EOPNOTSUPP);
2553 #endif /* SCTP */
2554 }
2555
2556 int
2557 sys_sctp_generic_sendmsg_iov(td, uap)
2558         struct thread *td;
2559         struct sctp_generic_sendmsg_iov_args /* {
2560                 int sd,
2561                 struct iovec *iov,
2562                 int iovlen,
2563                 caddr_t to,
2564                 __socklen_t tolen,
2565                 struct sctp_sndrcvinfo *sinfo,
2566                 int flags
2567         } */ *uap;
2568 {
2569 #if (defined(INET) || defined(INET6)) && defined(SCTP)
2570         struct sctp_sndrcvinfo sinfo, *u_sinfo = NULL;
2571         struct socket *so;
2572         struct file *fp = NULL;
2573         int error=0, i;
2574         ssize_t len;
2575         struct sockaddr *to = NULL;
2576 #ifdef KTRACE
2577         struct uio *ktruio = NULL;
2578 #endif
2579         struct uio auio;
2580         struct iovec *iov, *tiov;
2581         cap_rights_t rights;
2582
2583         if (uap->sinfo) {
2584                 error = copyin(uap->sinfo, &sinfo, sizeof (sinfo));
2585                 if (error)
2586                         return (error);
2587                 u_sinfo = &sinfo;
2588         }
2589         rights = CAP_SEND;
2590         if (uap->tolen) {
2591                 error = getsockaddr(&to, uap->to, uap->tolen);
2592                 if (error) {
2593                         to = NULL;
2594                         goto sctp_bad2;
2595                 }
2596                 rights |= CAP_CONNECT;
2597         }
2598
2599         AUDIT_ARG_FD(uap->sd);
2600         error = getsock_cap(td->td_proc->p_fd, uap->sd, rights, &fp, NULL);
2601         if (error)
2602                 goto sctp_bad1;
2603
2604 #ifdef COMPAT_FREEBSD32
2605         if (SV_CURPROC_FLAG(SV_ILP32))
2606                 error = freebsd32_copyiniov((struct iovec32 *)uap->iov,
2607                     uap->iovlen, &iov, EMSGSIZE);
2608         else
2609 #endif
2610                 error = copyiniov(uap->iov, uap->iovlen, &iov, EMSGSIZE);
2611         if (error)
2612                 goto sctp_bad1;
2613 #ifdef KTRACE
2614         if (to && (KTRPOINT(td, KTR_STRUCT)))
2615                 ktrsockaddr(to);
2616 #endif
2617
2618         so = (struct socket *)fp->f_data;
2619         if (so->so_proto->pr_protocol != IPPROTO_SCTP) {
2620                 error = EOPNOTSUPP;
2621                 goto sctp_bad;
2622         }
2623 #ifdef MAC
2624         error = mac_socket_check_send(td->td_ucred, so);
2625         if (error)
2626                 goto sctp_bad;
2627 #endif /* MAC */
2628
2629         auio.uio_iov = iov;
2630         auio.uio_iovcnt = uap->iovlen;
2631         auio.uio_segflg = UIO_USERSPACE;
2632         auio.uio_rw = UIO_WRITE;
2633         auio.uio_td = td;
2634         auio.uio_offset = 0;                    /* XXX */
2635         auio.uio_resid = 0;
2636         tiov = iov;
2637         for (i = 0; i <uap->iovlen; i++, tiov++) {
2638                 if ((auio.uio_resid += tiov->iov_len) < 0) {
2639                         error = EINVAL;
2640                         goto sctp_bad;
2641                 }
2642         }
2643         len = auio.uio_resid;
2644         CURVNET_SET(so->so_vnet);
2645         error = sctp_lower_sosend(so, to, &auio,
2646                     (struct mbuf *)NULL, (struct mbuf *)NULL,
2647                     uap->flags, u_sinfo, td);
2648         CURVNET_RESTORE();
2649         if (error) {
2650                 if (auio.uio_resid != len && (error == ERESTART ||
2651                     error == EINTR || error == EWOULDBLOCK))
2652                         error = 0;
2653                 /* Generation of SIGPIPE can be controlled per socket */
2654                 if (error == EPIPE && !(so->so_options & SO_NOSIGPIPE) &&
2655                     !(uap->flags & MSG_NOSIGNAL)) {
2656                         PROC_LOCK(td->td_proc);
2657                         tdsignal(td, SIGPIPE);
2658                         PROC_UNLOCK(td->td_proc);
2659                 }
2660         }
2661         if (error == 0)
2662                 td->td_retval[0] = len - auio.uio_resid;
2663 #ifdef KTRACE
2664         if (ktruio != NULL) {
2665                 ktruio->uio_resid = td->td_retval[0];
2666                 ktrgenio(uap->sd, UIO_WRITE, ktruio, error);
2667         }
2668 #endif /* KTRACE */
2669 sctp_bad:
2670         free(iov, M_IOV);
2671 sctp_bad1:
2672         if (fp)
2673                 fdrop(fp, td);
2674 sctp_bad2:
2675         if (to)
2676                 free(to, M_SONAME);
2677         return (error);
2678 #else  /* SCTP */
2679         return (EOPNOTSUPP);
2680 #endif /* SCTP */
2681 }
2682
2683 int
2684 sys_sctp_generic_recvmsg(td, uap)
2685         struct thread *td;
2686         struct sctp_generic_recvmsg_args /* {
2687                 int sd,
2688                 struct iovec *iov,
2689                 int iovlen,
2690                 struct sockaddr *from,
2691                 __socklen_t *fromlenaddr,
2692                 struct sctp_sndrcvinfo *sinfo,
2693                 int *msg_flags
2694         } */ *uap;
2695 {
2696 #if (defined(INET) || defined(INET6)) && defined(SCTP)
2697         uint8_t sockbufstore[256];
2698         struct uio auio;
2699         struct iovec *iov, *tiov;
2700         struct sctp_sndrcvinfo sinfo;
2701         struct socket *so;
2702         struct file *fp = NULL;
2703         struct sockaddr *fromsa;
2704         int fromlen;
2705         ssize_t len;
2706         int i, msg_flags;
2707         int error = 0;
2708 #ifdef KTRACE
2709         struct uio *ktruio = NULL;
2710 #endif
2711
2712         AUDIT_ARG_FD(uap->sd);
2713         error = getsock_cap(td->td_proc->p_fd, uap->sd, CAP_RECV, &fp, NULL);
2714         if (error) {
2715                 return (error);
2716         }
2717 #ifdef COMPAT_FREEBSD32
2718         if (SV_CURPROC_FLAG(SV_ILP32))
2719                 error = freebsd32_copyiniov((struct iovec32 *)uap->iov,
2720                     uap->iovlen, &iov, EMSGSIZE);
2721         else
2722 #endif
2723                 error = copyiniov(uap->iov, uap->iovlen, &iov, EMSGSIZE);
2724         if (error)
2725                 goto out1;
2726
2727         so = fp->f_data;
2728         if (so->so_proto->pr_protocol != IPPROTO_SCTP) {
2729                 error = EOPNOTSUPP;
2730                 goto out;
2731         }
2732 #ifdef MAC
2733         error = mac_socket_check_receive(td->td_ucred, so);
2734         if (error) {
2735                 goto out;
2736         }
2737 #endif /* MAC */
2738
2739         if (uap->fromlenaddr) {
2740                 error = copyin(uap->fromlenaddr,
2741                     &fromlen, sizeof (fromlen));
2742                 if (error) {
2743                         goto out;
2744                 }
2745         } else {
2746                 fromlen = 0;
2747         }
2748         if (uap->msg_flags) {
2749                 error = copyin(uap->msg_flags, &msg_flags, sizeof (int));
2750                 if (error) {
2751                         goto out;
2752                 }
2753         } else {
2754                 msg_flags = 0;
2755         }
2756         auio.uio_iov = iov;
2757         auio.uio_iovcnt = uap->iovlen;
2758         auio.uio_segflg = UIO_USERSPACE;
2759         auio.uio_rw = UIO_READ;
2760         auio.uio_td = td;
2761         auio.uio_offset = 0;                    /* XXX */
2762         auio.uio_resid = 0;
2763         tiov = iov;
2764         for (i = 0; i <uap->iovlen; i++, tiov++) {
2765                 if ((auio.uio_resid += tiov->iov_len) < 0) {
2766                         error = EINVAL;
2767                         goto out;
2768                 }
2769         }
2770         len = auio.uio_resid;
2771         fromsa = (struct sockaddr *)sockbufstore;
2772
2773 #ifdef KTRACE
2774         if (KTRPOINT(td, KTR_GENIO))
2775                 ktruio = cloneuio(&auio);
2776 #endif /* KTRACE */
2777         memset(&sinfo, 0, sizeof(struct sctp_sndrcvinfo));
2778         CURVNET_SET(so->so_vnet);
2779         error = sctp_sorecvmsg(so, &auio, (struct mbuf **)NULL,
2780                     fromsa, fromlen, &msg_flags,
2781                     (struct sctp_sndrcvinfo *)&sinfo, 1);
2782         CURVNET_RESTORE();
2783         if (error) {
2784                 if (auio.uio_resid != len && (error == ERESTART ||
2785                     error == EINTR || error == EWOULDBLOCK))
2786                         error = 0;
2787         } else {
2788                 if (uap->sinfo)
2789                         error = copyout(&sinfo, uap->sinfo, sizeof (sinfo));
2790         }
2791 #ifdef KTRACE
2792         if (ktruio != NULL) {
2793                 ktruio->uio_resid = len - auio.uio_resid;
2794                 ktrgenio(uap->sd, UIO_READ, ktruio, error);
2795         }
2796 #endif /* KTRACE */
2797         if (error)
2798                 goto out;
2799         td->td_retval[0] = len - auio.uio_resid;
2800
2801         if (fromlen && uap->from) {
2802                 len = fromlen;
2803                 if (len <= 0 || fromsa == 0)
2804                         len = 0;
2805                 else {
2806                         len = MIN(len, fromsa->sa_len);
2807                         error = copyout(fromsa, uap->from, (size_t)len);
2808                         if (error)
2809                                 goto out;
2810                 }
2811                 error = copyout(&len, uap->fromlenaddr, sizeof (socklen_t));
2812                 if (error) {
2813                         goto out;
2814                 }
2815         }
2816 #ifdef KTRACE
2817         if (KTRPOINT(td, KTR_STRUCT))
2818                 ktrsockaddr(fromsa);
2819 #endif
2820         if (uap->msg_flags) {
2821                 error = copyout(&msg_flags, uap->msg_flags, sizeof (int));
2822                 if (error) {
2823                         goto out;
2824                 }
2825         }
2826 out:
2827         free(iov, M_IOV);
2828 out1:
2829         if (fp)
2830                 fdrop(fp, td);
2831
2832         return (error);
2833 #else  /* SCTP */
2834         return (EOPNOTSUPP);
2835 #endif /* SCTP */
2836 }