xref: /dragonfly/sys/kern/uipc_syscalls.c (revision 7ff0fc30)
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  * 3. 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  * $FreeBSD: src/sys/kern/uipc_syscalls.c,v 1.65.2.17 2003/04/04 17:11:16 tegge Exp $
34  */
35 
36 #include "opt_ktrace.h"
37 
38 #include <sys/param.h>
39 #include <sys/systm.h>
40 #include <sys/kernel.h>
41 #include <sys/sysmsg.h>
42 #include <sys/malloc.h>
43 #include <sys/filedesc.h>
44 #include <sys/event.h>
45 #include <sys/proc.h>
46 #include <sys/fcntl.h>
47 #include <sys/file.h>
48 #include <sys/filio.h>
49 #include <sys/kern_syscall.h>
50 #include <sys/mbuf.h>
51 #include <sys/protosw.h>
52 #include <sys/sfbuf.h>
53 #include <sys/socket.h>
54 #include <sys/socketvar.h>
55 #include <sys/socketops.h>
56 #include <sys/uio.h>
57 #include <sys/vnode.h>
58 #include <sys/lock.h>
59 #include <sys/mount.h>
60 #include <sys/jail.h>
61 #ifdef KTRACE
62 #include <sys/ktrace.h>
63 #endif
64 #include <vm/vm.h>
65 #include <vm/vm_object.h>
66 #include <vm/vm_page.h>
67 #include <vm/vm_pageout.h>
68 #include <vm/vm_kern.h>
69 #include <vm/vm_extern.h>
70 #include <sys/file2.h>
71 #include <sys/signalvar.h>
72 #include <sys/serialize.h>
73 
74 #include <sys/thread2.h>
75 #include <sys/msgport2.h>
76 #include <sys/socketvar2.h>
77 #include <net/netmsg2.h>
78 #include <vm/vm_page2.h>
79 
80 extern int use_soaccept_pred_fast;
81 extern int use_sendfile_async;
82 extern int use_soconnect_async;
83 
84 /*
85  * System call interface to the socket abstraction.
86  */
87 
88 extern	struct fileops socketops;
89 
90 /*
91  * socket_args(int domain, int type, int protocol)
92  */
93 int
94 kern_socket(int domain, int type, int protocol, int *res)
95 {
96 	struct thread *td = curthread;
97 	struct filedesc *fdp = td->td_proc->p_fd;
98 	struct socket *so;
99 	struct file *fp;
100 	int fd, error;
101 	u_int fflags = 0;
102 	int oflags = 0;
103 
104 	KKASSERT(td->td_lwp);
105 
106 	if (type & SOCK_NONBLOCK) {
107 		type &= ~SOCK_NONBLOCK;
108 		fflags |= FNONBLOCK;
109 	}
110 	if (type & SOCK_CLOEXEC) {
111 		type &= ~SOCK_CLOEXEC;
112 		oflags |= O_CLOEXEC;
113 	}
114 
115 	error = falloc(td->td_lwp, &fp, &fd);
116 	if (error)
117 		return (error);
118 	error = socreate(domain, &so, type, protocol, td);
119 	if (error) {
120 		fsetfd(fdp, NULL, fd);
121 	} else {
122 		fp->f_type = DTYPE_SOCKET;
123 		fp->f_flag = FREAD | FWRITE | fflags;
124 		fp->f_ops = &socketops;
125 		fp->f_data = so;
126 		if (oflags & O_CLOEXEC)
127 			fdp->fd_files[fd].fileflags |= UF_EXCLOSE;
128 		*res = fd;
129 		fsetfd(fdp, fp, fd);
130 	}
131 	fdrop(fp);
132 	return (error);
133 }
134 
135 /*
136  * MPALMOSTSAFE
137  */
138 int
139 sys_socket(struct sysmsg *sysmsg, const struct socket_args *uap)
140 {
141 	int error;
142 
143 	error = kern_socket(uap->domain, uap->type, uap->protocol,
144 			    &sysmsg->sysmsg_iresult);
145 
146 	return (error);
147 }
148 
149 int
150 kern_bind(int s, struct sockaddr *sa)
151 {
152 	struct thread *td = curthread;
153 	struct file *fp;
154 	int error;
155 
156 	error = holdsock(td, s, &fp);
157 	if (error)
158 		return (error);
159 	error = sobind((struct socket *)fp->f_data, sa, td);
160 	dropfp(td, s, fp);
161 
162 	return (error);
163 }
164 
165 /*
166  * bind_args(int s, caddr_t name, int namelen)
167  *
168  * MPALMOSTSAFE
169  */
170 int
171 sys_bind(struct sysmsg *sysmsg, const struct bind_args *uap)
172 {
173 	struct sockaddr *sa;
174 	int error;
175 
176 	error = getsockaddr(&sa, uap->name, uap->namelen);
177 	if (error)
178 		return (error);
179 	if (!prison_remote_ip(curthread, sa)) {
180 		kfree(sa, M_SONAME);
181 		return EAFNOSUPPORT;
182 	}
183 	error = kern_bind(uap->s, sa);
184 	kfree(sa, M_SONAME);
185 
186 	return (error);
187 }
188 
189 int
190 kern_listen(int s, int backlog)
191 {
192 	struct thread *td = curthread;
193 	struct file *fp;
194 	int error;
195 
196 	error = holdsock(td, s, &fp);
197 	if (error)
198 		return (error);
199 	error = solisten((struct socket *)fp->f_data, backlog, td);
200 	dropfp(td, s, fp);
201 
202 	return (error);
203 }
204 
205 /*
206  * listen_args(int s, int backlog)
207  *
208  * MPALMOSTSAFE
209  */
210 int
211 sys_listen(struct sysmsg *sysmsg, const struct listen_args *uap)
212 {
213 	int error;
214 
215 	error = kern_listen(uap->s, uap->backlog);
216 	return (error);
217 }
218 
219 /*
220  * Returns the accepted socket as well.
221  *
222  * NOTE!  The sockets sitting on so_comp/so_incomp might have 0 refs, the
223  *	  pool token is absolutely required to avoid a sofree() race,
224  *	  as well as to avoid tailq handling races.
225  */
226 static boolean_t
227 soaccept_predicate(struct netmsg_so_notify *msg)
228 {
229 	struct socket *head = msg->base.nm_so;
230 	struct socket *so;
231 
232 	if (head->so_error != 0) {
233 		msg->base.lmsg.ms_error = head->so_error;
234 		return (TRUE);
235 	}
236 	lwkt_getpooltoken(head);
237 	if (!TAILQ_EMPTY(&head->so_comp)) {
238 		/* Abuse nm_so field as copy in/copy out parameter. XXX JH */
239 		so = TAILQ_FIRST(&head->so_comp);
240 		KKASSERT((so->so_state & (SS_INCOMP | SS_COMP)) == SS_COMP);
241 		TAILQ_REMOVE(&head->so_comp, so, so_list);
242 		head->so_qlen--;
243 		soclrstate(so, SS_COMP);
244 
245 		/*
246 		 * Keep a reference before clearing the so_head
247 		 * to avoid racing socket close in netisr.
248 		 */
249 		soreference(so);
250 		so->so_head = NULL;
251 
252 		lwkt_relpooltoken(head);
253 
254 		msg->base.lmsg.ms_error = 0;
255 		msg->base.nm_so = so;
256 		return (TRUE);
257 	}
258 	lwkt_relpooltoken(head);
259 	if (head->so_state & SS_CANTRCVMORE) {
260 		msg->base.lmsg.ms_error = ECONNABORTED;
261 		return (TRUE);
262 	}
263 	if (msg->nm_fflags & FNONBLOCK) {
264 		msg->base.lmsg.ms_error = EWOULDBLOCK;
265 		return (TRUE);
266 	}
267 
268 	return (FALSE);
269 }
270 
271 /*
272  * The second argument to kern_accept() is a handle to a struct sockaddr.
273  * This allows kern_accept() to return a pointer to an allocated struct
274  * sockaddr which must be freed later with FREE().  The caller must
275  * initialize *name to NULL.
276  */
277 int
278 kern_accept(int s, int fflags, struct sockaddr **name, int *namelen, int *res,
279     int sockflags)
280 {
281 	struct thread *td = curthread;
282 	struct filedesc *fdp = td->td_proc->p_fd;
283 	struct file *lfp = NULL;
284 	struct file *nfp = NULL;
285 	struct sockaddr *sa;
286 	struct socket *head, *so;
287 	struct netmsg_so_notify msg;
288 	int fd;
289 	u_int fflag;		/* type must match fp->f_flag */
290 	int error, tmp;
291 
292 	*res = -1;
293 	if (name && namelen && *namelen < 0)
294 		return (EINVAL);
295 
296 	error = holdsock(td, s, &lfp);
297 	if (error)
298 		return (error);
299 
300 	error = falloc(td->td_lwp, &nfp, &fd);
301 	if (error) {		/* Probably ran out of file descriptors. */
302 		fdrop(lfp);
303 		return (error);
304 	}
305 	head = (struct socket *)lfp->f_data;
306 	if ((head->so_options & SO_ACCEPTCONN) == 0) {
307 		error = EINVAL;
308 		goto done;
309 	}
310 
311 	if (fflags & O_FBLOCKING)
312 		fflags |= lfp->f_flag & ~FNONBLOCK;
313 	else if (fflags & O_FNONBLOCKING)
314 		fflags |= lfp->f_flag | FNONBLOCK;
315 	else
316 		fflags = lfp->f_flag;
317 
318 	if (use_soaccept_pred_fast) {
319 		boolean_t pred;
320 
321 		/* Initialize necessary parts for soaccept_predicate() */
322 		netmsg_init(&msg.base, head, &netisr_apanic_rport, 0, NULL);
323 		msg.nm_fflags = fflags;
324 
325 		lwkt_getpooltoken(head);
326 		pred = soaccept_predicate(&msg);
327 		lwkt_relpooltoken(head);
328 
329 		if (pred) {
330 			error = msg.base.lmsg.ms_error;
331 			if (error)
332 				goto done;
333 			else
334 				goto accepted;
335 		}
336 	}
337 
338 	/* optimize for uniprocessor case later XXX JH */
339 	netmsg_init_abortable(&msg.base, head, &curthread->td_msgport,
340 			      0, netmsg_so_notify, netmsg_so_notify_doabort);
341 	msg.nm_predicate = soaccept_predicate;
342 	msg.nm_fflags = fflags;
343 	msg.nm_etype = NM_REVENT;
344 	error = lwkt_domsg(head->so_port, &msg.base.lmsg, PCATCH);
345 	if (error)
346 		goto done;
347 
348 accepted:
349 	/*
350 	 * At this point we have the connection that's ready to be accepted.
351 	 *
352 	 * NOTE! soaccept_predicate() ref'd so for us, and soaccept() expects
353 	 * 	 to eat the ref and turn it into a descriptor.
354 	 */
355 	so = msg.base.nm_so;
356 
357 	fflag = lfp->f_flag;
358 
359 	/* connection has been removed from the listen queue */
360 	KNOTE(&head->so_rcv.ssb_kq.ki_note, 0);
361 
362 	if (sockflags & SOCK_KERN_NOINHERIT) {
363 		fflag &= ~(FASYNC | FNONBLOCK);
364 		if (sockflags & SOCK_NONBLOCK)
365 			fflag |= FNONBLOCK;
366 	} else {
367 		if (head->so_sigio != NULL)
368 			fsetown(fgetown(&head->so_sigio), &so->so_sigio);
369 	}
370 
371 	nfp->f_type = DTYPE_SOCKET;
372 	nfp->f_flag = fflag;
373 	nfp->f_ops = &socketops;
374 	nfp->f_data = so;
375 	/* Sync socket async state with file flags */
376 	tmp = fflag & FASYNC;
377 	fo_ioctl(nfp, FIOASYNC, (caddr_t)&tmp, td->td_ucred, NULL);
378 
379 	sa = NULL;
380 	if (so->so_faddr != NULL) {
381 		sa = so->so_faddr;
382 		so->so_faddr = NULL;
383 
384 		soaccept_generic(so);
385 		error = 0;
386 	} else {
387 		error = soaccept(so, &sa);
388 	}
389 
390 	/*
391 	 * Set the returned name and namelen as applicable.  Set the returned
392 	 * namelen to 0 for older code which might ignore the return value
393 	 * from accept.
394 	 */
395 	if (error == 0) {
396 		if (sa && name && namelen) {
397 			if (*namelen > sa->sa_len)
398 				*namelen = sa->sa_len;
399 			*name = sa;
400 		} else {
401 			if (sa)
402 				kfree(sa, M_SONAME);
403 		}
404 	}
405 
406 done:
407 	/*
408 	 * If an error occured clear the reserved descriptor, else associate
409 	 * nfp with it.
410 	 *
411 	 * Note that *res is normally ignored if an error is returned but
412 	 * a syscall message will still have access to the result code.
413 	 */
414 	if (error) {
415 		fsetfd(fdp, NULL, fd);
416 	} else {
417 		if (sockflags & SOCK_CLOEXEC)
418 			fdp->fd_files[fd].fileflags |= UF_EXCLOSE;
419 		*res = fd;
420 		fsetfd(fdp, nfp, fd);
421 	}
422 	fdrop(nfp);
423 	dropfp(td, s, lfp);
424 
425 	return (error);
426 }
427 
428 /*
429  * accept(int s, caddr_t name, int *anamelen)
430  *
431  * MPALMOSTSAFE
432  */
433 int
434 sys_accept(struct sysmsg *sysmsg, const struct accept_args *uap)
435 {
436 	struct sockaddr *sa = NULL;
437 	int sa_len;
438 	int error;
439 
440 	if (uap->name) {
441 		error = copyin(uap->anamelen, &sa_len, sizeof(sa_len));
442 		if (error)
443 			return (error);
444 
445 		error = kern_accept(uap->s, 0, &sa, &sa_len,
446 				    &sysmsg->sysmsg_iresult, 0);
447 
448 		if (error == 0) {
449 			prison_local_ip(curthread, sa);
450 			error = copyout(sa, uap->name, sa_len);
451 		}
452 		if (error == 0) {
453 			error = copyout(&sa_len, uap->anamelen,
454 					sizeof(*uap->anamelen));
455 		}
456 		if (sa)
457 			kfree(sa, M_SONAME);
458 	} else {
459 		error = kern_accept(uap->s, 0, NULL, 0,
460 				    &sysmsg->sysmsg_iresult, 0);
461 	}
462 	return (error);
463 }
464 
465 /*
466  * extaccept(int s, int fflags, caddr_t name, int *anamelen)
467  *
468  * MPALMOSTSAFE
469  */
470 int
471 sys_extaccept(struct sysmsg *sysmsg, const struct extaccept_args *uap)
472 {
473 	struct sockaddr *sa = NULL;
474 	int sa_len;
475 	int error;
476 	int fflags = uap->flags & O_FMASK;
477 
478 	if (uap->name) {
479 		error = copyin(uap->anamelen, &sa_len, sizeof(sa_len));
480 		if (error)
481 			return (error);
482 
483 		error = kern_accept(uap->s, fflags, &sa, &sa_len,
484 				    &sysmsg->sysmsg_iresult, 0);
485 
486 		if (error == 0) {
487 			prison_local_ip(curthread, sa);
488 			error = copyout(sa, uap->name, sa_len);
489 		}
490 		if (error == 0) {
491 			error = copyout(&sa_len, uap->anamelen,
492 			    sizeof(*uap->anamelen));
493 		}
494 		if (sa)
495 			kfree(sa, M_SONAME);
496 	} else {
497 		error = kern_accept(uap->s, fflags, NULL, 0,
498 				    &sysmsg->sysmsg_iresult, 0);
499 	}
500 	return (error);
501 }
502 
503 /*
504  * accept4(int s, caddr_t name, int *anamelen, int flags)
505  *
506  * MPALMOSTSAFE
507  */
508 int
509 sys_accept4(struct sysmsg *sysmsg, const struct accept4_args *uap)
510 {
511 	struct sockaddr *sa = NULL;
512 	int sa_len;
513 	int error;
514 	int sockflags;
515 
516 	if (uap->flags & ~(SOCK_NONBLOCK | SOCK_CLOEXEC))
517 		return (EINVAL);
518 	sockflags = uap->flags | SOCK_KERN_NOINHERIT;
519 
520 	if (uap->name) {
521 		error = copyin(uap->anamelen, &sa_len, sizeof(sa_len));
522 		if (error)
523 			return (error);
524 
525 		error = kern_accept(uap->s, 0, &sa, &sa_len,
526 				    &sysmsg->sysmsg_iresult, sockflags);
527 
528 		if (error == 0) {
529 			prison_local_ip(curthread, sa);
530 			error = copyout(sa, uap->name, sa_len);
531 		}
532 		if (error == 0) {
533 			error = copyout(&sa_len, uap->anamelen,
534 					sizeof(*uap->anamelen));
535 		}
536 		if (sa)
537 			kfree(sa, M_SONAME);
538 	} else {
539 		error = kern_accept(uap->s, 0, NULL, 0,
540 				    &sysmsg->sysmsg_iresult, sockflags);
541 	}
542 	return (error);
543 }
544 
545 /*
546  * Returns TRUE if predicate satisfied.
547  */
548 static boolean_t
549 soconnected_predicate(struct netmsg_so_notify *msg)
550 {
551 	struct socket *so = msg->base.nm_so;
552 
553 	/* check predicate */
554 	if (!(so->so_state & SS_ISCONNECTING) || so->so_error != 0) {
555 		msg->base.lmsg.ms_error = so->so_error;
556 		return (TRUE);
557 	}
558 
559 	return (FALSE);
560 }
561 
562 int
563 kern_connect(int s, int fflags, struct sockaddr *sa)
564 {
565 	struct thread *td = curthread;
566 	struct file *fp;
567 	struct socket *so;
568 	int error, interrupted = 0;
569 
570 	error = holdsock(td, s, &fp);
571 	if (error)
572 		return (error);
573 	so = (struct socket *)fp->f_data;
574 
575 	if (fflags & O_FBLOCKING)
576 		/* fflags &= ~FNONBLOCK; */;
577 	else if (fflags & O_FNONBLOCKING)
578 		fflags |= FNONBLOCK;
579 	else
580 		fflags = fp->f_flag;
581 
582 	if (so->so_state & SS_ISCONNECTING) {
583 		error = EALREADY;
584 		goto done;
585 	}
586 	error = soconnect(so, sa, td, use_soconnect_async ? FALSE : TRUE);
587 	if (error)
588 		goto bad;
589 	if ((fflags & FNONBLOCK) && (so->so_state & SS_ISCONNECTING)) {
590 		error = EINPROGRESS;
591 		goto done;
592 	}
593 	if ((so->so_state & SS_ISCONNECTING) && so->so_error == 0) {
594 		struct netmsg_so_notify msg;
595 
596 		netmsg_init_abortable(&msg.base, so,
597 				      &curthread->td_msgport,
598 				      0,
599 				      netmsg_so_notify,
600 				      netmsg_so_notify_doabort);
601 		msg.nm_predicate = soconnected_predicate;
602 		msg.nm_etype = NM_REVENT;
603 		error = lwkt_domsg(so->so_port, &msg.base.lmsg, PCATCH);
604 		if (error == EINTR || error == ERESTART)
605 			interrupted = 1;
606 	}
607 	if (error == 0) {
608 		error = so->so_error;
609 		so->so_error = 0;
610 	}
611 bad:
612 	if (!interrupted)
613 		soclrstate(so, SS_ISCONNECTING);
614 	if (error == ERESTART)
615 		error = EINTR;
616 done:
617 	dropfp(td, s, fp);
618 
619 	return (error);
620 }
621 
622 /*
623  * connect_args(int s, caddr_t name, int namelen)
624  *
625  * MPALMOSTSAFE
626  */
627 int
628 sys_connect(struct sysmsg *sysmsg, const struct connect_args *uap)
629 {
630 	struct sockaddr *sa;
631 	int error;
632 
633 	error = getsockaddr(&sa, uap->name, uap->namelen);
634 	if (error)
635 		return (error);
636 	if (!prison_remote_ip(curthread, sa)) {
637 		kfree(sa, M_SONAME);
638 		return EAFNOSUPPORT;
639 	}
640 	error = kern_connect(uap->s, 0, sa);
641 	kfree(sa, M_SONAME);
642 
643 	return (error);
644 }
645 
646 /*
647  * connect_args(int s, int fflags, caddr_t name, int namelen)
648  *
649  * MPALMOSTSAFE
650  */
651 int
652 sys_extconnect(struct sysmsg *sysmsg, const struct extconnect_args *uap)
653 {
654 	struct sockaddr *sa;
655 	int error;
656 	int fflags = uap->flags & O_FMASK;
657 
658 	error = getsockaddr(&sa, uap->name, uap->namelen);
659 	if (error)
660 		return (error);
661 	if (!prison_remote_ip(curthread, sa)) {
662 		kfree(sa, M_SONAME);
663 		return EAFNOSUPPORT;
664 	}
665 	error = kern_connect(uap->s, fflags, sa);
666 	kfree(sa, M_SONAME);
667 
668 	return (error);
669 }
670 
671 int
672 kern_socketpair(int domain, int type, int protocol, int *sv)
673 {
674 	struct thread *td = curthread;
675 	struct filedesc *fdp;
676 	struct file *fp1, *fp2;
677 	struct socket *so1, *so2;
678 	int fd1, fd2, error;
679 	u_int fflags = 0;
680 	int oflags = 0;
681 
682 	if (type & SOCK_NONBLOCK) {
683 		type &= ~SOCK_NONBLOCK;
684 		fflags |= FNONBLOCK;
685 	}
686 	if (type & SOCK_CLOEXEC) {
687 		type &= ~SOCK_CLOEXEC;
688 		oflags |= O_CLOEXEC;
689 	}
690 
691 	fdp = td->td_proc->p_fd;
692 	error = socreate(domain, &so1, type, protocol, td);
693 	if (error)
694 		return (error);
695 	error = socreate(domain, &so2, type, protocol, td);
696 	if (error)
697 		goto free1;
698 	error = falloc(td->td_lwp, &fp1, &fd1);
699 	if (error)
700 		goto free2;
701 	sv[0] = fd1;
702 	fp1->f_data = so1;
703 	error = falloc(td->td_lwp, &fp2, &fd2);
704 	if (error)
705 		goto free3;
706 	fp2->f_data = so2;
707 	sv[1] = fd2;
708 	error = soconnect2(so1, so2);
709 	if (error)
710 		goto free4;
711 	if (type == SOCK_DGRAM) {
712 		/*
713 		 * Datagram socket connection is asymmetric.
714 		 */
715 		 error = soconnect2(so2, so1);
716 		 if (error)
717 			goto free4;
718 	}
719 	fp1->f_type = fp2->f_type = DTYPE_SOCKET;
720 	fp1->f_flag = fp2->f_flag = FREAD|FWRITE|fflags;
721 	fp1->f_ops = fp2->f_ops = &socketops;
722 	if (oflags & O_CLOEXEC) {
723 		fdp->fd_files[fd1].fileflags |= UF_EXCLOSE;
724 		fdp->fd_files[fd2].fileflags |= UF_EXCLOSE;
725 	}
726 	fsetfd(fdp, fp1, fd1);
727 	fsetfd(fdp, fp2, fd2);
728 	fdrop(fp1);
729 	fdrop(fp2);
730 	return (error);
731 free4:
732 	fsetfd(fdp, NULL, fd2);
733 	fdrop(fp2);
734 free3:
735 	fsetfd(fdp, NULL, fd1);
736 	fdrop(fp1);
737 free2:
738 	(void)soclose(so2, 0);
739 free1:
740 	(void)soclose(so1, 0);
741 	return (error);
742 }
743 
744 /*
745  * socketpair(int domain, int type, int protocol, int *rsv)
746  */
747 int
748 sys_socketpair(struct sysmsg *sysmsg, const struct socketpair_args *uap)
749 {
750 	int error, sockv[2];
751 
752 	error = kern_socketpair(uap->domain, uap->type, uap->protocol, sockv);
753 
754 	if (error == 0) {
755 		error = copyout(sockv, uap->rsv, sizeof(sockv));
756 
757 		if (error != 0) {
758 			kern_close(sockv[0]);
759 			kern_close(sockv[1]);
760 		}
761 	}
762 
763 	return (error);
764 }
765 
766 int
767 kern_sendmsg(int s, struct sockaddr *sa, struct uio *auio,
768 	     struct mbuf *control, int flags, size_t *res)
769 {
770 	struct thread *td = curthread;
771 	struct lwp *lp = td->td_lwp;
772 	struct proc *p = td->td_proc;
773 	struct file *fp;
774 	size_t len;
775 	int error;
776 	struct socket *so;
777 #ifdef KTRACE
778 	struct iovec *ktriov = NULL;
779 	struct uio ktruio;
780 #endif
781 
782 	error = holdsock(td, s, &fp);
783 	if (error)
784 		return (error);
785 #ifdef KTRACE
786 	if (KTRPOINT(td, KTR_GENIO)) {
787 		int iovlen = auio->uio_iovcnt * sizeof (struct iovec);
788 
789 		ktriov = kmalloc(iovlen, M_TEMP, M_WAITOK);
790 		bcopy((caddr_t)auio->uio_iov, (caddr_t)ktriov, iovlen);
791 		ktruio = *auio;
792 	}
793 #endif
794 	len = auio->uio_resid;
795 	so = (struct socket *)fp->f_data;
796 	if ((flags & (MSG_FNONBLOCKING|MSG_FBLOCKING)) == 0) {
797 		if (fp->f_flag & FNONBLOCK)
798 			flags |= MSG_FNONBLOCKING;
799 	}
800 	error = so_pru_sosend(so, sa, auio, NULL, control, flags, td);
801 	if (error) {
802 		if (auio->uio_resid != len && (error == ERESTART ||
803 		    error == EINTR || error == EWOULDBLOCK))
804 			error = 0;
805 		if (error == EPIPE && !(flags & MSG_NOSIGNAL) &&
806 		    !(so->so_options & SO_NOSIGPIPE))
807 			lwpsignal(p, lp, SIGPIPE);
808 	}
809 #ifdef KTRACE
810 	if (ktriov != NULL) {
811 		if (error == 0) {
812 			ktruio.uio_iov = ktriov;
813 			ktruio.uio_resid = len - auio->uio_resid;
814 			ktrgenio(lp, s, UIO_WRITE, &ktruio, error);
815 		}
816 		kfree(ktriov, M_TEMP);
817 	}
818 #endif
819 	if (error == 0)
820 		*res  = len - auio->uio_resid;
821 	dropfp(td, s, fp);
822 
823 	return (error);
824 }
825 
826 /*
827  * sendto_args(int s, caddr_t buf, size_t len, int flags, caddr_t to, int tolen)
828  *
829  * MPALMOSTSAFE
830  */
831 int
832 sys_sendto(struct sysmsg *sysmsg, const struct sendto_args *uap)
833 {
834 	struct thread *td = curthread;
835 	struct uio auio;
836 	struct iovec aiov;
837 	struct sockaddr *sa = NULL;
838 	int error;
839 
840 	if (uap->to) {
841 		error = getsockaddr(&sa, uap->to, uap->tolen);
842 		if (error)
843 			return (error);
844 		if (!prison_remote_ip(curthread, sa)) {
845 			kfree(sa, M_SONAME);
846 			return EAFNOSUPPORT;
847 		}
848 	}
849 	aiov.iov_base = uap->buf;
850 	aiov.iov_len = uap->len;
851 	auio.uio_iov = &aiov;
852 	auio.uio_iovcnt = 1;
853 	auio.uio_offset = 0;
854 	auio.uio_resid = uap->len;
855 	auio.uio_segflg = UIO_USERSPACE;
856 	auio.uio_rw = UIO_WRITE;
857 	auio.uio_td = td;
858 
859 	error = kern_sendmsg(uap->s, sa, &auio, NULL, uap->flags,
860 			     &sysmsg->sysmsg_szresult);
861 
862 	if (sa)
863 		kfree(sa, M_SONAME);
864 	return (error);
865 }
866 
867 /*
868  * sendmsg_args(int s, caddr_t msg, int flags)
869  *
870  * MPALMOSTSAFE
871  */
872 int
873 sys_sendmsg(struct sysmsg *sysmsg, const struct sendmsg_args *uap)
874 {
875 	struct thread *td = curthread;
876 	struct msghdr msg;
877 	struct uio auio;
878 	struct iovec aiov[UIO_SMALLIOV], *iov = NULL;
879 	struct sockaddr *sa = NULL;
880 	struct mbuf *control = NULL;
881 	int error;
882 
883 	error = copyin(uap->msg, (caddr_t)&msg, sizeof(msg));
884 	if (error)
885 		return (error);
886 
887 	/*
888 	 * Conditionally copyin msg.msg_name.
889 	 */
890 	if (msg.msg_name) {
891 		error = getsockaddr(&sa, msg.msg_name, msg.msg_namelen);
892 		if (error)
893 			return (error);
894 		if (!prison_remote_ip(curthread, sa)) {
895 			kfree(sa, M_SONAME);
896 			return EAFNOSUPPORT;
897 		}
898 	}
899 
900 	/*
901 	 * Populate auio.
902 	 */
903 	error = iovec_copyin(msg.msg_iov, &iov, aiov, msg.msg_iovlen,
904 			     &auio.uio_resid);
905 	if (error)
906 		goto cleanup2;
907 	auio.uio_iov = iov;
908 	auio.uio_iovcnt = msg.msg_iovlen;
909 	auio.uio_offset = 0;
910 	auio.uio_segflg = UIO_USERSPACE;
911 	auio.uio_rw = UIO_WRITE;
912 	auio.uio_td = td;
913 
914 	/*
915 	 * Conditionally copyin msg.msg_control.
916 	 */
917 	if (msg.msg_control) {
918 		if (msg.msg_controllen < sizeof(struct cmsghdr) ||
919 		    msg.msg_controllen > MLEN) {
920 			error = EINVAL;
921 			goto cleanup;
922 		}
923 		control = m_get(M_WAITOK, MT_CONTROL);
924 		if (control == NULL) {
925 			error = ENOBUFS;
926 			goto cleanup;
927 		}
928 		control->m_len = msg.msg_controllen;
929 		error = copyin(msg.msg_control, mtod(control, caddr_t),
930 			       msg.msg_controllen);
931 		if (error) {
932 			m_free(control);
933 			goto cleanup;
934 		}
935 	}
936 
937 	error = kern_sendmsg(uap->s, sa, &auio, control, uap->flags,
938 			     &sysmsg->sysmsg_szresult);
939 
940 cleanup:
941 	iovec_free(&iov, aiov);
942 cleanup2:
943 	if (sa)
944 		kfree(sa, M_SONAME);
945 	return (error);
946 }
947 
948 /*
949  * kern_recvmsg() takes a handle to sa and control.  If the handle is non-
950  * null, it returns a dynamically allocated struct sockaddr and an mbuf.
951  * Don't forget to FREE() and m_free() these if they are returned.
952  */
953 int
954 kern_recvmsg(int s, struct sockaddr **sa, struct uio *auio,
955 	     struct mbuf **control, int *flags, size_t *res)
956 {
957 	struct thread *td = curthread;
958 	struct file *fp;
959 	size_t len;
960 	int error;
961 	int lflags;
962 	struct socket *so;
963 #ifdef KTRACE
964 	struct iovec *ktriov = NULL;
965 	struct uio ktruio;
966 #endif
967 
968 	error = holdsock(td, s, &fp);
969 	if (error)
970 		return (error);
971 #ifdef KTRACE
972 	if (KTRPOINT(td, KTR_GENIO)) {
973 		int iovlen = auio->uio_iovcnt * sizeof (struct iovec);
974 
975 		ktriov = kmalloc(iovlen, M_TEMP, M_WAITOK);
976 		bcopy(auio->uio_iov, ktriov, iovlen);
977 		ktruio = *auio;
978 	}
979 #endif
980 	len = auio->uio_resid;
981 	so = (struct socket *)fp->f_data;
982 
983 	if (flags == NULL || (*flags & (MSG_FNONBLOCKING|MSG_FBLOCKING)) == 0) {
984 		if (fp->f_flag & FNONBLOCK) {
985 			if (flags) {
986 				*flags |= MSG_FNONBLOCKING;
987 			} else {
988 				lflags = MSG_FNONBLOCKING;
989 				flags = &lflags;
990 			}
991 		}
992 	}
993 
994 	error = so_pru_soreceive(so, sa, auio, NULL, control, flags);
995 	if (error) {
996 		if (auio->uio_resid != len && (error == ERESTART ||
997 		    error == EINTR || error == EWOULDBLOCK))
998 			error = 0;
999 	}
1000 #ifdef KTRACE
1001 	if (ktriov != NULL) {
1002 		if (error == 0) {
1003 			ktruio.uio_iov = ktriov;
1004 			ktruio.uio_resid = len - auio->uio_resid;
1005 			ktrgenio(td->td_lwp, s, UIO_READ, &ktruio, error);
1006 		}
1007 		kfree(ktriov, M_TEMP);
1008 	}
1009 #endif
1010 	if (error == 0)
1011 		*res = len - auio->uio_resid;
1012 	dropfp(td, s, fp);
1013 
1014 	return (error);
1015 }
1016 
1017 /*
1018  * recvfrom_args(int s, caddr_t buf, size_t len, int flags,
1019  *			caddr_t from, int *fromlenaddr)
1020  *
1021  * MPALMOSTSAFE
1022  */
1023 int
1024 sys_recvfrom(struct sysmsg *sysmsg, const struct recvfrom_args *uap)
1025 {
1026 	struct thread *td = curthread;
1027 	struct uio auio;
1028 	struct iovec aiov;
1029 	struct sockaddr *sa = NULL;
1030 	int error, fromlen;
1031 	int flags;
1032 
1033 	if (uap->from && uap->fromlenaddr) {
1034 		error = copyin(uap->fromlenaddr, &fromlen, sizeof(fromlen));
1035 		if (error)
1036 			return (error);
1037 		if (fromlen < 0)
1038 			return (EINVAL);
1039 	} else {
1040 		fromlen = 0;
1041 	}
1042 	aiov.iov_base = uap->buf;
1043 	aiov.iov_len = uap->len;
1044 	auio.uio_iov = &aiov;
1045 	auio.uio_iovcnt = 1;
1046 	auio.uio_offset = 0;
1047 	auio.uio_resid = uap->len;
1048 	auio.uio_segflg = UIO_USERSPACE;
1049 	auio.uio_rw = UIO_READ;
1050 	auio.uio_td = td;
1051 	flags = uap->flags;
1052 
1053 	error = kern_recvmsg(uap->s, uap->from ? &sa : NULL, &auio, NULL,
1054 			     &flags, &sysmsg->sysmsg_szresult);
1055 
1056 	if (error == 0 && uap->from) {
1057 		/* note: sa may still be NULL */
1058 		if (sa) {
1059 			fromlen = MIN(fromlen, sa->sa_len);
1060 			prison_local_ip(curthread, sa);
1061 			error = copyout(sa, uap->from, fromlen);
1062 		} else {
1063 			fromlen = 0;
1064 		}
1065 		if (error == 0) {
1066 			error = copyout(&fromlen, uap->fromlenaddr,
1067 					sizeof(fromlen));
1068 		}
1069 	}
1070 	if (sa)
1071 		kfree(sa, M_SONAME);
1072 
1073 	return (error);
1074 }
1075 
1076 /*
1077  * recvmsg_args(int s, struct msghdr *msg, int flags)
1078  *
1079  * MPALMOSTSAFE
1080  */
1081 int
1082 sys_recvmsg(struct sysmsg *sysmsg, const struct recvmsg_args *uap)
1083 {
1084 	struct thread *td = curthread;
1085 	struct msghdr msg;
1086 	struct uio auio;
1087 	struct iovec aiov[UIO_SMALLIOV], *iov = NULL;
1088 	struct mbuf *m, *control = NULL;
1089 	struct sockaddr *sa = NULL;
1090 	caddr_t ctlbuf;
1091 	socklen_t *ufromlenp, *ucontrollenp;
1092 	int error, fromlen, controllen, len, flags, *uflagsp;
1093 
1094 	/*
1095 	 * This copyin handles everything except the iovec.
1096 	 */
1097 	error = copyin(uap->msg, &msg, sizeof(msg));
1098 	if (error)
1099 		return (error);
1100 
1101 	if (msg.msg_name && msg.msg_namelen < 0)
1102 		return (EINVAL);
1103 	if (msg.msg_control && msg.msg_controllen < 0)
1104 		return (EINVAL);
1105 
1106 	ufromlenp = (socklen_t *)((caddr_t)uap->msg + offsetof(struct msghdr,
1107 		    msg_namelen));
1108 	ucontrollenp = (socklen_t *)((caddr_t)uap->msg + offsetof(struct msghdr,
1109 		       msg_controllen));
1110 	uflagsp = (int *)((caddr_t)uap->msg + offsetof(struct msghdr,
1111 							msg_flags));
1112 
1113 	/*
1114 	 * Populate auio.
1115 	 */
1116 	error = iovec_copyin(msg.msg_iov, &iov, aiov, msg.msg_iovlen,
1117 			     &auio.uio_resid);
1118 	if (error)
1119 		return (error);
1120 	auio.uio_iov = iov;
1121 	auio.uio_iovcnt = msg.msg_iovlen;
1122 	auio.uio_offset = 0;
1123 	auio.uio_segflg = UIO_USERSPACE;
1124 	auio.uio_rw = UIO_READ;
1125 	auio.uio_td = td;
1126 
1127 	flags = uap->flags;
1128 
1129 	error = kern_recvmsg(uap->s,
1130 			     (msg.msg_name ? &sa : NULL), &auio,
1131 			     (msg.msg_control ? &control : NULL), &flags,
1132 			     &sysmsg->sysmsg_szresult);
1133 
1134 	/*
1135 	 * Conditionally copyout the name and populate the namelen field.
1136 	 */
1137 	if (error == 0 && msg.msg_name) {
1138 		/* note: sa may still be NULL */
1139 		if (sa != NULL) {
1140 			fromlen = MIN(msg.msg_namelen, sa->sa_len);
1141 			prison_local_ip(curthread, sa);
1142 			error = copyout(sa, msg.msg_name, fromlen);
1143 		} else {
1144 			fromlen = 0;
1145 		}
1146 		if (error == 0)
1147 			error = copyout(&fromlen, ufromlenp,
1148 			    sizeof(*ufromlenp));
1149 	}
1150 
1151 	/*
1152 	 * Copyout msg.msg_control and msg.msg_controllen.
1153 	 */
1154 	if (error == 0 && msg.msg_control) {
1155 		len = msg.msg_controllen;
1156 		m = control;
1157 		ctlbuf = (caddr_t)msg.msg_control;
1158 
1159 		while(m && len > 0) {
1160 			unsigned int tocopy;
1161 
1162 			if (len >= m->m_len) {
1163 				tocopy = m->m_len;
1164 			} else {
1165 				msg.msg_flags |= MSG_CTRUNC;
1166 				tocopy = len;
1167 			}
1168 
1169 			error = copyout(mtod(m, caddr_t), ctlbuf, tocopy);
1170 			if (error)
1171 				goto cleanup;
1172 
1173 			ctlbuf += tocopy;
1174 			len -= tocopy;
1175 			m = m->m_next;
1176 		}
1177 		controllen = ctlbuf - (caddr_t)msg.msg_control;
1178 		error = copyout(&controllen, ucontrollenp,
1179 		    sizeof(*ucontrollenp));
1180 	}
1181 
1182 	if (error == 0)
1183 		error = copyout(&flags, uflagsp, sizeof(*uflagsp));
1184 
1185 cleanup:
1186 	if (sa)
1187 		kfree(sa, M_SONAME);
1188 	iovec_free(&iov, aiov);
1189 	if (control)
1190 		m_freem(control);
1191 	return (error);
1192 }
1193 
1194 /*
1195  * If sopt->sopt_td == NULL, then sopt->sopt_val is treated as an
1196  * in kernel pointer instead of a userland pointer.  This allows us
1197  * to manipulate socket options in the emulation code.
1198  */
1199 int
1200 kern_setsockopt(int s, struct sockopt *sopt)
1201 {
1202 	struct thread *td = curthread;
1203 	struct file *fp;
1204 	int error;
1205 
1206 	if (sopt->sopt_val == NULL && sopt->sopt_valsize != 0)
1207 		return (EFAULT);
1208 	if (sopt->sopt_val != NULL && sopt->sopt_valsize == 0)
1209 		return (EINVAL);
1210 	if (sopt->sopt_valsize > SOMAXOPT_SIZE)	/* unsigned */
1211 		return (EINVAL);
1212 
1213 	error = holdsock(td, s, &fp);
1214 	if (error)
1215 		return (error);
1216 
1217 	error = sosetopt((struct socket *)fp->f_data, sopt);
1218 	dropfp(td, s, fp);
1219 
1220 	return (error);
1221 }
1222 
1223 /*
1224  * setsockopt_args(int s, int level, int name, caddr_t val, int valsize)
1225  *
1226  * MPALMOSTSAFE
1227  */
1228 int
1229 sys_setsockopt(struct sysmsg *sysmsg, const struct setsockopt_args *uap)
1230 {
1231 	struct thread *td = curthread;
1232 	struct sockopt sopt;
1233 	int error;
1234 
1235 	sopt.sopt_level = uap->level;
1236 	sopt.sopt_name = uap->name;
1237 	sopt.sopt_valsize = uap->valsize;
1238 	sopt.sopt_td = td;
1239 	sopt.sopt_val = NULL;
1240 
1241 	if (sopt.sopt_valsize > SOMAXOPT_SIZE) /* unsigned */
1242 		return (EINVAL);
1243 	if (uap->val) {
1244 		sopt.sopt_val = kmalloc(sopt.sopt_valsize, M_TEMP, M_WAITOK);
1245 		error = copyin(uap->val, sopt.sopt_val, sopt.sopt_valsize);
1246 		if (error)
1247 			goto out;
1248 	}
1249 
1250 	error = kern_setsockopt(uap->s, &sopt);
1251 out:
1252 	if (uap->val)
1253 		kfree(sopt.sopt_val, M_TEMP);
1254 	return(error);
1255 }
1256 
1257 /*
1258  * If sopt->sopt_td == NULL, then sopt->sopt_val is treated as an
1259  * in kernel pointer instead of a userland pointer.  This allows us
1260  * to manipulate socket options in the emulation code.
1261  */
1262 int
1263 kern_getsockopt(int s, struct sockopt *sopt)
1264 {
1265 	struct thread *td = curthread;
1266 	struct file *fp;
1267 	int error;
1268 
1269 	if (sopt->sopt_val == NULL && sopt->sopt_valsize != 0)
1270 		return (EFAULT);
1271 	if (sopt->sopt_val != NULL && sopt->sopt_valsize == 0)
1272 		return (EINVAL);
1273 
1274 	error = holdsock(td, s, &fp);
1275 	if (error)
1276 		return (error);
1277 
1278 	error = sogetopt((struct socket *)fp->f_data, sopt);
1279 	dropfp(td, s, fp);
1280 
1281 	return (error);
1282 }
1283 
1284 /*
1285  * getsockopt_args(int s, int level, int name, caddr_t val, int *avalsize)
1286  *
1287  * MPALMOSTSAFE
1288  */
1289 int
1290 sys_getsockopt(struct sysmsg *sysmsg, const struct getsockopt_args *uap)
1291 {
1292 	struct thread *td = curthread;
1293 	struct sockopt sopt;
1294 	int error, valsize, valszmax, mflag = 0;
1295 
1296 	if (uap->val) {
1297 		error = copyin(uap->avalsize, &valsize, sizeof(valsize));
1298 		if (error)
1299 			return (error);
1300 	} else {
1301 		valsize = 0;
1302 	}
1303 
1304 	sopt.sopt_level = uap->level;
1305 	sopt.sopt_name = uap->name;
1306 	sopt.sopt_valsize = valsize;
1307 	sopt.sopt_td = td;
1308 	sopt.sopt_val = NULL;
1309 
1310 	if (td->td_proc->p_ucred->cr_uid == 0) {
1311 		valszmax = SOMAXOPT_SIZE0;
1312 		mflag = M_NULLOK;
1313 	} else {
1314 		valszmax = SOMAXOPT_SIZE;
1315 	}
1316 	if (sopt.sopt_valsize > valszmax) /* unsigned */
1317 		return (EINVAL);
1318 	if (uap->val) {
1319 		sopt.sopt_val = kmalloc(sopt.sopt_valsize, M_TEMP,
1320 		    M_WAITOK | mflag);
1321 		if (sopt.sopt_val == NULL)
1322 			return (ENOBUFS);
1323 		error = copyin(uap->val, sopt.sopt_val, sopt.sopt_valsize);
1324 		if (error)
1325 			goto out;
1326 	}
1327 
1328 	error = kern_getsockopt(uap->s, &sopt);
1329 	if (error)
1330 		goto out;
1331 	valsize = sopt.sopt_valsize;
1332 	error = copyout(&valsize, uap->avalsize, sizeof(valsize));
1333 	if (error)
1334 		goto out;
1335 	if (uap->val)
1336 		error = copyout(sopt.sopt_val, uap->val, sopt.sopt_valsize);
1337 out:
1338 	if (uap->val)
1339 		kfree(sopt.sopt_val, M_TEMP);
1340 	return (error);
1341 }
1342 
1343 /*
1344  * The second argument to kern_getsockname() is a handle to a struct sockaddr.
1345  * This allows kern_getsockname() to return a pointer to an allocated struct
1346  * sockaddr which must be freed later with FREE().  The caller must
1347  * initialize *name to NULL.
1348  */
1349 int
1350 kern_getsockname(int s, struct sockaddr **name, int *namelen)
1351 {
1352 	struct thread *td = curthread;
1353 	struct file *fp;
1354 	struct socket *so;
1355 	struct sockaddr *sa = NULL;
1356 	int error;
1357 
1358 	error = holdsock(td, s, &fp);
1359 	if (error)
1360 		return (error);
1361 	if (*namelen < 0) {
1362 		fdrop(fp);
1363 		return (EINVAL);
1364 	}
1365 	so = (struct socket *)fp->f_data;
1366 	error = so_pru_sockaddr(so, &sa);
1367 	if (error == 0) {
1368 		if (sa == NULL) {
1369 			*namelen = 0;
1370 		} else {
1371 			*namelen = MIN(*namelen, sa->sa_len);
1372 			*name = sa;
1373 		}
1374 	}
1375 	dropfp(td, s, fp);
1376 
1377 	return (error);
1378 }
1379 
1380 /*
1381  * getsockname_args(int fdes, caddr_t asa, int *alen)
1382  *
1383  * Get socket name.
1384  *
1385  * MPALMOSTSAFE
1386  */
1387 int
1388 sys_getsockname(struct sysmsg *sysmsg, const struct getsockname_args *uap)
1389 {
1390 	struct sockaddr *sa = NULL;
1391 	struct sockaddr satmp;
1392 	int error, sa_len_in, sa_len_out;
1393 
1394 	error = copyin(uap->alen, &sa_len_in, sizeof(sa_len_in));
1395 	if (error)
1396 		return (error);
1397 
1398 	sa_len_out = sa_len_in;
1399 	error = kern_getsockname(uap->fdes, &sa, &sa_len_out);
1400 
1401 	if (error == 0) {
1402 		if (sa) {
1403 			prison_local_ip(curthread, sa);
1404 			error = copyout(sa, uap->asa, sa_len_out);
1405 		} else {
1406 			/*
1407 			 * unnamed uipc sockets don't bother storing
1408 			 * sockaddr, simulate an AF_LOCAL sockaddr.
1409 			 */
1410 			sa_len_out = sizeof(satmp);
1411 			if (sa_len_out > sa_len_in)
1412 				sa_len_out = sa_len_in;
1413 			if (sa_len_out < 0)
1414 				sa_len_out = 0;
1415 			bzero(&satmp, sizeof(satmp));
1416 			satmp.sa_len = sa_len_out;
1417 			satmp.sa_family = AF_LOCAL;
1418 			error = copyout(&satmp, uap->asa, sa_len_out);
1419 		}
1420 	}
1421 	if (error == 0 && sa_len_out != sa_len_in)
1422 		error = copyout(&sa_len_out, uap->alen, sizeof(*uap->alen));
1423 	if (sa)
1424 		kfree(sa, M_SONAME);
1425 	return (error);
1426 }
1427 
1428 /*
1429  * The second argument to kern_getpeername() is a handle to a struct sockaddr.
1430  * This allows kern_getpeername() to return a pointer to an allocated struct
1431  * sockaddr which must be freed later with FREE().  The caller must
1432  * initialize *name to NULL.
1433  */
1434 int
1435 kern_getpeername(int s, struct sockaddr **name, int *namelen)
1436 {
1437 	struct thread *td = curthread;
1438 	struct file *fp;
1439 	struct socket *so;
1440 	struct sockaddr *sa = NULL;
1441 	int error;
1442 
1443 	error = holdsock(td, s, &fp);
1444 	if (error)
1445 		return (error);
1446 	if (*namelen < 0) {
1447 		fdrop(fp);
1448 		return (EINVAL);
1449 	}
1450 	so = (struct socket *)fp->f_data;
1451 	if ((so->so_state & (SS_ISCONNECTED|SS_ISCONFIRMING)) == 0) {
1452 		fdrop(fp);
1453 		return (ENOTCONN);
1454 	}
1455 	error = so_pru_peeraddr(so, &sa);
1456 	if (error == 0) {
1457 		if (sa == NULL) {
1458 			*namelen = 0;
1459 		} else {
1460 			*namelen = MIN(*namelen, sa->sa_len);
1461 			*name = sa;
1462 		}
1463 	}
1464 	dropfp(td, s, fp);
1465 
1466 	return (error);
1467 }
1468 
1469 /*
1470  * getpeername_args(int fdes, caddr_t asa, int *alen)
1471  *
1472  * Get name of peer for connected socket.
1473  *
1474  * MPALMOSTSAFE
1475  */
1476 int
1477 sys_getpeername(struct sysmsg *sysmsg, const struct getpeername_args *uap)
1478 {
1479 	struct sockaddr *sa = NULL;
1480 	int error, sa_len;
1481 
1482 	error = copyin(uap->alen, &sa_len, sizeof(sa_len));
1483 	if (error)
1484 		return (error);
1485 
1486 	error = kern_getpeername(uap->fdes, &sa, &sa_len);
1487 
1488 	if (error == 0) {
1489 		prison_local_ip(curthread, sa);
1490 		error = copyout(sa, uap->asa, sa_len);
1491 	}
1492 	if (error == 0)
1493 		error = copyout(&sa_len, uap->alen, sizeof(*uap->alen));
1494 	if (sa)
1495 		kfree(sa, M_SONAME);
1496 	return (error);
1497 }
1498 
1499 int
1500 getsockaddr(struct sockaddr **namp, caddr_t uaddr, size_t len)
1501 {
1502 	struct sockaddr *sa;
1503 	int error;
1504 
1505 	*namp = NULL;
1506 	if (len > SOCK_MAXADDRLEN)
1507 		return ENAMETOOLONG;
1508 	if (len < offsetof(struct sockaddr, sa_data[0]))
1509 		return EDOM;
1510 	sa = kmalloc(len, M_SONAME, M_WAITOK);
1511 	error = copyin(uaddr, sa, len);
1512 	if (error) {
1513 		kfree(sa, M_SONAME);
1514 	} else {
1515 		sa->sa_len = len;
1516 		*namp = sa;
1517 	}
1518 	return error;
1519 }
1520 
1521 /*
1522  * Detach a mapped page and release resources back to the system.
1523  * We must release our wiring and if the object is ripped out
1524  * from under the vm_page we become responsible for freeing the
1525  * page.
1526  *
1527  * MPSAFE
1528  */
1529 static void
1530 sf_buf_mfree(void *arg)
1531 {
1532 	struct sf_buf *sf = arg;
1533 	vm_page_t m;
1534 
1535 	m = sf_buf_page(sf);
1536 	if (sf_buf_free(sf)) {
1537 		/* sf invalid now */
1538 		vm_page_sbusy_drop(m);
1539 #if 0
1540 		if (m->object == NULL &&
1541 		    m->wire_count == 0 &&
1542 		    (m->flags & PG_NEED_COMMIT) == 0) {
1543 			vm_page_free(m);
1544 		} else {
1545 			vm_page_wakeup(m);
1546 		}
1547 #endif
1548 	}
1549 }
1550 
1551 /*
1552  * sendfile(2).
1553  * int sendfile(int fd, int s, off_t offset, size_t nbytes,
1554  *	 struct sf_hdtr *hdtr, off_t *sbytes, int flags)
1555  *
1556  * Send a file specified by 'fd' and starting at 'offset' to a socket
1557  * specified by 's'. Send only 'nbytes' of the file or until EOF if
1558  * nbytes == 0. Optionally add a header and/or trailer to the socket
1559  * output. If specified, write the total number of bytes sent into *sbytes.
1560  *
1561  * In FreeBSD kern/uipc_syscalls.c,v 1.103, a bug was fixed that caused
1562  * the headers to count against the remaining bytes to be sent from
1563  * the file descriptor.  We may wish to implement a compatibility syscall
1564  * in the future.
1565  *
1566  * MPALMOSTSAFE
1567  */
1568 int
1569 sys_sendfile(struct sysmsg *sysmsg, const struct sendfile_args *uap)
1570 {
1571 	struct thread *td = curthread;
1572 	struct file *fp;
1573 	struct vnode *vp = NULL;
1574 	struct sf_hdtr hdtr;
1575 	struct iovec aiov[UIO_SMALLIOV], *iov = NULL;
1576 	struct uio auio;
1577 	struct mbuf *mheader = NULL;
1578 	size_t hbytes = 0;
1579 	size_t tbytes;
1580 	off_t hdtr_size = 0;
1581 	off_t sbytes;
1582 	int error;
1583 
1584 	/*
1585 	 * Do argument checking. Must be a regular file in, stream
1586 	 * type and connected socket out, positive offset.
1587 	 */
1588 	fp = holdfp(td, uap->fd, FREAD);
1589 	if (fp == NULL) {
1590 		return (EBADF);
1591 	}
1592 	if (fp->f_type != DTYPE_VNODE) {
1593 		fdrop(fp);
1594 		return (EINVAL);
1595 	}
1596 	vp = (struct vnode *)fp->f_data;
1597 	vref(vp);
1598 	dropfp(td, uap->fd, fp);
1599 
1600 	/*
1601 	 * If specified, get the pointer to the sf_hdtr struct for
1602 	 * any headers/trailers.
1603 	 */
1604 	if (uap->hdtr) {
1605 		error = copyin(uap->hdtr, &hdtr, sizeof(hdtr));
1606 		if (error)
1607 			goto done;
1608 		/*
1609 		 * Send any headers.
1610 		 */
1611 		if (hdtr.headers) {
1612 			error = iovec_copyin(hdtr.headers, &iov, aiov,
1613 					     hdtr.hdr_cnt, &hbytes);
1614 			if (error)
1615 				goto done;
1616 			auio.uio_iov = iov;
1617 			auio.uio_iovcnt = hdtr.hdr_cnt;
1618 			auio.uio_offset = 0;
1619 			auio.uio_segflg = UIO_USERSPACE;
1620 			auio.uio_rw = UIO_WRITE;
1621 			auio.uio_td = td;
1622 			auio.uio_resid = hbytes;
1623 
1624 			mheader = m_uiomove(&auio);
1625 
1626 			iovec_free(&iov, aiov);
1627 			if (mheader == NULL)
1628 				goto done;
1629 		}
1630 	}
1631 
1632 	error = kern_sendfile(vp, uap->s, uap->offset, uap->nbytes, mheader,
1633 			      &sbytes, uap->flags);
1634 	if (error)
1635 		goto done;
1636 
1637 	/*
1638 	 * Send trailers. Wimp out and use writev(2).
1639 	 */
1640 	if (uap->hdtr != NULL && hdtr.trailers != NULL) {
1641 		error = iovec_copyin(hdtr.trailers, &iov, aiov,
1642 				     hdtr.trl_cnt, &auio.uio_resid);
1643 		if (error)
1644 			goto done;
1645 		auio.uio_iov = iov;
1646 		auio.uio_iovcnt = hdtr.trl_cnt;
1647 		auio.uio_offset = 0;
1648 		auio.uio_segflg = UIO_USERSPACE;
1649 		auio.uio_rw = UIO_WRITE;
1650 		auio.uio_td = td;
1651 
1652 		tbytes = 0;	/* avoid gcc warnings */
1653 		error = kern_sendmsg(uap->s, NULL, &auio, NULL, 0, &tbytes);
1654 
1655 		iovec_free(&iov, aiov);
1656 		if (error)
1657 			goto done;
1658 		hdtr_size += tbytes;	/* trailer bytes successfully sent */
1659 	}
1660 
1661 done:
1662 	if (vp)
1663 		vrele(vp);
1664 	if (uap->sbytes != NULL) {
1665 		sbytes += hdtr_size;
1666 		copyout(&sbytes, uap->sbytes, sizeof(off_t));
1667 	}
1668 	return (error);
1669 }
1670 
1671 int
1672 kern_sendfile(struct vnode *vp, int sfd, off_t offset, size_t nbytes,
1673 	      struct mbuf *mheader, off_t *sbytes, int flags)
1674 {
1675 	struct thread *td = curthread;
1676 	struct vm_object *obj;
1677 	struct socket *so;
1678 	struct file *fp;
1679 	struct mbuf *m, *mp;
1680 	struct sf_buf *sf;
1681 	struct vm_page *pg;
1682 	off_t off, xfsize, xbytes;
1683 	off_t hbytes = 0;
1684 	int error = 0;
1685 
1686 	if (vp->v_type != VREG) {
1687 		error = EINVAL;
1688 		goto done0;
1689 	}
1690 	if ((obj = vp->v_object) == NULL) {
1691 		error = EINVAL;
1692 		goto done0;
1693 	}
1694 	error = holdsock(td, sfd, &fp);
1695 	if (error)
1696 		goto done0;
1697 	so = (struct socket *)fp->f_data;
1698 	if (so->so_type != SOCK_STREAM) {
1699 		error = EINVAL;
1700 		goto done1;
1701 	}
1702 	if ((so->so_state & SS_ISCONNECTED) == 0) {
1703 		error = ENOTCONN;
1704 		goto done1;
1705 	}
1706 	if (offset < 0) {
1707 		error = EINVAL;
1708 		goto done1;
1709 	}
1710 
1711 	/*
1712 	 * preallocation is required for asynchronous passing of mbufs,
1713 	 * otherwise we can wind up building up an infinite number of
1714 	 * mbufs during the asynchronous latency.
1715 	 */
1716 	if ((so->so_snd.ssb_flags & (SSB_PREALLOC | SSB_STOPSUPP)) == 0) {
1717 		error = EINVAL;
1718 		goto done1;
1719 	}
1720 
1721 	*sbytes = 0;
1722 	xbytes = 0;
1723 
1724 	/*
1725 	 * Protect against multiple writers to the socket.
1726 	 * We need at least a shared lock on the VM object
1727 	 */
1728 	ssb_lock(&so->so_snd, M_WAITOK);
1729 	vm_object_hold_shared(obj);
1730 
1731 	/*
1732 	 * Loop through the pages in the file, starting with the requested
1733 	 * offset. Get a file page (do I/O if necessary), map the file page
1734 	 * into an sf_buf, attach an mbuf header to the sf_buf, and queue
1735 	 * it on the socket.
1736 	 */
1737 	for (off = offset; ;
1738 	     off += xfsize, *sbytes += xfsize + hbytes, xbytes += xfsize) {
1739 		vm_pindex_t pindex;
1740 		vm_offset_t pgoff;
1741 		long space;
1742 		int loops;
1743 
1744 		pindex = OFF_TO_IDX(off);
1745 		loops = 0;
1746 
1747 retry_lookup:
1748 		/*
1749 		 * Calculate the amount to transfer. Not to exceed a page,
1750 		 * the EOF, or the passed in nbytes.
1751 		 */
1752 		xfsize = vp->v_filesize - off;
1753 		if (xfsize > PAGE_SIZE)
1754 			xfsize = PAGE_SIZE;
1755 		pgoff = (vm_offset_t)(off & PAGE_MASK);
1756 		if (PAGE_SIZE - pgoff < xfsize)
1757 			xfsize = PAGE_SIZE - pgoff;
1758 		if (nbytes && xfsize > (nbytes - xbytes))
1759 			xfsize = nbytes - xbytes;
1760 		if (xfsize <= 0)
1761 			break;
1762 		/*
1763 		 * Optimize the non-blocking case by looking at the socket space
1764 		 * before going to the extra work of constituting the sf_buf.
1765 		 */
1766 		if (so->so_snd.ssb_flags & SSB_PREALLOC)
1767 			space = ssb_space_prealloc(&so->so_snd);
1768 		else
1769 			space = ssb_space(&so->so_snd);
1770 
1771 		if ((fp->f_flag & FNONBLOCK) && space <= 0) {
1772 			if (so->so_state & SS_CANTSENDMORE)
1773 				error = EPIPE;
1774 			else
1775 				error = EAGAIN;
1776 			goto done;
1777 		}
1778 
1779 		/*
1780 		 * Attempt to look up the page.
1781 		 *
1782 		 * Try to find the data using a shared vm_object token and
1783 		 * vm_page_lookup_sbusy_try() first.
1784 		 *
1785 		 * If data is missing, use a UIO_NOCOPY VOP_READ to load
1786 		 * the missing data and loop back up.  We avoid all sorts
1787 		 * of problems by not trying to hold onto the page during
1788 		 * the I/O.
1789 		 *
1790 		 * NOTE: The soft-busy will temporary block filesystem
1791 		 *	 truncation operations when a file is removed
1792 		 *	 while the sendfile is running.
1793 		 */
1794 		pg = vm_page_lookup_sbusy_try(obj, pindex, pgoff, xfsize);
1795 		if (pg == NULL) {
1796 			struct uio auio;
1797 			struct iovec aiov;
1798 			int bsize;
1799 
1800 			if (++loops > 100000) {
1801 				kprintf("sendfile: VOP operation failed "
1802 					"to retain page\n");
1803 				error = EIO;
1804 				goto done;
1805 			}
1806 
1807 			vm_object_drop(obj);
1808 			bsize = vp->v_mount->mnt_stat.f_iosize;
1809 			auio.uio_iov = &aiov;
1810 			auio.uio_iovcnt = 1;
1811 			aiov.iov_base = 0;
1812 			aiov.iov_len = MAXBSIZE;
1813 			auio.uio_resid = MAXBSIZE;
1814 			auio.uio_offset = trunc_page(off);
1815 			auio.uio_segflg = UIO_NOCOPY;
1816 			auio.uio_rw = UIO_READ;
1817 			auio.uio_td = td;
1818 
1819 			vn_lock(vp, LK_SHARED | LK_RETRY);
1820 			error = VOP_READ_FP(vp, &auio,
1821 					 IO_VMIO | ((MAXBSIZE / bsize) << 16),
1822 					 td->td_ucred, fp);
1823 			vn_unlock(vp);
1824 			vm_object_hold_shared(obj);
1825 
1826 			if (error)
1827 				goto done;
1828 			goto retry_lookup;
1829 		}
1830 
1831 		/*
1832 		 * Get a sendfile buf. We usually wait as long as necessary,
1833 		 * but this wait can be interrupted.
1834 		 */
1835 		if ((sf = sf_buf_alloc(pg)) == NULL) {
1836 			vm_page_sbusy_drop(pg);
1837 			/* vm_page_try_to_free(pg); */
1838 			error = EINTR;
1839 			goto done;
1840 		}
1841 
1842 		/*
1843 		 * Get an mbuf header and set it up as having external storage.
1844 		 */
1845 		MGETHDR(m, M_WAITOK, MT_DATA);
1846 		if (m == NULL) {
1847 			error = ENOBUFS;
1848 			vm_page_sbusy_drop(pg);
1849 			/* vm_page_try_to_free(pg); */
1850 			sf_buf_free(sf);
1851 			goto done;
1852 		}
1853 
1854 		m->m_ext.ext_free = sf_buf_mfree;
1855 		m->m_ext.ext_ref = sf_buf_ref;
1856 		m->m_ext.ext_arg = sf;
1857 		m->m_ext.ext_buf = (void *)sf_buf_kva(sf);
1858 		m->m_ext.ext_size = PAGE_SIZE;
1859 		m->m_data = (char *)sf_buf_kva(sf) + pgoff;
1860 		m->m_flags |= M_EXT;
1861 		m->m_pkthdr.len = m->m_len = xfsize;
1862 		KKASSERT((m->m_flags & (M_EXT_CLUSTER)) == 0);
1863 
1864 		if (mheader != NULL) {
1865 			hbytes = mheader->m_pkthdr.len;
1866 			mheader->m_pkthdr.len += m->m_pkthdr.len;
1867 			m_cat(mheader, m);
1868 			m = mheader;
1869 			mheader = NULL;
1870 		} else {
1871 			hbytes = 0;
1872 		}
1873 
1874 		/*
1875 		 * Add the buffer to the socket buffer chain.
1876 		 */
1877 		crit_enter();
1878 retry_space:
1879 		/*
1880 		 * Make sure that the socket is still able to take more data.
1881 		 * CANTSENDMORE being true usually means that the connection
1882 		 * was closed. so_error is true when an error was sensed after
1883 		 * a previous send.
1884 		 * The state is checked after the page mapping and buffer
1885 		 * allocation above since those operations may block and make
1886 		 * any socket checks stale. From this point forward, nothing
1887 		 * blocks before the pru_send (or more accurately, any blocking
1888 		 * results in a loop back to here to re-check).
1889 		 */
1890 		if ((so->so_state & SS_CANTSENDMORE) || so->so_error) {
1891 			if (so->so_state & SS_CANTSENDMORE) {
1892 				error = EPIPE;
1893 			} else {
1894 				error = so->so_error;
1895 				so->so_error = 0;
1896 			}
1897 			m_freem(m);
1898 			crit_exit();
1899 			goto done;
1900 		}
1901 		/*
1902 		 * Wait for socket space to become available. We do this just
1903 		 * after checking the connection state above in order to avoid
1904 		 * a race condition with ssb_wait().
1905 		 */
1906 		if (so->so_snd.ssb_flags & SSB_PREALLOC)
1907 			space = ssb_space_prealloc(&so->so_snd);
1908 		else
1909 			space = ssb_space(&so->so_snd);
1910 
1911 		if (space < m->m_pkthdr.len && space < so->so_snd.ssb_lowat) {
1912 			if (fp->f_flag & FNONBLOCK) {
1913 				m_freem(m);
1914 				crit_exit();
1915 				error = EAGAIN;
1916 				goto done;
1917 			}
1918 			error = ssb_wait(&so->so_snd);
1919 			/*
1920 			 * An error from ssb_wait usually indicates that we've
1921 			 * been interrupted by a signal. If we've sent anything
1922 			 * then return bytes sent, otherwise return the error.
1923 			 */
1924 			if (error) {
1925 				m_freem(m);
1926 				crit_exit();
1927 				goto done;
1928 			}
1929 			goto retry_space;
1930 		}
1931 
1932 		if (so->so_snd.ssb_flags & SSB_PREALLOC) {
1933 			for (mp = m; mp != NULL; mp = mp->m_next)
1934 				ssb_preallocstream(&so->so_snd, mp);
1935 		}
1936 		if (use_sendfile_async)
1937 			error = so_pru_senda(so, 0, m, NULL, NULL, td);
1938 		else
1939 			error = so_pru_send(so, 0, m, NULL, NULL, td);
1940 
1941 		crit_exit();
1942 		if (error)
1943 			goto done;
1944 	}
1945 	if (mheader != NULL) {
1946 		*sbytes += mheader->m_pkthdr.len;
1947 
1948 		if (so->so_snd.ssb_flags & SSB_PREALLOC) {
1949 			for (mp = mheader; mp != NULL; mp = mp->m_next)
1950 				ssb_preallocstream(&so->so_snd, mp);
1951 		}
1952 		if (use_sendfile_async)
1953 			error = so_pru_senda(so, 0, mheader, NULL, NULL, td);
1954 		else
1955 			error = so_pru_send(so, 0, mheader, NULL, NULL, td);
1956 
1957 		mheader = NULL;
1958 	}
1959 done:
1960 	vm_object_drop(obj);
1961 	ssb_unlock(&so->so_snd);
1962 done1:
1963 	dropfp(td, sfd, fp);
1964 done0:
1965 	if (mheader != NULL)
1966 		m_freem(mheader);
1967 	return (error);
1968 }
1969