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