]> CyberLeo.Net >> Repos - FreeBSD/FreeBSD.git/blob - sys/kern/uipc_syscalls.c
In kern_sendfile() use m_extadd() instead of MEXTADD() macro, supplying
[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 ((u_int)buflen > MLEN) {
1705 #ifdef COMPAT_OLDSOCK
1706                 if (type == MT_SONAME && (u_int)buflen <= 112)
1707                         buflen = MLEN;          /* unix domain compat. hack */
1708                 else
1709 #endif
1710                         if ((u_int)buflen > MCLBYTES)
1711                                 return (EINVAL);
1712         }
1713         m = m_get(M_WAITOK, type);
1714         if ((u_int)buflen > MLEN)
1715                 MCLGET(m, M_WAITOK);
1716         m->m_len = buflen;
1717         error = copyin(buf, mtod(m, caddr_t), (u_int)buflen);
1718         if (error)
1719                 (void) m_free(m);
1720         else {
1721                 *mp = m;
1722                 if (type == MT_SONAME) {
1723                         sa = mtod(m, struct sockaddr *);
1724
1725 #if defined(COMPAT_OLDSOCK) && BYTE_ORDER != BIG_ENDIAN
1726                         if (sa->sa_family == 0 && sa->sa_len < AF_MAX)
1727                                 sa->sa_family = sa->sa_len;
1728 #endif
1729                         sa->sa_len = buflen;
1730                 }
1731         }
1732         return (error);
1733 }
1734
1735 int
1736 getsockaddr(namp, uaddr, len)
1737         struct sockaddr **namp;
1738         caddr_t uaddr;
1739         size_t len;
1740 {
1741         struct sockaddr *sa;
1742         int error;
1743
1744         if (len > SOCK_MAXADDRLEN)
1745                 return (ENAMETOOLONG);
1746         if (len < offsetof(struct sockaddr, sa_data[0]))
1747                 return (EINVAL);
1748         sa = malloc(len, M_SONAME, M_WAITOK);
1749         error = copyin(uaddr, sa, len);
1750         if (error) {
1751                 free(sa, M_SONAME);
1752         } else {
1753 #if defined(COMPAT_OLDSOCK) && BYTE_ORDER != BIG_ENDIAN
1754                 if (sa->sa_family == 0 && sa->sa_len < AF_MAX)
1755                         sa->sa_family = sa->sa_len;
1756 #endif
1757                 sa->sa_len = len;
1758                 *namp = sa;
1759         }
1760         return (error);
1761 }
1762
1763 #include <sys/condvar.h>
1764
1765 struct sendfile_sync {
1766         struct mtx      mtx;
1767         struct cv       cv;
1768         unsigned        count;
1769 };
1770
1771 /*
1772  * Detach mapped page and release resources back to the system.
1773  */
1774 void
1775 sf_buf_mext(void *addr, void *args)
1776 {
1777         vm_page_t m;
1778         struct sendfile_sync *sfs;
1779
1780         m = sf_buf_page(args);
1781         sf_buf_free(args);
1782         vm_page_lock(m);
1783         vm_page_unwire(m, 0);
1784         /*
1785          * Check for the object going away on us. This can
1786          * happen since we don't hold a reference to it.
1787          * If so, we're responsible for freeing the page.
1788          */
1789         if (m->wire_count == 0 && m->object == NULL)
1790                 vm_page_free(m);
1791         vm_page_unlock(m);
1792         if (addr == NULL)
1793                 return;
1794         sfs = addr;
1795         mtx_lock(&sfs->mtx);
1796         KASSERT(sfs->count> 0, ("Sendfile sync botchup count == 0"));
1797         if (--sfs->count == 0)
1798                 cv_signal(&sfs->cv);
1799         mtx_unlock(&sfs->mtx);
1800 }
1801
1802 /*
1803  * sendfile(2)
1804  *
1805  * int sendfile(int fd, int s, off_t offset, size_t nbytes,
1806  *       struct sf_hdtr *hdtr, off_t *sbytes, int flags)
1807  *
1808  * Send a file specified by 'fd' and starting at 'offset' to a socket
1809  * specified by 's'. Send only 'nbytes' of the file or until EOF if nbytes ==
1810  * 0.  Optionally add a header and/or trailer to the socket output.  If
1811  * specified, write the total number of bytes sent into *sbytes.
1812  */
1813 int
1814 sys_sendfile(struct thread *td, struct sendfile_args *uap)
1815 {
1816
1817         return (do_sendfile(td, uap, 0));
1818 }
1819
1820 static int
1821 do_sendfile(struct thread *td, struct sendfile_args *uap, int compat)
1822 {
1823         struct sf_hdtr hdtr;
1824         struct uio *hdr_uio, *trl_uio;
1825         int error;
1826
1827         hdr_uio = trl_uio = NULL;
1828
1829         if (uap->hdtr != NULL) {
1830                 error = copyin(uap->hdtr, &hdtr, sizeof(hdtr));
1831                 if (error)
1832                         goto out;
1833                 if (hdtr.headers != NULL) {
1834                         error = copyinuio(hdtr.headers, hdtr.hdr_cnt, &hdr_uio);
1835                         if (error)
1836                                 goto out;
1837                 }
1838                 if (hdtr.trailers != NULL) {
1839                         error = copyinuio(hdtr.trailers, hdtr.trl_cnt, &trl_uio);
1840                         if (error)
1841                                 goto out;
1842
1843                 }
1844         }
1845
1846         error = kern_sendfile(td, uap, hdr_uio, trl_uio, compat);
1847 out:
1848         if (hdr_uio)
1849                 free(hdr_uio, M_IOV);
1850         if (trl_uio)
1851                 free(trl_uio, M_IOV);
1852         return (error);
1853 }
1854
1855 #ifdef COMPAT_FREEBSD4
1856 int
1857 freebsd4_sendfile(struct thread *td, struct freebsd4_sendfile_args *uap)
1858 {
1859         struct sendfile_args args;
1860
1861         args.fd = uap->fd;
1862         args.s = uap->s;
1863         args.offset = uap->offset;
1864         args.nbytes = uap->nbytes;
1865         args.hdtr = uap->hdtr;
1866         args.sbytes = uap->sbytes;
1867         args.flags = uap->flags;
1868
1869         return (do_sendfile(td, &args, 1));
1870 }
1871 #endif /* COMPAT_FREEBSD4 */
1872
1873 int
1874 kern_sendfile(struct thread *td, struct sendfile_args *uap,
1875     struct uio *hdr_uio, struct uio *trl_uio, int compat)
1876 {
1877         struct file *sock_fp;
1878         struct vnode *vp;
1879         struct vm_object *obj = NULL;
1880         struct socket *so = NULL;
1881         struct mbuf *m = NULL;
1882         struct sf_buf *sf;
1883         struct vm_page *pg;
1884         off_t off, xfsize, fsbytes = 0, sbytes = 0, rem = 0;
1885         int error, hdrlen = 0, mnw = 0;
1886         struct sendfile_sync *sfs = NULL;
1887
1888         /*
1889          * The file descriptor must be a regular file and have a
1890          * backing VM object.
1891          * File offset must be positive.  If it goes beyond EOF
1892          * we send only the header/trailer and no payload data.
1893          */
1894         AUDIT_ARG_FD(uap->fd);
1895         /*
1896          * sendfile(2) can start at any offset within a file so we require
1897          * CAP_READ+CAP_SEEK = CAP_PREAD.
1898          */
1899         if ((error = fgetvp_read(td, uap->fd, CAP_PREAD, &vp)) != 0)
1900                 goto out;
1901         vn_lock(vp, LK_SHARED | LK_RETRY);
1902         if (vp->v_type == VREG) {
1903                 obj = vp->v_object;
1904                 if (obj != NULL) {
1905                         /*
1906                          * Temporarily increase the backing VM
1907                          * object's reference count so that a forced
1908                          * reclamation of its vnode does not
1909                          * immediately destroy it.
1910                          */
1911                         VM_OBJECT_WLOCK(obj);
1912                         if ((obj->flags & OBJ_DEAD) == 0) {
1913                                 vm_object_reference_locked(obj);
1914                                 VM_OBJECT_WUNLOCK(obj);
1915                         } else {
1916                                 VM_OBJECT_WUNLOCK(obj);
1917                                 obj = NULL;
1918                         }
1919                 }
1920         }
1921         VOP_UNLOCK(vp, 0);
1922         if (obj == NULL) {
1923                 error = EINVAL;
1924                 goto out;
1925         }
1926         if (uap->offset < 0) {
1927                 error = EINVAL;
1928                 goto out;
1929         }
1930
1931         /*
1932          * The socket must be a stream socket and connected.
1933          * Remember if it a blocking or non-blocking socket.
1934          */
1935         if ((error = getsock_cap(td->td_proc->p_fd, uap->s, CAP_SEND,
1936             &sock_fp, NULL)) != 0)
1937                 goto out;
1938         so = sock_fp->f_data;
1939         if (so->so_type != SOCK_STREAM) {
1940                 error = EINVAL;
1941                 goto out;
1942         }
1943         if ((so->so_state & SS_ISCONNECTED) == 0) {
1944                 error = ENOTCONN;
1945                 goto out;
1946         }
1947         /*
1948          * Do not wait on memory allocations but return ENOMEM for
1949          * caller to retry later.
1950          * XXX: Experimental.
1951          */
1952         if (uap->flags & SF_MNOWAIT)
1953                 mnw = 1;
1954
1955         if (uap->flags & SF_SYNC) {
1956                 sfs = malloc(sizeof *sfs, M_TEMP, M_WAITOK | M_ZERO);
1957                 mtx_init(&sfs->mtx, "sendfile", NULL, MTX_DEF);
1958                 cv_init(&sfs->cv, "sendfile");
1959         }
1960
1961 #ifdef MAC
1962         error = mac_socket_check_send(td->td_ucred, so);
1963         if (error)
1964                 goto out;
1965 #endif
1966
1967         /* If headers are specified copy them into mbufs. */
1968         if (hdr_uio != NULL) {
1969                 hdr_uio->uio_td = td;
1970                 hdr_uio->uio_rw = UIO_WRITE;
1971                 if (hdr_uio->uio_resid > 0) {
1972                         /*
1973                          * In FBSD < 5.0 the nbytes to send also included
1974                          * the header.  If compat is specified subtract the
1975                          * header size from nbytes.
1976                          */
1977                         if (compat) {
1978                                 if (uap->nbytes > hdr_uio->uio_resid)
1979                                         uap->nbytes -= hdr_uio->uio_resid;
1980                                 else
1981                                         uap->nbytes = 0;
1982                         }
1983                         m = m_uiotombuf(hdr_uio, (mnw ? M_NOWAIT : M_WAITOK),
1984                             0, 0, 0);
1985                         if (m == NULL) {
1986                                 error = mnw ? EAGAIN : ENOBUFS;
1987                                 goto out;
1988                         }
1989                         hdrlen = m_length(m, NULL);
1990                 }
1991         }
1992
1993         /*
1994          * Protect against multiple writers to the socket.
1995          *
1996          * XXXRW: Historically this has assumed non-interruptibility, so now
1997          * we implement that, but possibly shouldn't.
1998          */
1999         (void)sblock(&so->so_snd, SBL_WAIT | SBL_NOINTR);
2000
2001         /*
2002          * Loop through the pages of the file, starting with the requested
2003          * offset. Get a file page (do I/O if necessary), map the file page
2004          * into an sf_buf, attach an mbuf header to the sf_buf, and queue
2005          * it on the socket.
2006          * This is done in two loops.  The inner loop turns as many pages
2007          * as it can, up to available socket buffer space, without blocking
2008          * into mbufs to have it bulk delivered into the socket send buffer.
2009          * The outer loop checks the state and available space of the socket
2010          * and takes care of the overall progress.
2011          */
2012         for (off = uap->offset, rem = uap->nbytes; ; ) {
2013                 struct mbuf *mtail = NULL;
2014                 int loopbytes = 0;
2015                 int space = 0;
2016                 int done = 0;
2017
2018                 /*
2019                  * Check the socket state for ongoing connection,
2020                  * no errors and space in socket buffer.
2021                  * If space is low allow for the remainder of the
2022                  * file to be processed if it fits the socket buffer.
2023                  * Otherwise block in waiting for sufficient space
2024                  * to proceed, or if the socket is nonblocking, return
2025                  * to userland with EAGAIN while reporting how far
2026                  * we've come.
2027                  * We wait until the socket buffer has significant free
2028                  * space to do bulk sends.  This makes good use of file
2029                  * system read ahead and allows packet segmentation
2030                  * offloading hardware to take over lots of work.  If
2031                  * we were not careful here we would send off only one
2032                  * sfbuf at a time.
2033                  */
2034                 SOCKBUF_LOCK(&so->so_snd);
2035                 if (so->so_snd.sb_lowat < so->so_snd.sb_hiwat / 2)
2036                         so->so_snd.sb_lowat = so->so_snd.sb_hiwat / 2;
2037 retry_space:
2038                 if (so->so_snd.sb_state & SBS_CANTSENDMORE) {
2039                         error = EPIPE;
2040                         SOCKBUF_UNLOCK(&so->so_snd);
2041                         goto done;
2042                 } else if (so->so_error) {
2043                         error = so->so_error;
2044                         so->so_error = 0;
2045                         SOCKBUF_UNLOCK(&so->so_snd);
2046                         goto done;
2047                 }
2048                 space = sbspace(&so->so_snd);
2049                 if (space < rem &&
2050                     (space <= 0 ||
2051                      space < so->so_snd.sb_lowat)) {
2052                         if (so->so_state & SS_NBIO) {
2053                                 SOCKBUF_UNLOCK(&so->so_snd);
2054                                 error = EAGAIN;
2055                                 goto done;
2056                         }
2057                         /*
2058                          * sbwait drops the lock while sleeping.
2059                          * When we loop back to retry_space the
2060                          * state may have changed and we retest
2061                          * for it.
2062                          */
2063                         error = sbwait(&so->so_snd);
2064                         /*
2065                          * An error from sbwait usually indicates that we've
2066                          * been interrupted by a signal. If we've sent anything
2067                          * then return bytes sent, otherwise return the error.
2068                          */
2069                         if (error) {
2070                                 SOCKBUF_UNLOCK(&so->so_snd);
2071                                 goto done;
2072                         }
2073                         goto retry_space;
2074                 }
2075                 SOCKBUF_UNLOCK(&so->so_snd);
2076
2077                 /*
2078                  * Reduce space in the socket buffer by the size of
2079                  * the header mbuf chain.
2080                  * hdrlen is set to 0 after the first loop.
2081                  */
2082                 space -= hdrlen;
2083
2084                 /*
2085                  * Loop and construct maximum sized mbuf chain to be bulk
2086                  * dumped into socket buffer.
2087                  */
2088                 while (space > loopbytes) {
2089                         vm_pindex_t pindex;
2090                         vm_offset_t pgoff;
2091                         struct mbuf *m0;
2092
2093                         VM_OBJECT_WLOCK(obj);
2094                         /*
2095                          * Calculate the amount to transfer.
2096                          * Not to exceed a page, the EOF,
2097                          * or the passed in nbytes.
2098                          */
2099                         pgoff = (vm_offset_t)(off & PAGE_MASK);
2100                         xfsize = omin(PAGE_SIZE - pgoff,
2101                             obj->un_pager.vnp.vnp_size - uap->offset -
2102                             fsbytes - loopbytes);
2103                         if (uap->nbytes)
2104                                 rem = (uap->nbytes - fsbytes - loopbytes);
2105                         else
2106                                 rem = obj->un_pager.vnp.vnp_size -
2107                                     uap->offset - fsbytes - loopbytes;
2108                         xfsize = omin(rem, xfsize);
2109                         xfsize = omin(space - loopbytes, xfsize);
2110                         if (xfsize <= 0) {
2111                                 VM_OBJECT_WUNLOCK(obj);
2112                                 done = 1;               /* all data sent */
2113                                 break;
2114                         }
2115
2116                         /*
2117                          * Attempt to look up the page.  Allocate
2118                          * if not found or wait and loop if busy.
2119                          */
2120                         pindex = OFF_TO_IDX(off);
2121                         pg = vm_page_grab(obj, pindex, VM_ALLOC_NOBUSY |
2122                             VM_ALLOC_NORMAL | VM_ALLOC_WIRED | VM_ALLOC_RETRY);
2123
2124                         /*
2125                          * Check if page is valid for what we need,
2126                          * otherwise initiate I/O.
2127                          * If we already turned some pages into mbufs,
2128                          * send them off before we come here again and
2129                          * block.
2130                          */
2131                         if (pg->valid && vm_page_is_valid(pg, pgoff, xfsize))
2132                                 VM_OBJECT_WUNLOCK(obj);
2133                         else if (m != NULL)
2134                                 error = EAGAIN; /* send what we already got */
2135                         else if (uap->flags & SF_NODISKIO)
2136                                 error = EBUSY;
2137                         else {
2138                                 int bsize;
2139                                 ssize_t resid;
2140
2141                                 /*
2142                                  * Ensure that our page is still around
2143                                  * when the I/O completes.
2144                                  */
2145                                 vm_page_io_start(pg);
2146                                 VM_OBJECT_WUNLOCK(obj);
2147
2148                                 /*
2149                                  * Get the page from backing store.
2150                                  */
2151                                 error = vn_lock(vp, LK_SHARED);
2152                                 if (error != 0)
2153                                         goto after_read;
2154                                 bsize = vp->v_mount->mnt_stat.f_iosize;
2155
2156                                 /*
2157                                  * XXXMAC: Because we don't have fp->f_cred
2158                                  * here, we pass in NOCRED.  This is probably
2159                                  * wrong, but is consistent with our original
2160                                  * implementation.
2161                                  */
2162                                 error = vn_rdwr(UIO_READ, vp, NULL, MAXBSIZE,
2163                                     trunc_page(off), UIO_NOCOPY, IO_NODELOCKED |
2164                                     IO_VMIO | ((MAXBSIZE / bsize) << IO_SEQSHIFT),
2165                                     td->td_ucred, NOCRED, &resid, td);
2166                                 VOP_UNLOCK(vp, 0);
2167                         after_read:
2168                                 VM_OBJECT_WLOCK(obj);
2169                                 vm_page_io_finish(pg);
2170                                 if (!error)
2171                                         VM_OBJECT_WUNLOCK(obj);
2172                                 mbstat.sf_iocnt++;
2173                         }
2174                         if (error) {
2175                                 vm_page_lock(pg);
2176                                 vm_page_unwire(pg, 0);
2177                                 /*
2178                                  * See if anyone else might know about
2179                                  * this page.  If not and it is not valid,
2180                                  * then free it.
2181                                  */
2182                                 if (pg->wire_count == 0 && pg->valid == 0 &&
2183                                     pg->busy == 0 && !(pg->oflags & VPO_BUSY))
2184                                         vm_page_free(pg);
2185                                 vm_page_unlock(pg);
2186                                 VM_OBJECT_WUNLOCK(obj);
2187                                 if (error == EAGAIN)
2188                                         error = 0;      /* not a real error */
2189                                 break;
2190                         }
2191
2192                         /*
2193                          * Get a sendfile buf.  When allocating the
2194                          * first buffer for mbuf chain, we usually
2195                          * wait as long as necessary, but this wait
2196                          * can be interrupted.  For consequent
2197                          * buffers, do not sleep, since several
2198                          * threads might exhaust the buffers and then
2199                          * deadlock.
2200                          */
2201                         sf = sf_buf_alloc(pg, (mnw || m != NULL) ? SFB_NOWAIT :
2202                             SFB_CATCH);
2203                         if (sf == NULL) {
2204                                 mbstat.sf_allocfail++;
2205                                 vm_page_lock(pg);
2206                                 vm_page_unwire(pg, 0);
2207                                 KASSERT(pg->object != NULL,
2208                                     ("kern_sendfile: object disappeared"));
2209                                 vm_page_unlock(pg);
2210                                 if (m == NULL)
2211                                         error = (mnw ? EAGAIN : EINTR);
2212                                 break;
2213                         }
2214
2215                         /*
2216                          * Get an mbuf and set it up as having
2217                          * external storage.
2218                          */
2219                         m0 = m_get((mnw ? M_NOWAIT : M_WAITOK), MT_DATA);
2220                         if (m0 == NULL) {
2221                                 error = (mnw ? EAGAIN : ENOBUFS);
2222                                 sf_buf_mext((void *)sf_buf_kva(sf), sf);
2223                                 break;
2224                         }
2225                         if (m_extadd(m0, (caddr_t )sf_buf_kva(sf), PAGE_SIZE,
2226                             sf_buf_mext, sfs, sf, M_RDONLY, EXT_SFBUF,
2227                             (mnw ? M_NOWAIT : M_WAITOK)) != 0) {
2228                                 error = (mnw ? EAGAIN : ENOBUFS);
2229                                 sf_buf_mext((void *)sf_buf_kva(sf), sf);
2230                                 m_freem(m0);
2231                                 break;
2232                         }
2233                         m0->m_data = (char *)sf_buf_kva(sf) + pgoff;
2234                         m0->m_len = xfsize;
2235
2236                         /* Append to mbuf chain. */
2237                         if (mtail != NULL)
2238                                 mtail->m_next = m0;
2239                         else if (m != NULL)
2240                                 m_last(m)->m_next = m0;
2241                         else
2242                                 m = m0;
2243                         mtail = m0;
2244
2245                         /* Keep track of bits processed. */
2246                         loopbytes += xfsize;
2247                         off += xfsize;
2248
2249                         if (sfs != NULL) {
2250                                 mtx_lock(&sfs->mtx);
2251                                 sfs->count++;
2252                                 mtx_unlock(&sfs->mtx);
2253                         }
2254                 }
2255
2256                 /* Add the buffer chain to the socket buffer. */
2257                 if (m != NULL) {
2258                         int mlen, err;
2259
2260                         mlen = m_length(m, NULL);
2261                         SOCKBUF_LOCK(&so->so_snd);
2262                         if (so->so_snd.sb_state & SBS_CANTSENDMORE) {
2263                                 error = EPIPE;
2264                                 SOCKBUF_UNLOCK(&so->so_snd);
2265                                 goto done;
2266                         }
2267                         SOCKBUF_UNLOCK(&so->so_snd);
2268                         CURVNET_SET(so->so_vnet);
2269                         /* Avoid error aliasing. */
2270                         err = (*so->so_proto->pr_usrreqs->pru_send)
2271                                     (so, 0, m, NULL, NULL, td);
2272                         CURVNET_RESTORE();
2273                         if (err == 0) {
2274                                 /*
2275                                  * We need two counters to get the
2276                                  * file offset and nbytes to send
2277                                  * right:
2278                                  * - sbytes contains the total amount
2279                                  *   of bytes sent, including headers.
2280                                  * - fsbytes contains the total amount
2281                                  *   of bytes sent from the file.
2282                                  */
2283                                 sbytes += mlen;
2284                                 fsbytes += mlen;
2285                                 if (hdrlen) {
2286                                         fsbytes -= hdrlen;
2287                                         hdrlen = 0;
2288                                 }
2289                         } else if (error == 0)
2290                                 error = err;
2291                         m = NULL;       /* pru_send always consumes */
2292                 }
2293
2294                 /* Quit outer loop on error or when we're done. */
2295                 if (done)
2296                         break;
2297                 if (error)
2298                         goto done;
2299         }
2300
2301         /*
2302          * Send trailers. Wimp out and use writev(2).
2303          */
2304         if (trl_uio != NULL) {
2305                 sbunlock(&so->so_snd);
2306                 error = kern_writev(td, uap->s, trl_uio);
2307                 if (error == 0)
2308                         sbytes += td->td_retval[0];
2309                 goto out;
2310         }
2311
2312 done:
2313         sbunlock(&so->so_snd);
2314 out:
2315         /*
2316          * If there was no error we have to clear td->td_retval[0]
2317          * because it may have been set by writev.
2318          */
2319         if (error == 0) {
2320                 td->td_retval[0] = 0;
2321         }
2322         if (uap->sbytes != NULL) {
2323                 copyout(&sbytes, uap->sbytes, sizeof(off_t));
2324         }
2325         if (obj != NULL)
2326                 vm_object_deallocate(obj);
2327         if (vp != NULL)
2328                 vrele(vp);
2329         if (so)
2330                 fdrop(sock_fp, td);
2331         if (m)
2332                 m_freem(m);
2333
2334         if (sfs != NULL) {
2335                 mtx_lock(&sfs->mtx);
2336                 if (sfs->count != 0)
2337                         cv_wait(&sfs->cv, &sfs->mtx);
2338                 KASSERT(sfs->count == 0, ("sendfile sync still busy"));
2339                 cv_destroy(&sfs->cv);
2340                 mtx_destroy(&sfs->mtx);
2341                 free(sfs, M_TEMP);
2342         }
2343
2344         if (error == ERESTART)
2345                 error = EINTR;
2346
2347         return (error);
2348 }
2349
2350 /*
2351  * SCTP syscalls.
2352  * Functionality only compiled in if SCTP is defined in the kernel Makefile,
2353  * otherwise all return EOPNOTSUPP.
2354  * XXX: We should make this loadable one day.
2355  */
2356 int
2357 sys_sctp_peeloff(td, uap)
2358         struct thread *td;
2359         struct sctp_peeloff_args /* {
2360                 int     sd;
2361                 caddr_t name;
2362         } */ *uap;
2363 {
2364 #if (defined(INET) || defined(INET6)) && defined(SCTP)
2365         struct file *nfp = NULL;
2366         int error;
2367         struct socket *head, *so;
2368         int fd;
2369         u_int fflag;
2370
2371         AUDIT_ARG_FD(uap->sd);
2372         error = fgetsock(td, uap->sd, CAP_PEELOFF, &head, &fflag);
2373         if (error)
2374                 goto done2;
2375         if (head->so_proto->pr_protocol != IPPROTO_SCTP) {
2376                 error = EOPNOTSUPP;
2377                 goto done;
2378         }
2379         error = sctp_can_peel_off(head, (sctp_assoc_t)uap->name);
2380         if (error)
2381                 goto done;
2382         /*
2383          * At this point we know we do have a assoc to pull
2384          * we proceed to get the fd setup. This may block
2385          * but that is ok.
2386          */
2387
2388         error = falloc(td, &nfp, &fd, 0);
2389         if (error)
2390                 goto done;
2391         td->td_retval[0] = fd;
2392
2393         CURVNET_SET(head->so_vnet);
2394         so = sonewconn(head, SS_ISCONNECTED);
2395         if (so == NULL) {
2396                 error = ENOMEM;
2397                 goto noconnection;
2398         }
2399         /*
2400          * Before changing the flags on the socket, we have to bump the
2401          * reference count.  Otherwise, if the protocol calls sofree(),
2402          * the socket will be released due to a zero refcount.
2403          */
2404         SOCK_LOCK(so);
2405         soref(so);                      /* file descriptor reference */
2406         SOCK_UNLOCK(so);
2407
2408         ACCEPT_LOCK();
2409
2410         TAILQ_REMOVE(&head->so_comp, so, so_list);
2411         head->so_qlen--;
2412         so->so_state |= (head->so_state & SS_NBIO);
2413         so->so_state &= ~SS_NOFDREF;
2414         so->so_qstate &= ~SQ_COMP;
2415         so->so_head = NULL;
2416         ACCEPT_UNLOCK();
2417         finit(nfp, fflag, DTYPE_SOCKET, so, &socketops);
2418         error = sctp_do_peeloff(head, so, (sctp_assoc_t)uap->name);
2419         if (error)
2420                 goto noconnection;
2421         if (head->so_sigio != NULL)
2422                 fsetown(fgetown(&head->so_sigio), &so->so_sigio);
2423
2424 noconnection:
2425         /*
2426          * close the new descriptor, assuming someone hasn't ripped it
2427          * out from under us.
2428          */
2429         if (error)
2430                 fdclose(td->td_proc->p_fd, nfp, fd, td);
2431
2432         /*
2433          * Release explicitly held references before returning.
2434          */
2435         CURVNET_RESTORE();
2436 done:
2437         if (nfp != NULL)
2438                 fdrop(nfp, td);
2439         fputsock(head);
2440 done2:
2441         return (error);
2442 #else  /* SCTP */
2443         return (EOPNOTSUPP);
2444 #endif /* SCTP */
2445 }
2446
2447 int
2448 sys_sctp_generic_sendmsg (td, uap)
2449         struct thread *td;
2450         struct sctp_generic_sendmsg_args /* {
2451                 int sd,
2452                 caddr_t msg,
2453                 int mlen,
2454                 caddr_t to,
2455                 __socklen_t tolen,
2456                 struct sctp_sndrcvinfo *sinfo,
2457                 int flags
2458         } */ *uap;
2459 {
2460 #if (defined(INET) || defined(INET6)) && defined(SCTP)
2461         struct sctp_sndrcvinfo sinfo, *u_sinfo = NULL;
2462         struct socket *so;
2463         struct file *fp = NULL;
2464         int error = 0, len;
2465         struct sockaddr *to = NULL;
2466 #ifdef KTRACE
2467         struct uio *ktruio = NULL;
2468 #endif
2469         struct uio auio;
2470         struct iovec iov[1];
2471         cap_rights_t rights;
2472
2473         if (uap->sinfo) {
2474                 error = copyin(uap->sinfo, &sinfo, sizeof (sinfo));
2475                 if (error)
2476                         return (error);
2477                 u_sinfo = &sinfo;
2478         }
2479
2480         rights = CAP_SEND;
2481         if (uap->tolen) {
2482                 error = getsockaddr(&to, uap->to, uap->tolen);
2483                 if (error) {
2484                         to = NULL;
2485                         goto sctp_bad2;
2486                 }
2487                 rights |= CAP_CONNECT;
2488         }
2489
2490         AUDIT_ARG_FD(uap->sd);
2491         error = getsock_cap(td->td_proc->p_fd, uap->sd, rights, &fp, NULL);
2492         if (error)
2493                 goto sctp_bad;
2494 #ifdef KTRACE
2495         if (to && (KTRPOINT(td, KTR_STRUCT)))
2496                 ktrsockaddr(to);
2497 #endif
2498
2499         iov[0].iov_base = uap->msg;
2500         iov[0].iov_len = uap->mlen;
2501
2502         so = (struct socket *)fp->f_data;
2503         if (so->so_proto->pr_protocol != IPPROTO_SCTP) {
2504                 error = EOPNOTSUPP;
2505                 goto sctp_bad;
2506         }
2507 #ifdef MAC
2508         error = mac_socket_check_send(td->td_ucred, so);
2509         if (error)
2510                 goto sctp_bad;
2511 #endif /* MAC */
2512
2513         auio.uio_iov =  iov;
2514         auio.uio_iovcnt = 1;
2515         auio.uio_segflg = UIO_USERSPACE;
2516         auio.uio_rw = UIO_WRITE;
2517         auio.uio_td = td;
2518         auio.uio_offset = 0;                    /* XXX */
2519         auio.uio_resid = 0;
2520         len = auio.uio_resid = uap->mlen;
2521         CURVNET_SET(so->so_vnet);
2522         error = sctp_lower_sosend(so, to, &auio,
2523                     (struct mbuf *)NULL, (struct mbuf *)NULL,
2524                     uap->flags, u_sinfo, td);
2525         CURVNET_RESTORE();
2526         if (error) {
2527                 if (auio.uio_resid != len && (error == ERESTART ||
2528                     error == EINTR || error == EWOULDBLOCK))
2529                         error = 0;
2530                 /* Generation of SIGPIPE can be controlled per socket. */
2531                 if (error == EPIPE && !(so->so_options & SO_NOSIGPIPE) &&
2532                     !(uap->flags & MSG_NOSIGNAL)) {
2533                         PROC_LOCK(td->td_proc);
2534                         tdsignal(td, SIGPIPE);
2535                         PROC_UNLOCK(td->td_proc);
2536                 }
2537         }
2538         if (error == 0)
2539                 td->td_retval[0] = len - auio.uio_resid;
2540 #ifdef KTRACE
2541         if (ktruio != NULL) {
2542                 ktruio->uio_resid = td->td_retval[0];
2543                 ktrgenio(uap->sd, UIO_WRITE, ktruio, error);
2544         }
2545 #endif /* KTRACE */
2546 sctp_bad:
2547         if (fp)
2548                 fdrop(fp, td);
2549 sctp_bad2:
2550         if (to)
2551                 free(to, M_SONAME);
2552         return (error);
2553 #else  /* SCTP */
2554         return (EOPNOTSUPP);
2555 #endif /* SCTP */
2556 }
2557
2558 int
2559 sys_sctp_generic_sendmsg_iov(td, uap)
2560         struct thread *td;
2561         struct sctp_generic_sendmsg_iov_args /* {
2562                 int sd,
2563                 struct iovec *iov,
2564                 int iovlen,
2565                 caddr_t to,
2566                 __socklen_t tolen,
2567                 struct sctp_sndrcvinfo *sinfo,
2568                 int flags
2569         } */ *uap;
2570 {
2571 #if (defined(INET) || defined(INET6)) && defined(SCTP)
2572         struct sctp_sndrcvinfo sinfo, *u_sinfo = NULL;
2573         struct socket *so;
2574         struct file *fp = NULL;
2575         int error=0, i;
2576         ssize_t len;
2577         struct sockaddr *to = NULL;
2578 #ifdef KTRACE
2579         struct uio *ktruio = NULL;
2580 #endif
2581         struct uio auio;
2582         struct iovec *iov, *tiov;
2583         cap_rights_t rights;
2584
2585         if (uap->sinfo) {
2586                 error = copyin(uap->sinfo, &sinfo, sizeof (sinfo));
2587                 if (error)
2588                         return (error);
2589                 u_sinfo = &sinfo;
2590         }
2591         rights = CAP_SEND;
2592         if (uap->tolen) {
2593                 error = getsockaddr(&to, uap->to, uap->tolen);
2594                 if (error) {
2595                         to = NULL;
2596                         goto sctp_bad2;
2597                 }
2598                 rights |= CAP_CONNECT;
2599         }
2600
2601         AUDIT_ARG_FD(uap->sd);
2602         error = getsock_cap(td->td_proc->p_fd, uap->sd, rights, &fp, NULL);
2603         if (error)
2604                 goto sctp_bad1;
2605
2606 #ifdef COMPAT_FREEBSD32
2607         if (SV_CURPROC_FLAG(SV_ILP32))
2608                 error = freebsd32_copyiniov((struct iovec32 *)uap->iov,
2609                     uap->iovlen, &iov, EMSGSIZE);
2610         else
2611 #endif
2612                 error = copyiniov(uap->iov, uap->iovlen, &iov, EMSGSIZE);
2613         if (error)
2614                 goto sctp_bad1;
2615 #ifdef KTRACE
2616         if (to && (KTRPOINT(td, KTR_STRUCT)))
2617                 ktrsockaddr(to);
2618 #endif
2619
2620         so = (struct socket *)fp->f_data;
2621         if (so->so_proto->pr_protocol != IPPROTO_SCTP) {
2622                 error = EOPNOTSUPP;
2623                 goto sctp_bad;
2624         }
2625 #ifdef MAC
2626         error = mac_socket_check_send(td->td_ucred, so);
2627         if (error)
2628                 goto sctp_bad;
2629 #endif /* MAC */
2630
2631         auio.uio_iov = iov;
2632         auio.uio_iovcnt = uap->iovlen;
2633         auio.uio_segflg = UIO_USERSPACE;
2634         auio.uio_rw = UIO_WRITE;
2635         auio.uio_td = td;
2636         auio.uio_offset = 0;                    /* XXX */
2637         auio.uio_resid = 0;
2638         tiov = iov;
2639         for (i = 0; i <uap->iovlen; i++, tiov++) {
2640                 if ((auio.uio_resid += tiov->iov_len) < 0) {
2641                         error = EINVAL;
2642                         goto sctp_bad;
2643                 }
2644         }
2645         len = auio.uio_resid;
2646         CURVNET_SET(so->so_vnet);
2647         error = sctp_lower_sosend(so, to, &auio,
2648                     (struct mbuf *)NULL, (struct mbuf *)NULL,
2649                     uap->flags, u_sinfo, td);
2650         CURVNET_RESTORE();
2651         if (error) {
2652                 if (auio.uio_resid != len && (error == ERESTART ||
2653                     error == EINTR || error == EWOULDBLOCK))
2654                         error = 0;
2655                 /* Generation of SIGPIPE can be controlled per socket */
2656                 if (error == EPIPE && !(so->so_options & SO_NOSIGPIPE) &&
2657                     !(uap->flags & MSG_NOSIGNAL)) {
2658                         PROC_LOCK(td->td_proc);
2659                         tdsignal(td, SIGPIPE);
2660                         PROC_UNLOCK(td->td_proc);
2661                 }
2662         }
2663         if (error == 0)
2664                 td->td_retval[0] = len - auio.uio_resid;
2665 #ifdef KTRACE
2666         if (ktruio != NULL) {
2667                 ktruio->uio_resid = td->td_retval[0];
2668                 ktrgenio(uap->sd, UIO_WRITE, ktruio, error);
2669         }
2670 #endif /* KTRACE */
2671 sctp_bad:
2672         free(iov, M_IOV);
2673 sctp_bad1:
2674         if (fp)
2675                 fdrop(fp, td);
2676 sctp_bad2:
2677         if (to)
2678                 free(to, M_SONAME);
2679         return (error);
2680 #else  /* SCTP */
2681         return (EOPNOTSUPP);
2682 #endif /* SCTP */
2683 }
2684
2685 int
2686 sys_sctp_generic_recvmsg(td, uap)
2687         struct thread *td;
2688         struct sctp_generic_recvmsg_args /* {
2689                 int sd,
2690                 struct iovec *iov,
2691                 int iovlen,
2692                 struct sockaddr *from,
2693                 __socklen_t *fromlenaddr,
2694                 struct sctp_sndrcvinfo *sinfo,
2695                 int *msg_flags
2696         } */ *uap;
2697 {
2698 #if (defined(INET) || defined(INET6)) && defined(SCTP)
2699         uint8_t sockbufstore[256];
2700         struct uio auio;
2701         struct iovec *iov, *tiov;
2702         struct sctp_sndrcvinfo sinfo;
2703         struct socket *so;
2704         struct file *fp = NULL;
2705         struct sockaddr *fromsa;
2706         int fromlen;
2707         ssize_t len;
2708         int i, msg_flags;
2709         int error = 0;
2710 #ifdef KTRACE
2711         struct uio *ktruio = NULL;
2712 #endif
2713
2714         AUDIT_ARG_FD(uap->sd);
2715         error = getsock_cap(td->td_proc->p_fd, uap->sd, CAP_RECV, &fp, NULL);
2716         if (error) {
2717                 return (error);
2718         }
2719 #ifdef COMPAT_FREEBSD32
2720         if (SV_CURPROC_FLAG(SV_ILP32))
2721                 error = freebsd32_copyiniov((struct iovec32 *)uap->iov,
2722                     uap->iovlen, &iov, EMSGSIZE);
2723         else
2724 #endif
2725                 error = copyiniov(uap->iov, uap->iovlen, &iov, EMSGSIZE);
2726         if (error)
2727                 goto out1;
2728
2729         so = fp->f_data;
2730         if (so->so_proto->pr_protocol != IPPROTO_SCTP) {
2731                 error = EOPNOTSUPP;
2732                 goto out;
2733         }
2734 #ifdef MAC
2735         error = mac_socket_check_receive(td->td_ucred, so);
2736         if (error) {
2737                 goto out;
2738         }
2739 #endif /* MAC */
2740
2741         if (uap->fromlenaddr) {
2742                 error = copyin(uap->fromlenaddr,
2743                     &fromlen, sizeof (fromlen));
2744                 if (error) {
2745                         goto out;
2746                 }
2747         } else {
2748                 fromlen = 0;
2749         }
2750         if (uap->msg_flags) {
2751                 error = copyin(uap->msg_flags, &msg_flags, sizeof (int));
2752                 if (error) {
2753                         goto out;
2754                 }
2755         } else {
2756                 msg_flags = 0;
2757         }
2758         auio.uio_iov = iov;
2759         auio.uio_iovcnt = uap->iovlen;
2760         auio.uio_segflg = UIO_USERSPACE;
2761         auio.uio_rw = UIO_READ;
2762         auio.uio_td = td;
2763         auio.uio_offset = 0;                    /* XXX */
2764         auio.uio_resid = 0;
2765         tiov = iov;
2766         for (i = 0; i <uap->iovlen; i++, tiov++) {
2767                 if ((auio.uio_resid += tiov->iov_len) < 0) {
2768                         error = EINVAL;
2769                         goto out;
2770                 }
2771         }
2772         len = auio.uio_resid;
2773         fromsa = (struct sockaddr *)sockbufstore;
2774
2775 #ifdef KTRACE
2776         if (KTRPOINT(td, KTR_GENIO))
2777                 ktruio = cloneuio(&auio);
2778 #endif /* KTRACE */
2779         memset(&sinfo, 0, sizeof(struct sctp_sndrcvinfo));
2780         CURVNET_SET(so->so_vnet);
2781         error = sctp_sorecvmsg(so, &auio, (struct mbuf **)NULL,
2782                     fromsa, fromlen, &msg_flags,
2783                     (struct sctp_sndrcvinfo *)&sinfo, 1);
2784         CURVNET_RESTORE();
2785         if (error) {
2786                 if (auio.uio_resid != len && (error == ERESTART ||
2787                     error == EINTR || error == EWOULDBLOCK))
2788                         error = 0;
2789         } else {
2790                 if (uap->sinfo)
2791                         error = copyout(&sinfo, uap->sinfo, sizeof (sinfo));
2792         }
2793 #ifdef KTRACE
2794         if (ktruio != NULL) {
2795                 ktruio->uio_resid = len - auio.uio_resid;
2796                 ktrgenio(uap->sd, UIO_READ, ktruio, error);
2797         }
2798 #endif /* KTRACE */
2799         if (error)
2800                 goto out;
2801         td->td_retval[0] = len - auio.uio_resid;
2802
2803         if (fromlen && uap->from) {
2804                 len = fromlen;
2805                 if (len <= 0 || fromsa == 0)
2806                         len = 0;
2807                 else {
2808                         len = MIN(len, fromsa->sa_len);
2809                         error = copyout(fromsa, uap->from, (size_t)len);
2810                         if (error)
2811                                 goto out;
2812                 }
2813                 error = copyout(&len, uap->fromlenaddr, sizeof (socklen_t));
2814                 if (error) {
2815                         goto out;
2816                 }
2817         }
2818 #ifdef KTRACE
2819         if (KTRPOINT(td, KTR_STRUCT))
2820                 ktrsockaddr(fromsa);
2821 #endif
2822         if (uap->msg_flags) {
2823                 error = copyout(&msg_flags, uap->msg_flags, sizeof (int));
2824                 if (error) {
2825                         goto out;
2826                 }
2827         }
2828 out:
2829         free(iov, M_IOV);
2830 out1:
2831         if (fp)
2832                 fdrop(fp, td);
2833
2834         return (error);
2835 #else  /* SCTP */
2836         return (EOPNOTSUPP);
2837 #endif /* SCTP */
2838 }