xref: /freebsd/sys/netinet6/udp6_usrreq.c (revision 884a2a699669ec61e2366e3e358342dbc94be24a)
1 /*-
2  * Copyright (C) 1995, 1996, 1997, and 1998 WIDE Project.
3  * Copyright (c) 2010-2011 Juniper Networks, Inc.
4  * All rights reserved.
5  *
6  * Portions of this software were developed by Robert N. M. Watson under
7  * contract to Juniper Networks, Inc.
8  *
9  * Redistribution and use in source and binary forms, with or without
10  * modification, are permitted provided that the following conditions
11  * are met:
12  * 1. Redistributions of source code must retain the above copyright
13  *    notice, this list of conditions and the following disclaimer.
14  * 2. Redistributions in binary form must reproduce the above copyright
15  *    notice, this list of conditions and the following disclaimer in the
16  *    documentation and/or other materials provided with the distribution.
17  * 3. Neither the name of the project nor the names of its contributors
18  *    may be used to endorse or promote products derived from this software
19  *    without specific prior written permission.
20  *
21  * THIS SOFTWARE IS PROVIDED BY THE PROJECT AND CONTRIBUTORS ``AS IS'' AND
22  * ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
23  * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE
24  * ARE DISCLAIMED.  IN NO EVENT SHALL THE PROJECT OR CONTRIBUTORS BE LIABLE
25  * FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL
26  * DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS
27  * OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION)
28  * HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT
29  * LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY
30  * OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF
31  * SUCH DAMAGE.
32  *
33  *	$KAME: udp6_usrreq.c,v 1.27 2001/05/21 05:45:10 jinmei Exp $
34  *	$KAME: udp6_output.c,v 1.31 2001/05/21 16:39:15 jinmei Exp $
35  */
36 
37 /*-
38  * Copyright (c) 1982, 1986, 1988, 1990, 1993, 1995
39  *	The Regents of the University of California.
40  * All rights reserved.
41  *
42  * Redistribution and use in source and binary forms, with or without
43  * modification, are permitted provided that the following conditions
44  * are met:
45  * 1. Redistributions of source code must retain the above copyright
46  *    notice, this list of conditions and the following disclaimer.
47  * 2. Redistributions in binary form must reproduce the above copyright
48  *    notice, this list of conditions and the following disclaimer in the
49  *    documentation and/or other materials provided with the distribution.
50  * 4. Neither the name of the University nor the names of its contributors
51  *    may be used to endorse or promote products derived from this software
52  *    without specific prior written permission.
53  *
54  * THIS SOFTWARE IS PROVIDED BY THE REGENTS AND CONTRIBUTORS ``AS IS'' AND
55  * ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
56  * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE
57  * ARE DISCLAIMED.  IN NO EVENT SHALL THE REGENTS OR CONTRIBUTORS BE LIABLE
58  * FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL
59  * DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS
60  * OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION)
61  * HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT
62  * LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY
63  * OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF
64  * SUCH DAMAGE.
65  *
66  *	@(#)udp_usrreq.c	8.6 (Berkeley) 5/23/95
67  */
68 
69 #include <sys/cdefs.h>
70 __FBSDID("$FreeBSD$");
71 
72 #include "opt_inet.h"
73 #include "opt_inet6.h"
74 #include "opt_ipsec.h"
75 
76 #include <sys/param.h>
77 #include <sys/jail.h>
78 #include <sys/kernel.h>
79 #include <sys/lock.h>
80 #include <sys/mbuf.h>
81 #include <sys/priv.h>
82 #include <sys/proc.h>
83 #include <sys/protosw.h>
84 #include <sys/signalvar.h>
85 #include <sys/socket.h>
86 #include <sys/socketvar.h>
87 #include <sys/sx.h>
88 #include <sys/sysctl.h>
89 #include <sys/syslog.h>
90 #include <sys/systm.h>
91 
92 #include <net/if.h>
93 #include <net/if_types.h>
94 #include <net/route.h>
95 
96 #include <netinet/in.h>
97 #include <netinet/in_pcb.h>
98 #include <netinet/in_systm.h>
99 #include <netinet/in_var.h>
100 #include <netinet/ip.h>
101 #include <netinet/ip_icmp.h>
102 #include <netinet/ip6.h>
103 #include <netinet/icmp_var.h>
104 #include <netinet/icmp6.h>
105 #include <netinet/ip_var.h>
106 #include <netinet/udp.h>
107 #include <netinet/udp_var.h>
108 
109 #include <netinet6/ip6protosw.h>
110 #include <netinet6/ip6_var.h>
111 #include <netinet6/in6_pcb.h>
112 #include <netinet6/udp6_var.h>
113 #include <netinet6/scope6_var.h>
114 
115 #ifdef IPSEC
116 #include <netipsec/ipsec.h>
117 #include <netipsec/ipsec6.h>
118 #endif /* IPSEC */
119 
120 #include <security/mac/mac_framework.h>
121 
122 /*
123  * UDP protocol implementation.
124  * Per RFC 768, August, 1980.
125  */
126 
127 extern struct protosw	inetsw[];
128 static void		udp6_detach(struct socket *so);
129 
130 static void
131 udp6_append(struct inpcb *inp, struct mbuf *n, int off,
132     struct sockaddr_in6 *fromsa)
133 {
134 	struct socket *so;
135 	struct mbuf *opts;
136 
137 	INP_LOCK_ASSERT(inp);
138 
139 #ifdef IPSEC
140 	/* Check AH/ESP integrity. */
141 	if (ipsec6_in_reject(n, inp)) {
142 		m_freem(n);
143 		V_ipsec6stat.in_polvio++;
144 		return;
145 	}
146 #endif /* IPSEC */
147 #ifdef MAC
148 	if (mac_inpcb_check_deliver(inp, n) != 0) {
149 		m_freem(n);
150 		return;
151 	}
152 #endif
153 	opts = NULL;
154 	if (inp->inp_flags & INP_CONTROLOPTS ||
155 	    inp->inp_socket->so_options & SO_TIMESTAMP)
156 		ip6_savecontrol(inp, n, &opts);
157 	m_adj(n, off + sizeof(struct udphdr));
158 
159 	so = inp->inp_socket;
160 	SOCKBUF_LOCK(&so->so_rcv);
161 	if (sbappendaddr_locked(&so->so_rcv, (struct sockaddr *)fromsa, n,
162 	    opts) == 0) {
163 		SOCKBUF_UNLOCK(&so->so_rcv);
164 		m_freem(n);
165 		if (opts)
166 			m_freem(opts);
167 		UDPSTAT_INC(udps_fullsock);
168 	} else
169 		sorwakeup_locked(so);
170 }
171 
172 int
173 udp6_input(struct mbuf **mp, int *offp, int proto)
174 {
175 	struct mbuf *m = *mp;
176 	struct ifnet *ifp;
177 	struct ip6_hdr *ip6;
178 	struct udphdr *uh;
179 	struct inpcb *inp;
180 	struct udpcb *up;
181 	int off = *offp;
182 	int plen, ulen;
183 	struct sockaddr_in6 fromsa;
184 
185 	ifp = m->m_pkthdr.rcvif;
186 	ip6 = mtod(m, struct ip6_hdr *);
187 
188 	if (faithprefix_p != NULL && (*faithprefix_p)(&ip6->ip6_dst)) {
189 		/* XXX send icmp6 host/port unreach? */
190 		m_freem(m);
191 		return (IPPROTO_DONE);
192 	}
193 
194 #ifndef PULLDOWN_TEST
195 	IP6_EXTHDR_CHECK(m, off, sizeof(struct udphdr), IPPROTO_DONE);
196 	ip6 = mtod(m, struct ip6_hdr *);
197 	uh = (struct udphdr *)((caddr_t)ip6 + off);
198 #else
199 	IP6_EXTHDR_GET(uh, struct udphdr *, m, off, sizeof(*uh));
200 	if (!uh)
201 		return (IPPROTO_DONE);
202 #endif
203 
204 	UDPSTAT_INC(udps_ipackets);
205 
206 	/*
207 	 * Destination port of 0 is illegal, based on RFC768.
208 	 */
209 	if (uh->uh_dport == 0)
210 		goto badunlocked;
211 
212 	plen = ntohs(ip6->ip6_plen) - off + sizeof(*ip6);
213 	ulen = ntohs((u_short)uh->uh_ulen);
214 
215 	if (plen != ulen) {
216 		UDPSTAT_INC(udps_badlen);
217 		goto badunlocked;
218 	}
219 
220 	/*
221 	 * Checksum extended UDP header and data.
222 	 */
223 	if (uh->uh_sum == 0) {
224 		UDPSTAT_INC(udps_nosum);
225 		goto badunlocked;
226 	}
227 	if (in6_cksum(m, IPPROTO_UDP, off, ulen) != 0) {
228 		UDPSTAT_INC(udps_badsum);
229 		goto badunlocked;
230 	}
231 
232 	/*
233 	 * Construct sockaddr format source address.
234 	 */
235 	init_sin6(&fromsa, m);
236 	fromsa.sin6_port = uh->uh_sport;
237 
238 	if (IN6_IS_ADDR_MULTICAST(&ip6->ip6_dst)) {
239 		struct inpcb *last;
240 		struct ip6_moptions *imo;
241 
242 		INP_INFO_RLOCK(&V_udbinfo);
243 		/*
244 		 * In the event that laddr should be set to the link-local
245 		 * address (this happens in RIPng), the multicast address
246 		 * specified in the received packet will not match laddr.  To
247 		 * handle this situation, matching is relaxed if the
248 		 * receiving interface is the same as one specified in the
249 		 * socket and if the destination multicast address matches
250 		 * one of the multicast groups specified in the socket.
251 		 */
252 
253 		/*
254 		 * KAME note: traditionally we dropped udpiphdr from mbuf
255 		 * here.  We need udphdr for IPsec processing so we do that
256 		 * later.
257 		 */
258 		last = NULL;
259 		LIST_FOREACH(inp, &V_udb, inp_list) {
260 			if ((inp->inp_vflag & INP_IPV6) == 0)
261 				continue;
262 			if (inp->inp_lport != uh->uh_dport)
263 				continue;
264 			if (inp->inp_fport != 0 &&
265 			    inp->inp_fport != uh->uh_sport)
266 				continue;
267 			if (!IN6_IS_ADDR_UNSPECIFIED(&inp->in6p_laddr)) {
268 				if (!IN6_ARE_ADDR_EQUAL(&inp->in6p_laddr,
269 							&ip6->ip6_dst))
270 					continue;
271 			}
272 			if (!IN6_IS_ADDR_UNSPECIFIED(&inp->in6p_faddr)) {
273 				if (!IN6_ARE_ADDR_EQUAL(&inp->in6p_faddr,
274 							&ip6->ip6_src) ||
275 				    inp->inp_fport != uh->uh_sport)
276 					continue;
277 			}
278 
279 			/*
280 			 * XXXRW: Because we weren't holding either the inpcb
281 			 * or the hash lock when we checked for a match
282 			 * before, we should probably recheck now that the
283 			 * inpcb lock is (supposed to be) held.
284 			 */
285 
286 			/*
287 			 * Handle socket delivery policy for any-source
288 			 * and source-specific multicast. [RFC3678]
289 			 */
290 			imo = inp->in6p_moptions;
291 			if (imo && IN6_IS_ADDR_MULTICAST(&ip6->ip6_dst)) {
292 				struct sockaddr_in6	 mcaddr;
293 				int			 blocked;
294 
295 				INP_RLOCK(inp);
296 
297 				bzero(&mcaddr, sizeof(struct sockaddr_in6));
298 				mcaddr.sin6_len = sizeof(struct sockaddr_in6);
299 				mcaddr.sin6_family = AF_INET6;
300 				mcaddr.sin6_addr = ip6->ip6_dst;
301 
302 				blocked = im6o_mc_filter(imo, ifp,
303 					(struct sockaddr *)&mcaddr,
304 					(struct sockaddr *)&fromsa);
305 				if (blocked != MCAST_PASS) {
306 					if (blocked == MCAST_NOTGMEMBER)
307 						IP6STAT_INC(ip6s_notmember);
308 					if (blocked == MCAST_NOTSMEMBER ||
309 					    blocked == MCAST_MUTED)
310 						UDPSTAT_INC(udps_filtermcast);
311 					INP_RUNLOCK(inp); /* XXX */
312 					continue;
313 				}
314 
315 				INP_RUNLOCK(inp);
316 			}
317 			if (last != NULL) {
318 				struct mbuf *n;
319 
320 				if ((n = m_copy(m, 0, M_COPYALL)) != NULL) {
321 					INP_RLOCK(last);
322 					up = intoudpcb(last);
323 					if (up->u_tun_func == NULL) {
324 						udp6_append(last, n, off, &fromsa);
325 					} else {
326 						/*
327 						 * Engage the tunneling
328 						 * protocol we will have to
329 						 * leave the info_lock up,
330 						 * since we are hunting
331 						 * through multiple UDP's.
332 						 *
333 						 */
334 						(*up->u_tun_func)(n, off, last);
335 					}
336 					INP_RUNLOCK(last);
337 				}
338 			}
339 			last = inp;
340 			/*
341 			 * Don't look for additional matches if this one does
342 			 * not have either the SO_REUSEPORT or SO_REUSEADDR
343 			 * socket options set.  This heuristic avoids
344 			 * searching through all pcbs in the common case of a
345 			 * non-shared port.  It assumes that an application
346 			 * will never clear these options after setting them.
347 			 */
348 			if ((last->inp_socket->so_options &
349 			     (SO_REUSEPORT|SO_REUSEADDR)) == 0)
350 				break;
351 		}
352 
353 		if (last == NULL) {
354 			/*
355 			 * No matching pcb found; discard datagram.  (No need
356 			 * to send an ICMP Port Unreachable for a broadcast
357 			 * or multicast datgram.)
358 			 */
359 			UDPSTAT_INC(udps_noport);
360 			UDPSTAT_INC(udps_noportmcast);
361 			goto badheadlocked;
362 		}
363 		INP_RLOCK(last);
364 		INP_INFO_RUNLOCK(&V_udbinfo);
365 		up = intoudpcb(last);
366 		if (up->u_tun_func == NULL) {
367 			udp6_append(last, m, off, &fromsa);
368 		} else {
369 			/*
370 			 * Engage the tunneling protocol.
371 			 */
372 			(*up->u_tun_func)(m, off, last);
373 		}
374 		INP_RUNLOCK(last);
375 		return (IPPROTO_DONE);
376 	}
377 	/*
378 	 * Locate pcb for datagram.
379 	 */
380 	inp = in6_pcblookup_mbuf(&V_udbinfo, &ip6->ip6_src, uh->uh_sport,
381 	    &ip6->ip6_dst, uh->uh_dport, INPLOOKUP_WILDCARD |
382 	    INPLOOKUP_RLOCKPCB, m->m_pkthdr.rcvif, m);
383 	if (inp == NULL) {
384 		if (udp_log_in_vain) {
385 			char ip6bufs[INET6_ADDRSTRLEN];
386 			char ip6bufd[INET6_ADDRSTRLEN];
387 
388 			log(LOG_INFO,
389 			    "Connection attempt to UDP [%s]:%d from [%s]:%d\n",
390 			    ip6_sprintf(ip6bufd, &ip6->ip6_dst),
391 			    ntohs(uh->uh_dport),
392 			    ip6_sprintf(ip6bufs, &ip6->ip6_src),
393 			    ntohs(uh->uh_sport));
394 		}
395 		UDPSTAT_INC(udps_noport);
396 		if (m->m_flags & M_MCAST) {
397 			printf("UDP6: M_MCAST is set in a unicast packet.\n");
398 			UDPSTAT_INC(udps_noportmcast);
399 			goto badunlocked;
400 		}
401 		if (V_udp_blackhole)
402 			goto badunlocked;
403 		if (badport_bandlim(BANDLIM_ICMP6_UNREACH) < 0)
404 			goto badunlocked;
405 		icmp6_error(m, ICMP6_DST_UNREACH, ICMP6_DST_UNREACH_NOPORT, 0);
406 		return (IPPROTO_DONE);
407 	}
408 	INP_RLOCK_ASSERT(inp);
409 	up = intoudpcb(inp);
410 	if (up->u_tun_func == NULL) {
411 		udp6_append(inp, m, off, &fromsa);
412 	} else {
413 		/*
414 		 * Engage the tunneling protocol.
415 		 */
416 
417 		(*up->u_tun_func)(m, off, inp);
418 	}
419 	INP_RUNLOCK(inp);
420 	return (IPPROTO_DONE);
421 
422 badheadlocked:
423 	INP_INFO_RUNLOCK(&V_udbinfo);
424 badunlocked:
425 	if (m)
426 		m_freem(m);
427 	return (IPPROTO_DONE);
428 }
429 
430 void
431 udp6_ctlinput(int cmd, struct sockaddr *sa, void *d)
432 {
433 	struct udphdr uh;
434 	struct ip6_hdr *ip6;
435 	struct mbuf *m;
436 	int off = 0;
437 	struct ip6ctlparam *ip6cp = NULL;
438 	const struct sockaddr_in6 *sa6_src = NULL;
439 	void *cmdarg;
440 	struct inpcb *(*notify)(struct inpcb *, int) = udp_notify;
441 	struct udp_portonly {
442 		u_int16_t uh_sport;
443 		u_int16_t uh_dport;
444 	} *uhp;
445 
446 	if (sa->sa_family != AF_INET6 ||
447 	    sa->sa_len != sizeof(struct sockaddr_in6))
448 		return;
449 
450 	if ((unsigned)cmd >= PRC_NCMDS)
451 		return;
452 	if (PRC_IS_REDIRECT(cmd))
453 		notify = in6_rtchange, d = NULL;
454 	else if (cmd == PRC_HOSTDEAD)
455 		d = NULL;
456 	else if (inet6ctlerrmap[cmd] == 0)
457 		return;
458 
459 	/* if the parameter is from icmp6, decode it. */
460 	if (d != NULL) {
461 		ip6cp = (struct ip6ctlparam *)d;
462 		m = ip6cp->ip6c_m;
463 		ip6 = ip6cp->ip6c_ip6;
464 		off = ip6cp->ip6c_off;
465 		cmdarg = ip6cp->ip6c_cmdarg;
466 		sa6_src = ip6cp->ip6c_src;
467 	} else {
468 		m = NULL;
469 		ip6 = NULL;
470 		cmdarg = NULL;
471 		sa6_src = &sa6_any;
472 	}
473 
474 	if (ip6) {
475 		/*
476 		 * XXX: We assume that when IPV6 is non NULL,
477 		 * M and OFF are valid.
478 		 */
479 
480 		/* Check if we can safely examine src and dst ports. */
481 		if (m->m_pkthdr.len < off + sizeof(*uhp))
482 			return;
483 
484 		bzero(&uh, sizeof(uh));
485 		m_copydata(m, off, sizeof(*uhp), (caddr_t)&uh);
486 
487 		(void) in6_pcbnotify(&V_udbinfo, sa, uh.uh_dport,
488 		    (struct sockaddr *)ip6cp->ip6c_src, uh.uh_sport, cmd,
489 		    cmdarg, notify);
490 	} else
491 		(void) in6_pcbnotify(&V_udbinfo, sa, 0,
492 		    (const struct sockaddr *)sa6_src, 0, cmd, cmdarg, notify);
493 }
494 
495 static int
496 udp6_getcred(SYSCTL_HANDLER_ARGS)
497 {
498 	struct xucred xuc;
499 	struct sockaddr_in6 addrs[2];
500 	struct inpcb *inp;
501 	int error;
502 
503 	error = priv_check(req->td, PRIV_NETINET_GETCRED);
504 	if (error)
505 		return (error);
506 
507 	if (req->newlen != sizeof(addrs))
508 		return (EINVAL);
509 	if (req->oldlen != sizeof(struct xucred))
510 		return (EINVAL);
511 	error = SYSCTL_IN(req, addrs, sizeof(addrs));
512 	if (error)
513 		return (error);
514 	if ((error = sa6_embedscope(&addrs[0], V_ip6_use_defzone)) != 0 ||
515 	    (error = sa6_embedscope(&addrs[1], V_ip6_use_defzone)) != 0) {
516 		return (error);
517 	}
518 	inp = in6_pcblookup(&V_udbinfo, &addrs[1].sin6_addr,
519 	    addrs[1].sin6_port, &addrs[0].sin6_addr, addrs[0].sin6_port,
520 	    INPLOOKUP_WILDCARD | INPLOOKUP_RLOCKPCB, NULL);
521 	if (inp != NULL) {
522 		INP_RLOCK_ASSERT(inp);
523 		if (inp->inp_socket == NULL)
524 			error = ENOENT;
525 		if (error == 0)
526 			error = cr_canseesocket(req->td->td_ucred,
527 			    inp->inp_socket);
528 		if (error == 0)
529 			cru2x(inp->inp_cred, &xuc);
530 		INP_RUNLOCK(inp);
531 	} else
532 		error = ENOENT;
533 	if (error == 0)
534 		error = SYSCTL_OUT(req, &xuc, sizeof(struct xucred));
535 	return (error);
536 }
537 
538 SYSCTL_PROC(_net_inet6_udp6, OID_AUTO, getcred, CTLTYPE_OPAQUE|CTLFLAG_RW, 0,
539     0, udp6_getcred, "S,xucred", "Get the xucred of a UDP6 connection");
540 
541 static int
542 udp6_output(struct inpcb *inp, struct mbuf *m, struct sockaddr *addr6,
543     struct mbuf *control, struct thread *td)
544 {
545 	u_int32_t ulen = m->m_pkthdr.len;
546 	u_int32_t plen = sizeof(struct udphdr) + ulen;
547 	struct ip6_hdr *ip6;
548 	struct udphdr *udp6;
549 	struct in6_addr *laddr, *faddr, in6a;
550 	struct sockaddr_in6 *sin6 = NULL;
551 	struct ifnet *oifp = NULL;
552 	int scope_ambiguous = 0;
553 	u_short fport;
554 	int error = 0;
555 	struct ip6_pktopts *optp, opt;
556 	int af = AF_INET6, hlen = sizeof(struct ip6_hdr);
557 	int flags;
558 	struct sockaddr_in6 tmp;
559 
560 	INP_WLOCK_ASSERT(inp);
561 	INP_HASH_WLOCK_ASSERT(inp->inp_pcbinfo);
562 
563 	if (addr6) {
564 		/* addr6 has been validated in udp6_send(). */
565 		sin6 = (struct sockaddr_in6 *)addr6;
566 
567 		/* protect *sin6 from overwrites */
568 		tmp = *sin6;
569 		sin6 = &tmp;
570 
571 		/*
572 		 * Application should provide a proper zone ID or the use of
573 		 * default zone IDs should be enabled.  Unfortunately, some
574 		 * applications do not behave as it should, so we need a
575 		 * workaround.  Even if an appropriate ID is not determined,
576 		 * we'll see if we can determine the outgoing interface.  If we
577 		 * can, determine the zone ID based on the interface below.
578 		 */
579 		if (sin6->sin6_scope_id == 0 && !V_ip6_use_defzone)
580 			scope_ambiguous = 1;
581 		if ((error = sa6_embedscope(sin6, V_ip6_use_defzone)) != 0)
582 			return (error);
583 	}
584 
585 	if (control) {
586 		if ((error = ip6_setpktopts(control, &opt,
587 		    inp->in6p_outputopts, td->td_ucred, IPPROTO_UDP)) != 0)
588 			goto release;
589 		optp = &opt;
590 	} else
591 		optp = inp->in6p_outputopts;
592 
593 	if (sin6) {
594 		faddr = &sin6->sin6_addr;
595 
596 		/*
597 		 * IPv4 version of udp_output calls in_pcbconnect in this case,
598 		 * which needs splnet and affects performance.
599 		 * Since we saw no essential reason for calling in_pcbconnect,
600 		 * we get rid of such kind of logic, and call in6_selectsrc
601 		 * and in6_pcbsetport in order to fill in the local address
602 		 * and the local port.
603 		 */
604 		if (sin6->sin6_port == 0) {
605 			error = EADDRNOTAVAIL;
606 			goto release;
607 		}
608 
609 		if (!IN6_IS_ADDR_UNSPECIFIED(&inp->in6p_faddr)) {
610 			/* how about ::ffff:0.0.0.0 case? */
611 			error = EISCONN;
612 			goto release;
613 		}
614 
615 		fport = sin6->sin6_port; /* allow 0 port */
616 
617 		if (IN6_IS_ADDR_V4MAPPED(faddr)) {
618 			if ((inp->inp_flags & IN6P_IPV6_V6ONLY)) {
619 				/*
620 				 * I believe we should explicitly discard the
621 				 * packet when mapped addresses are disabled,
622 				 * rather than send the packet as an IPv6 one.
623 				 * If we chose the latter approach, the packet
624 				 * might be sent out on the wire based on the
625 				 * default route, the situation which we'd
626 				 * probably want to avoid.
627 				 * (20010421 jinmei@kame.net)
628 				 */
629 				error = EINVAL;
630 				goto release;
631 			}
632 			if (!IN6_IS_ADDR_UNSPECIFIED(&inp->in6p_laddr) &&
633 			    !IN6_IS_ADDR_V4MAPPED(&inp->in6p_laddr)) {
634 				/*
635 				 * when remote addr is an IPv4-mapped address,
636 				 * local addr should not be an IPv6 address,
637 				 * since you cannot determine how to map IPv6
638 				 * source address to IPv4.
639 				 */
640 				error = EINVAL;
641 				goto release;
642 			}
643 
644 			af = AF_INET;
645 		}
646 
647 		if (!IN6_IS_ADDR_V4MAPPED(faddr)) {
648 			error = in6_selectsrc(sin6, optp, inp, NULL,
649 			    td->td_ucred, &oifp, &in6a);
650 			if (error)
651 				goto release;
652 			if (oifp && scope_ambiguous &&
653 			    (error = in6_setscope(&sin6->sin6_addr,
654 			    oifp, NULL))) {
655 				goto release;
656 			}
657 			laddr = &in6a;
658 		} else
659 			laddr = &inp->in6p_laddr;	/* XXX */
660 		if (laddr == NULL) {
661 			if (error == 0)
662 				error = EADDRNOTAVAIL;
663 			goto release;
664 		}
665 		if (inp->inp_lport == 0 &&
666 		    (error = in6_pcbsetport(laddr, inp, td->td_ucred)) != 0) {
667 			/* Undo an address bind that may have occurred. */
668 			inp->in6p_laddr = in6addr_any;
669 			goto release;
670 		}
671 	} else {
672 		if (IN6_IS_ADDR_UNSPECIFIED(&inp->in6p_faddr)) {
673 			error = ENOTCONN;
674 			goto release;
675 		}
676 		if (IN6_IS_ADDR_V4MAPPED(&inp->in6p_faddr)) {
677 			if ((inp->inp_flags & IN6P_IPV6_V6ONLY)) {
678 				/*
679 				 * XXX: this case would happen when the
680 				 * application sets the V6ONLY flag after
681 				 * connecting the foreign address.
682 				 * Such applications should be fixed,
683 				 * so we bark here.
684 				 */
685 				log(LOG_INFO, "udp6_output: IPV6_V6ONLY "
686 				    "option was set for a connected socket\n");
687 				error = EINVAL;
688 				goto release;
689 			} else
690 				af = AF_INET;
691 		}
692 		laddr = &inp->in6p_laddr;
693 		faddr = &inp->in6p_faddr;
694 		fport = inp->inp_fport;
695 	}
696 
697 	if (af == AF_INET)
698 		hlen = sizeof(struct ip);
699 
700 	/*
701 	 * Calculate data length and get a mbuf
702 	 * for UDP and IP6 headers.
703 	 */
704 	M_PREPEND(m, hlen + sizeof(struct udphdr), M_DONTWAIT);
705 	if (m == 0) {
706 		error = ENOBUFS;
707 		goto release;
708 	}
709 
710 	/*
711 	 * Stuff checksum and output datagram.
712 	 */
713 	udp6 = (struct udphdr *)(mtod(m, caddr_t) + hlen);
714 	udp6->uh_sport = inp->inp_lport; /* lport is always set in the PCB */
715 	udp6->uh_dport = fport;
716 	if (plen <= 0xffff)
717 		udp6->uh_ulen = htons((u_short)plen);
718 	else
719 		udp6->uh_ulen = 0;
720 	udp6->uh_sum = 0;
721 
722 	switch (af) {
723 	case AF_INET6:
724 		ip6 = mtod(m, struct ip6_hdr *);
725 		ip6->ip6_flow	= inp->inp_flow & IPV6_FLOWINFO_MASK;
726 		ip6->ip6_vfc	&= ~IPV6_VERSION_MASK;
727 		ip6->ip6_vfc	|= IPV6_VERSION;
728 #if 0				/* ip6_plen will be filled in ip6_output. */
729 		ip6->ip6_plen	= htons((u_short)plen);
730 #endif
731 		ip6->ip6_nxt	= IPPROTO_UDP;
732 		ip6->ip6_hlim	= in6_selecthlim(inp, NULL);
733 		ip6->ip6_src	= *laddr;
734 		ip6->ip6_dst	= *faddr;
735 
736 		if ((udp6->uh_sum = in6_cksum(m, IPPROTO_UDP,
737 				sizeof(struct ip6_hdr), plen)) == 0) {
738 			udp6->uh_sum = 0xffff;
739 		}
740 
741 		flags = 0;
742 
743 		UDPSTAT_INC(udps_opackets);
744 		error = ip6_output(m, optp, NULL, flags, inp->in6p_moptions,
745 		    NULL, inp);
746 		break;
747 	case AF_INET:
748 		error = EAFNOSUPPORT;
749 		goto release;
750 	}
751 	goto releaseopt;
752 
753 release:
754 	m_freem(m);
755 
756 releaseopt:
757 	if (control) {
758 		ip6_clearpktopts(&opt, -1);
759 		m_freem(control);
760 	}
761 	return (error);
762 }
763 
764 static void
765 udp6_abort(struct socket *so)
766 {
767 	struct inpcb *inp;
768 
769 	inp = sotoinpcb(so);
770 	KASSERT(inp != NULL, ("udp6_abort: inp == NULL"));
771 
772 #ifdef INET
773 	if (inp->inp_vflag & INP_IPV4) {
774 		struct pr_usrreqs *pru;
775 
776 		pru = inetsw[ip_protox[IPPROTO_UDP]].pr_usrreqs;
777 		(*pru->pru_abort)(so);
778 		return;
779 	}
780 #endif
781 
782 	INP_WLOCK(inp);
783 	if (!IN6_IS_ADDR_UNSPECIFIED(&inp->in6p_faddr)) {
784 		INP_HASH_WLOCK(&V_udbinfo);
785 		in6_pcbdisconnect(inp);
786 		inp->in6p_laddr = in6addr_any;
787 		INP_HASH_WUNLOCK(&V_udbinfo);
788 		soisdisconnected(so);
789 	}
790 	INP_WUNLOCK(inp);
791 }
792 
793 static int
794 udp6_attach(struct socket *so, int proto, struct thread *td)
795 {
796 	struct inpcb *inp;
797 	int error;
798 
799 	inp = sotoinpcb(so);
800 	KASSERT(inp == NULL, ("udp6_attach: inp != NULL"));
801 
802 	if (so->so_snd.sb_hiwat == 0 || so->so_rcv.sb_hiwat == 0) {
803 		error = soreserve(so, udp_sendspace, udp_recvspace);
804 		if (error)
805 			return (error);
806 	}
807 	INP_INFO_WLOCK(&V_udbinfo);
808 	error = in_pcballoc(so, &V_udbinfo);
809 	if (error) {
810 		INP_INFO_WUNLOCK(&V_udbinfo);
811 		return (error);
812 	}
813 	inp = (struct inpcb *)so->so_pcb;
814 	inp->inp_vflag |= INP_IPV6;
815 	if ((inp->inp_flags & IN6P_IPV6_V6ONLY) == 0)
816 		inp->inp_vflag |= INP_IPV4;
817 	inp->in6p_hops = -1;	/* use kernel default */
818 	inp->in6p_cksum = -1;	/* just to be sure */
819 	/*
820 	 * XXX: ugly!!
821 	 * IPv4 TTL initialization is necessary for an IPv6 socket as well,
822 	 * because the socket may be bound to an IPv6 wildcard address,
823 	 * which may match an IPv4-mapped IPv6 address.
824 	 */
825 	inp->inp_ip_ttl = V_ip_defttl;
826 
827 	error = udp_newudpcb(inp);
828 	if (error) {
829 		in_pcbdetach(inp);
830 		in_pcbfree(inp);
831 		INP_INFO_WUNLOCK(&V_udbinfo);
832 		return (error);
833 	}
834 	INP_WUNLOCK(inp);
835 	INP_INFO_WUNLOCK(&V_udbinfo);
836 	return (0);
837 }
838 
839 static int
840 udp6_bind(struct socket *so, struct sockaddr *nam, struct thread *td)
841 {
842 	struct inpcb *inp;
843 	int error;
844 
845 	inp = sotoinpcb(so);
846 	KASSERT(inp != NULL, ("udp6_bind: inp == NULL"));
847 
848 	INP_WLOCK(inp);
849 	INP_HASH_WLOCK(&V_udbinfo);
850 	inp->inp_vflag &= ~INP_IPV4;
851 	inp->inp_vflag |= INP_IPV6;
852 	if ((inp->inp_flags & IN6P_IPV6_V6ONLY) == 0) {
853 		struct sockaddr_in6 *sin6_p;
854 
855 		sin6_p = (struct sockaddr_in6 *)nam;
856 
857 		if (IN6_IS_ADDR_UNSPECIFIED(&sin6_p->sin6_addr))
858 			inp->inp_vflag |= INP_IPV4;
859 #ifdef INET
860 		else if (IN6_IS_ADDR_V4MAPPED(&sin6_p->sin6_addr)) {
861 			struct sockaddr_in sin;
862 
863 			in6_sin6_2_sin(&sin, sin6_p);
864 			inp->inp_vflag |= INP_IPV4;
865 			inp->inp_vflag &= ~INP_IPV6;
866 			error = in_pcbbind(inp, (struct sockaddr *)&sin,
867 			    td->td_ucred);
868 			goto out;
869 		}
870 #endif
871 	}
872 
873 	error = in6_pcbbind(inp, nam, td->td_ucred);
874 #ifdef INET
875 out:
876 #endif
877 	INP_HASH_WUNLOCK(&V_udbinfo);
878 	INP_WUNLOCK(inp);
879 	return (error);
880 }
881 
882 static void
883 udp6_close(struct socket *so)
884 {
885 	struct inpcb *inp;
886 
887 	inp = sotoinpcb(so);
888 	KASSERT(inp != NULL, ("udp6_close: inp == NULL"));
889 
890 #ifdef INET
891 	if (inp->inp_vflag & INP_IPV4) {
892 		struct pr_usrreqs *pru;
893 
894 		pru = inetsw[ip_protox[IPPROTO_UDP]].pr_usrreqs;
895 		(*pru->pru_disconnect)(so);
896 		return;
897 	}
898 #endif
899 	INP_WLOCK(inp);
900 	if (!IN6_IS_ADDR_UNSPECIFIED(&inp->in6p_faddr)) {
901 		INP_HASH_WLOCK(&V_udbinfo);
902 		in6_pcbdisconnect(inp);
903 		inp->in6p_laddr = in6addr_any;
904 		INP_HASH_WUNLOCK(&V_udbinfo);
905 		soisdisconnected(so);
906 	}
907 	INP_WUNLOCK(inp);
908 }
909 
910 static int
911 udp6_connect(struct socket *so, struct sockaddr *nam, struct thread *td)
912 {
913 	struct inpcb *inp;
914 	struct sockaddr_in6 *sin6;
915 	int error;
916 
917 	inp = sotoinpcb(so);
918 	sin6 = (struct sockaddr_in6 *)nam;
919 	KASSERT(inp != NULL, ("udp6_connect: inp == NULL"));
920 
921 	/*
922 	 * XXXRW: Need to clarify locking of v4/v6 flags.
923 	 */
924 	INP_WLOCK(inp);
925 #ifdef INET
926 	if (IN6_IS_ADDR_V4MAPPED(&sin6->sin6_addr)) {
927 		struct sockaddr_in sin;
928 
929 		if ((inp->inp_flags & IN6P_IPV6_V6ONLY) != 0) {
930 			error = EINVAL;
931 			goto out;
932 		}
933 		if (inp->inp_faddr.s_addr != INADDR_ANY) {
934 			error = EISCONN;
935 			goto out;
936 		}
937 		in6_sin6_2_sin(&sin, sin6);
938 		inp->inp_vflag |= INP_IPV4;
939 		inp->inp_vflag &= ~INP_IPV6;
940 		error = prison_remote_ip4(td->td_ucred, &sin.sin_addr);
941 		if (error != 0)
942 			goto out;
943 		INP_HASH_WLOCK(&V_udbinfo);
944 		error = in_pcbconnect(inp, (struct sockaddr *)&sin,
945 		    td->td_ucred);
946 		INP_HASH_WUNLOCK(&V_udbinfo);
947 		if (error == 0)
948 			soisconnected(so);
949 		goto out;
950 	}
951 #endif
952 	if (!IN6_IS_ADDR_UNSPECIFIED(&inp->in6p_faddr)) {
953 		error = EISCONN;
954 		goto out;
955 	}
956 	inp->inp_vflag &= ~INP_IPV4;
957 	inp->inp_vflag |= INP_IPV6;
958 	error = prison_remote_ip6(td->td_ucred, &sin6->sin6_addr);
959 	if (error != 0)
960 		goto out;
961 	INP_HASH_WLOCK(&V_udbinfo);
962 	error = in6_pcbconnect(inp, nam, td->td_ucred);
963 	INP_HASH_WUNLOCK(&V_udbinfo);
964 	if (error == 0)
965 		soisconnected(so);
966 out:
967 	INP_WUNLOCK(inp);
968 	return (error);
969 }
970 
971 static void
972 udp6_detach(struct socket *so)
973 {
974 	struct inpcb *inp;
975 	struct udpcb *up;
976 
977 	inp = sotoinpcb(so);
978 	KASSERT(inp != NULL, ("udp6_detach: inp == NULL"));
979 
980 	INP_INFO_WLOCK(&V_udbinfo);
981 	INP_WLOCK(inp);
982 	up = intoudpcb(inp);
983 	KASSERT(up != NULL, ("%s: up == NULL", __func__));
984 	in_pcbdetach(inp);
985 	in_pcbfree(inp);
986 	INP_INFO_WUNLOCK(&V_udbinfo);
987 	udp_discardcb(up);
988 }
989 
990 static int
991 udp6_disconnect(struct socket *so)
992 {
993 	struct inpcb *inp;
994 	int error;
995 
996 	inp = sotoinpcb(so);
997 	KASSERT(inp != NULL, ("udp6_disconnect: inp == NULL"));
998 
999 #ifdef INET
1000 	if (inp->inp_vflag & INP_IPV4) {
1001 		struct pr_usrreqs *pru;
1002 
1003 		pru = inetsw[ip_protox[IPPROTO_UDP]].pr_usrreqs;
1004 		(void)(*pru->pru_disconnect)(so);
1005 		return (0);
1006 	}
1007 #endif
1008 
1009 	INP_WLOCK(inp);
1010 
1011 	if (IN6_IS_ADDR_UNSPECIFIED(&inp->in6p_faddr)) {
1012 		error = ENOTCONN;
1013 		goto out;
1014 	}
1015 
1016 	INP_HASH_WLOCK(&V_udbinfo);
1017 	in6_pcbdisconnect(inp);
1018 	inp->in6p_laddr = in6addr_any;
1019 	INP_HASH_WUNLOCK(&V_udbinfo);
1020 	SOCK_LOCK(so);
1021 	so->so_state &= ~SS_ISCONNECTED;		/* XXX */
1022 	SOCK_UNLOCK(so);
1023 out:
1024 	INP_WUNLOCK(inp);
1025 	return (0);
1026 }
1027 
1028 static int
1029 udp6_send(struct socket *so, int flags, struct mbuf *m,
1030     struct sockaddr *addr, struct mbuf *control, struct thread *td)
1031 {
1032 	struct inpcb *inp;
1033 	int error = 0;
1034 
1035 	inp = sotoinpcb(so);
1036 	KASSERT(inp != NULL, ("udp6_send: inp == NULL"));
1037 
1038 	INP_WLOCK(inp);
1039 	if (addr) {
1040 		if (addr->sa_len != sizeof(struct sockaddr_in6)) {
1041 			error = EINVAL;
1042 			goto bad;
1043 		}
1044 		if (addr->sa_family != AF_INET6) {
1045 			error = EAFNOSUPPORT;
1046 			goto bad;
1047 		}
1048 	}
1049 
1050 #ifdef INET
1051 	if ((inp->inp_flags & IN6P_IPV6_V6ONLY) == 0) {
1052 		int hasv4addr;
1053 		struct sockaddr_in6 *sin6 = 0;
1054 
1055 		if (addr == 0)
1056 			hasv4addr = (inp->inp_vflag & INP_IPV4);
1057 		else {
1058 			sin6 = (struct sockaddr_in6 *)addr;
1059 			hasv4addr = IN6_IS_ADDR_V4MAPPED(&sin6->sin6_addr)
1060 			    ? 1 : 0;
1061 		}
1062 		if (hasv4addr) {
1063 			struct pr_usrreqs *pru;
1064 
1065 			/*
1066 			 * XXXRW: We release UDP-layer locks before calling
1067 			 * udp_send() in order to avoid recursion.  However,
1068 			 * this does mean there is a short window where inp's
1069 			 * fields are unstable.  Could this lead to a
1070 			 * potential race in which the factors causing us to
1071 			 * select the UDPv4 output routine are invalidated?
1072 			 */
1073 			INP_WUNLOCK(inp);
1074 			if (sin6)
1075 				in6_sin6_2_sin_in_sock(addr);
1076 			pru = inetsw[ip_protox[IPPROTO_UDP]].pr_usrreqs;
1077 			/* addr will just be freed in sendit(). */
1078 			return ((*pru->pru_send)(so, flags, m, addr, control,
1079 			    td));
1080 		}
1081 	}
1082 #endif
1083 #ifdef MAC
1084 	mac_inpcb_create_mbuf(inp, m);
1085 #endif
1086 	INP_HASH_WLOCK(&V_udbinfo);
1087 	error = udp6_output(inp, m, addr, control, td);
1088 	INP_HASH_WUNLOCK(&V_udbinfo);
1089 #ifdef INET
1090 #endif
1091 	INP_WUNLOCK(inp);
1092 	return (error);
1093 
1094 bad:
1095 	INP_WUNLOCK(inp);
1096 	m_freem(m);
1097 	return (error);
1098 }
1099 
1100 struct pr_usrreqs udp6_usrreqs = {
1101 	.pru_abort =		udp6_abort,
1102 	.pru_attach =		udp6_attach,
1103 	.pru_bind =		udp6_bind,
1104 	.pru_connect =		udp6_connect,
1105 	.pru_control =		in6_control,
1106 	.pru_detach =		udp6_detach,
1107 	.pru_disconnect =	udp6_disconnect,
1108 	.pru_peeraddr =		in6_mapped_peeraddr,
1109 	.pru_send =		udp6_send,
1110 	.pru_shutdown =		udp_shutdown,
1111 	.pru_sockaddr =		in6_mapped_sockaddr,
1112 	.pru_soreceive =	soreceive_dgram,
1113 	.pru_sosend =		sosend_dgram,
1114 	.pru_sosetlabel =	in_pcbsosetlabel,
1115 	.pru_close =		udp6_close
1116 };
1117