xref: /freebsd/sys/netinet6/udp6_usrreq.c (revision c7046f76)
1 /*-
2  * SPDX-License-Identifier: BSD-3-Clause
3  *
4  * Copyright (C) 1995, 1996, 1997, and 1998 WIDE Project.
5  * Copyright (c) 2010-2011 Juniper Networks, Inc.
6  * Copyright (c) 2014 Kevin Lo
7  * All rights reserved.
8  *
9  * Portions of this software were developed by Robert N. M. Watson under
10  * contract to Juniper Networks, Inc.
11  *
12  * Redistribution and use in source and binary forms, with or without
13  * modification, are permitted provided that the following conditions
14  * are met:
15  * 1. Redistributions of source code must retain the above copyright
16  *    notice, this list of conditions and the following disclaimer.
17  * 2. Redistributions in binary form must reproduce the above copyright
18  *    notice, this list of conditions and the following disclaimer in the
19  *    documentation and/or other materials provided with the distribution.
20  * 3. Neither the name of the project nor the names of its contributors
21  *    may be used to endorse or promote products derived from this software
22  *    without specific prior written permission.
23  *
24  * THIS SOFTWARE IS PROVIDED BY THE PROJECT AND CONTRIBUTORS ``AS IS'' AND
25  * ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
26  * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE
27  * ARE DISCLAIMED.  IN NO EVENT SHALL THE PROJECT OR CONTRIBUTORS BE LIABLE
28  * FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL
29  * DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS
30  * OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION)
31  * HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT
32  * LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY
33  * OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF
34  * SUCH DAMAGE.
35  *
36  *	$KAME: udp6_usrreq.c,v 1.27 2001/05/21 05:45:10 jinmei Exp $
37  *	$KAME: udp6_output.c,v 1.31 2001/05/21 16:39:15 jinmei Exp $
38  */
39 
40 /*-
41  * Copyright (c) 1982, 1986, 1988, 1990, 1993, 1995
42  *	The Regents of the University of California.
43  * All rights reserved.
44  *
45  * Redistribution and use in source and binary forms, with or without
46  * modification, are permitted provided that the following conditions
47  * are met:
48  * 1. Redistributions of source code must retain the above copyright
49  *    notice, this list of conditions and the following disclaimer.
50  * 2. Redistributions in binary form must reproduce the above copyright
51  *    notice, this list of conditions and the following disclaimer in the
52  *    documentation and/or other materials provided with the distribution.
53  * 3. Neither the name of the University nor the names of its contributors
54  *    may be used to endorse or promote products derived from this software
55  *    without specific prior written permission.
56  *
57  * THIS SOFTWARE IS PROVIDED BY THE REGENTS AND CONTRIBUTORS ``AS IS'' AND
58  * ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
59  * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE
60  * ARE DISCLAIMED.  IN NO EVENT SHALL THE REGENTS OR CONTRIBUTORS BE LIABLE
61  * FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL
62  * DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS
63  * OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION)
64  * HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT
65  * LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY
66  * OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF
67  * SUCH DAMAGE.
68  *
69  *	@(#)udp_usrreq.c	8.6 (Berkeley) 5/23/95
70  */
71 
72 #include <sys/cdefs.h>
73 __FBSDID("$FreeBSD$");
74 
75 #include "opt_inet.h"
76 #include "opt_inet6.h"
77 #include "opt_ipsec.h"
78 #include "opt_route.h"
79 #include "opt_rss.h"
80 
81 #include <sys/param.h>
82 #include <sys/jail.h>
83 #include <sys/kernel.h>
84 #include <sys/lock.h>
85 #include <sys/mbuf.h>
86 #include <sys/priv.h>
87 #include <sys/proc.h>
88 #include <sys/protosw.h>
89 #include <sys/sdt.h>
90 #include <sys/signalvar.h>
91 #include <sys/socket.h>
92 #include <sys/socketvar.h>
93 #include <sys/sx.h>
94 #include <sys/sysctl.h>
95 #include <sys/syslog.h>
96 #include <sys/systm.h>
97 
98 #include <net/if.h>
99 #include <net/if_var.h>
100 #include <net/if_types.h>
101 #include <net/route.h>
102 #include <net/rss_config.h>
103 
104 #include <netinet/in.h>
105 #include <netinet/in_kdtrace.h>
106 #include <netinet/in_pcb.h>
107 #include <netinet/in_systm.h>
108 #include <netinet/in_var.h>
109 #include <netinet/ip.h>
110 #include <netinet/ip6.h>
111 #include <netinet/icmp6.h>
112 #include <netinet/ip_var.h>
113 #include <netinet/udp.h>
114 #include <netinet/udp_var.h>
115 #include <netinet/udplite.h>
116 
117 #include <netinet6/ip6protosw.h>
118 #include <netinet6/ip6_var.h>
119 #include <netinet6/in6_fib.h>
120 #include <netinet6/in6_pcb.h>
121 #include <netinet6/in6_rss.h>
122 #include <netinet6/udp6_var.h>
123 #include <netinet6/scope6_var.h>
124 
125 #include <netipsec/ipsec_support.h>
126 
127 #include <security/mac/mac_framework.h>
128 
129 VNET_DEFINE(int, zero_checksum_port) = 0;
130 #define	V_zero_checksum_port	VNET(zero_checksum_port)
131 SYSCTL_INT(_net_inet6_udp6, OID_AUTO, rfc6935_port, CTLFLAG_VNET | CTLFLAG_RW,
132     &VNET_NAME(zero_checksum_port), 0,
133     "Zero UDP checksum allowed for traffic to/from this port.");
134 
135 
136 /* netinet/udp_usrreqs.c */
137 pr_abort_t	udp_abort;
138 pr_disconnect_t	udp_disconnect;
139 pr_send_t	udp_send;
140 
141 /*
142  * UDP protocol implementation.
143  * Per RFC 768, August, 1980.
144  */
145 
146 static void		udp6_detach(struct socket *so);
147 
148 static int
149 udp6_append(struct inpcb *inp, struct mbuf *n, int off,
150     struct sockaddr_in6 *fromsa)
151 {
152 	struct socket *so;
153 	struct mbuf *opts = NULL, *tmp_opts;
154 	struct udpcb *up;
155 	bool filtered;
156 
157 	INP_LOCK_ASSERT(inp);
158 
159 	/*
160 	 * Engage the tunneling protocol.
161 	 */
162 	up = intoudpcb(inp);
163 	if (up->u_tun_func != NULL) {
164 		in_pcbref(inp);
165 		INP_RUNLOCK(inp);
166 		filtered = (*up->u_tun_func)(n, off, inp,
167 		    (struct sockaddr *)&fromsa[0], up->u_tun_ctx);
168 		INP_RLOCK(inp);
169 		if (filtered)
170 			return (in_pcbrele_rlocked(inp));
171 	}
172 #if defined(IPSEC) || defined(IPSEC_SUPPORT)
173 	/* Check AH/ESP integrity. */
174 	if (IPSEC_ENABLED(ipv6)) {
175 		if (IPSEC_CHECK_POLICY(ipv6, n, inp) != 0) {
176 			m_freem(n);
177 			return (0);
178 		}
179 	}
180 #endif /* IPSEC */
181 #ifdef MAC
182 	if (mac_inpcb_check_deliver(inp, n) != 0) {
183 		m_freem(n);
184 		return (0);
185 	}
186 #endif
187 	opts = NULL;
188 	if (inp->inp_flags & INP_CONTROLOPTS ||
189 	    inp->inp_socket->so_options & SO_TIMESTAMP)
190 		ip6_savecontrol(inp, n, &opts);
191 	if ((inp->inp_vflag & INP_IPV6) && (inp->inp_flags2 & INP_ORIGDSTADDR)) {
192 		tmp_opts = sbcreatecontrol(&fromsa[1],
193 		    sizeof(struct sockaddr_in6), IPV6_ORIGDSTADDR,
194 		    IPPROTO_IPV6, M_NOWAIT);
195                 if (tmp_opts) {
196                         if (opts) {
197                                 tmp_opts->m_next = opts;
198                                 opts = tmp_opts;
199                         } else
200                                 opts = tmp_opts;
201                 }
202 	}
203 	m_adj(n, off + sizeof(struct udphdr));
204 
205 	so = inp->inp_socket;
206 	SOCKBUF_LOCK(&so->so_rcv);
207 	if (sbappendaddr_locked(&so->so_rcv, (struct sockaddr *)&fromsa[0], n,
208 	    opts) == 0) {
209 		soroverflow_locked(so);
210 		m_freem(n);
211 		if (opts)
212 			m_freem(opts);
213 		UDPSTAT_INC(udps_fullsock);
214 	} else
215 		sorwakeup_locked(so);
216 	return (0);
217 }
218 
219 struct udp6_multi_match_ctx {
220 	struct ip6_hdr *ip6;
221 	struct udphdr *uh;
222 };
223 
224 static bool
225 udp6_multi_match(const struct inpcb *inp, void *v)
226 {
227 	struct udp6_multi_match_ctx *ctx = v;
228 
229 	if ((inp->inp_vflag & INP_IPV6) == 0)
230 		return(false);
231 	if (inp->inp_lport != ctx->uh->uh_dport)
232 		return(false);
233 	if (inp->inp_fport != 0 && inp->inp_fport != ctx->uh->uh_sport)
234 		return(false);
235 	if (!IN6_IS_ADDR_UNSPECIFIED(&inp->in6p_laddr) &&
236 	    !IN6_ARE_ADDR_EQUAL(&inp->in6p_laddr, &ctx->ip6->ip6_dst))
237 		return (false);
238 	if (!IN6_IS_ADDR_UNSPECIFIED(&inp->in6p_faddr) &&
239 	    (!IN6_ARE_ADDR_EQUAL(&inp->in6p_faddr, &ctx->ip6->ip6_src) ||
240 	    inp->inp_fport != ctx->uh->uh_sport))
241 		return (false);
242 
243 	return (true);
244 }
245 
246 static int
247 udp6_multi_input(struct mbuf *m, int off, int proto,
248     struct sockaddr_in6 *fromsa)
249 {
250 	struct udp6_multi_match_ctx ctx;
251 	struct inpcb_iterator inpi = INP_ITERATOR(udp_get_inpcbinfo(proto),
252 	    INPLOOKUP_RLOCKPCB, udp6_multi_match, &ctx);
253 	struct inpcb *inp;
254 	struct ip6_moptions *imo;
255 	struct mbuf *n;
256 	int appends = 0;
257 
258 	/*
259 	 * In the event that laddr should be set to the link-local
260 	 * address (this happens in RIPng), the multicast address
261 	 * specified in the received packet will not match laddr.  To
262 	 * handle this situation, matching is relaxed if the
263 	 * receiving interface is the same as one specified in the
264 	 * socket and if the destination multicast address matches
265 	 * one of the multicast groups specified in the socket.
266 	 */
267 
268 	/*
269 	 * KAME note: traditionally we dropped udpiphdr from mbuf
270 	 * here.  We need udphdr for IPsec processing so we do that
271 	 * later.
272 	 */
273 	ctx.ip6 = mtod(m, struct ip6_hdr *);
274 	ctx.uh = (struct udphdr *)((char *)ctx.ip6 + off);
275 	while ((inp = inp_next(&inpi)) != NULL) {
276 		INP_RLOCK_ASSERT(inp);
277 		/*
278 		 * XXXRW: Because we weren't holding either the inpcb
279 		 * or the hash lock when we checked for a match
280 		 * before, we should probably recheck now that the
281 		 * inpcb lock is (supposed to be) held.
282 		 */
283 		/*
284 		 * Handle socket delivery policy for any-source
285 		 * and source-specific multicast. [RFC3678]
286 		 */
287 		if ((imo = inp->in6p_moptions) != NULL) {
288 			struct sockaddr_in6	 mcaddr;
289 			int			 blocked;
290 
291 			bzero(&mcaddr, sizeof(struct sockaddr_in6));
292 			mcaddr.sin6_len = sizeof(struct sockaddr_in6);
293 			mcaddr.sin6_family = AF_INET6;
294 			mcaddr.sin6_addr = ctx.ip6->ip6_dst;
295 
296 			blocked = im6o_mc_filter(imo, m->m_pkthdr.rcvif,
297 				(struct sockaddr *)&mcaddr,
298 				(struct sockaddr *)&fromsa[0]);
299 			if (blocked != MCAST_PASS) {
300 				if (blocked == MCAST_NOTGMEMBER)
301 					IP6STAT_INC(ip6s_notmember);
302 				if (blocked == MCAST_NOTSMEMBER ||
303 				    blocked == MCAST_MUTED)
304 					UDPSTAT_INC(udps_filtermcast);
305 				continue;
306 			}
307 		}
308 		if ((n = m_copym(m, 0, M_COPYALL, M_NOWAIT)) != NULL) {
309 			if (proto == IPPROTO_UDPLITE)
310 				UDPLITE_PROBE(receive, NULL, inp, ctx.ip6,
311 				    inp, ctx.uh);
312 			else
313 				UDP_PROBE(receive, NULL, inp, ctx.ip6, inp,
314 				    ctx.uh);
315 			if (udp6_append(inp, n, off, fromsa)) {
316 				INP_RUNLOCK(inp);
317 				break;
318 			} else
319 				appends++;
320 		}
321 		/*
322 		 * Don't look for additional matches if this one does
323 		 * not have either the SO_REUSEPORT or SO_REUSEADDR
324 		 * socket options set.  This heuristic avoids
325 		 * searching through all pcbs in the common case of a
326 		 * non-shared port.  It assumes that an application
327 		 * will never clear these options after setting them.
328 		 */
329 		if ((inp->inp_socket->so_options &
330 		     (SO_REUSEPORT|SO_REUSEPORT_LB|SO_REUSEADDR)) == 0) {
331 			INP_RUNLOCK(inp);
332 			break;
333 		}
334 	}
335 	m_freem(m);
336 
337 	if (appends == 0) {
338 		/*
339 		 * No matching pcb found; discard datagram.  (No need
340 		 * to send an ICMP Port Unreachable for a broadcast
341 		 * or multicast datgram.)
342 		 */
343 		UDPSTAT_INC(udps_noport);
344 		UDPSTAT_INC(udps_noportmcast);
345 	}
346 
347 	return (IPPROTO_DONE);
348 }
349 
350 int
351 udp6_input(struct mbuf **mp, int *offp, int proto)
352 {
353 	struct mbuf *m = *mp;
354 	struct ip6_hdr *ip6;
355 	struct udphdr *uh;
356 	struct inpcb *inp;
357 	struct inpcbinfo *pcbinfo;
358 	struct udpcb *up;
359 	int off = *offp;
360 	int cscov_partial;
361 	int plen, ulen;
362 	struct sockaddr_in6 fromsa[2];
363 	struct m_tag *fwd_tag;
364 	uint16_t uh_sum;
365 	uint8_t nxt;
366 
367 	NET_EPOCH_ASSERT();
368 
369 	if (m->m_len < off + sizeof(struct udphdr)) {
370 		m = m_pullup(m, off + sizeof(struct udphdr));
371 		if (m == NULL) {
372 			IP6STAT_INC(ip6s_exthdrtoolong);
373 			*mp = NULL;
374 			return (IPPROTO_DONE);
375 		}
376 	}
377 	ip6 = mtod(m, struct ip6_hdr *);
378 	uh = (struct udphdr *)((caddr_t)ip6 + off);
379 
380 	UDPSTAT_INC(udps_ipackets);
381 
382 	/*
383 	 * Destination port of 0 is illegal, based on RFC768.
384 	 */
385 	if (uh->uh_dport == 0)
386 		goto badunlocked;
387 
388 	plen = ntohs(ip6->ip6_plen) - off + sizeof(*ip6);
389 	ulen = ntohs((u_short)uh->uh_ulen);
390 
391 	nxt = proto;
392 	cscov_partial = (nxt == IPPROTO_UDPLITE) ? 1 : 0;
393 	if (nxt == IPPROTO_UDPLITE) {
394 		/* Zero means checksum over the complete packet. */
395 		if (ulen == 0)
396 			ulen = plen;
397 		if (ulen == plen)
398 			cscov_partial = 0;
399 		if ((ulen < sizeof(struct udphdr)) || (ulen > plen)) {
400 			/* XXX: What is the right UDPLite MIB counter? */
401 			goto badunlocked;
402 		}
403 		if (uh->uh_sum == 0) {
404 			/* XXX: What is the right UDPLite MIB counter? */
405 			goto badunlocked;
406 		}
407 	} else {
408 		if ((ulen < sizeof(struct udphdr)) || (plen != ulen)) {
409 			UDPSTAT_INC(udps_badlen);
410 			goto badunlocked;
411 		}
412 		if (uh->uh_sum == 0) {
413 			UDPSTAT_INC(udps_nosum);
414 			/*
415 			 * dport 0 was rejected earlier so this is OK even if
416 			 * zero_checksum_port is 0 (which is its default value).
417 			 */
418 			if (ntohs(uh->uh_dport) == V_zero_checksum_port)
419 				goto skip_checksum;
420 			else
421 				goto badunlocked;
422 		}
423 	}
424 
425 	if ((m->m_pkthdr.csum_flags & CSUM_DATA_VALID_IPV6) &&
426 	    !cscov_partial) {
427 		if (m->m_pkthdr.csum_flags & CSUM_PSEUDO_HDR)
428 			uh_sum = m->m_pkthdr.csum_data;
429 		else
430 			uh_sum = in6_cksum_pseudo(ip6, ulen, nxt,
431 			    m->m_pkthdr.csum_data);
432 		uh_sum ^= 0xffff;
433 	} else
434 		uh_sum = in6_cksum_partial(m, nxt, off, plen, ulen);
435 
436 	if (uh_sum != 0) {
437 		UDPSTAT_INC(udps_badsum);
438 		goto badunlocked;
439 	}
440 
441 skip_checksum:
442 	/*
443 	 * Construct sockaddr format source address.
444 	 */
445 	init_sin6(&fromsa[0], m, 0);
446 	fromsa[0].sin6_port = uh->uh_sport;
447 	init_sin6(&fromsa[1], m, 1);
448 	fromsa[1].sin6_port = uh->uh_dport;
449 
450 	pcbinfo = udp_get_inpcbinfo(nxt);
451 	if (IN6_IS_ADDR_MULTICAST(&ip6->ip6_dst))  {
452 		*mp = NULL;
453 		return (udp6_multi_input(m, off, proto, fromsa));
454 	}
455 
456 	/*
457 	 * Locate pcb for datagram.
458 	 */
459 
460 	/*
461 	 * Grab info from PACKET_TAG_IPFORWARD tag prepended to the chain.
462 	 */
463 	if ((m->m_flags & M_IP6_NEXTHOP) &&
464 	    (fwd_tag = m_tag_find(m, PACKET_TAG_IPFORWARD, NULL)) != NULL) {
465 		struct sockaddr_in6 *next_hop6;
466 
467 		next_hop6 = (struct sockaddr_in6 *)(fwd_tag + 1);
468 
469 		/*
470 		 * Transparently forwarded. Pretend to be the destination.
471 		 * Already got one like this?
472 		 */
473 		inp = in6_pcblookup_mbuf(pcbinfo, &ip6->ip6_src,
474 		    uh->uh_sport, &ip6->ip6_dst, uh->uh_dport,
475 		    INPLOOKUP_RLOCKPCB, m->m_pkthdr.rcvif, m);
476 		if (!inp) {
477 			/*
478 			 * It's new.  Try to find the ambushing socket.
479 			 * Because we've rewritten the destination address,
480 			 * any hardware-generated hash is ignored.
481 			 */
482 			inp = in6_pcblookup(pcbinfo, &ip6->ip6_src,
483 			    uh->uh_sport, &next_hop6->sin6_addr,
484 			    next_hop6->sin6_port ? htons(next_hop6->sin6_port) :
485 			    uh->uh_dport, INPLOOKUP_WILDCARD |
486 			    INPLOOKUP_RLOCKPCB, m->m_pkthdr.rcvif);
487 		}
488 		/* Remove the tag from the packet. We don't need it anymore. */
489 		m_tag_delete(m, fwd_tag);
490 		m->m_flags &= ~M_IP6_NEXTHOP;
491 	} else
492 		inp = in6_pcblookup_mbuf(pcbinfo, &ip6->ip6_src,
493 		    uh->uh_sport, &ip6->ip6_dst, uh->uh_dport,
494 		    INPLOOKUP_WILDCARD | INPLOOKUP_RLOCKPCB,
495 		    m->m_pkthdr.rcvif, m);
496 	if (inp == NULL) {
497 		if (V_udp_log_in_vain) {
498 			char ip6bufs[INET6_ADDRSTRLEN];
499 			char ip6bufd[INET6_ADDRSTRLEN];
500 
501 			log(LOG_INFO,
502 			    "Connection attempt to UDP [%s]:%d from [%s]:%d\n",
503 			    ip6_sprintf(ip6bufd, &ip6->ip6_dst),
504 			    ntohs(uh->uh_dport),
505 			    ip6_sprintf(ip6bufs, &ip6->ip6_src),
506 			    ntohs(uh->uh_sport));
507 		}
508 		if (nxt == IPPROTO_UDPLITE)
509 			UDPLITE_PROBE(receive, NULL, NULL, ip6, NULL, uh);
510 		else
511 			UDP_PROBE(receive, NULL, NULL, ip6, NULL, uh);
512 		UDPSTAT_INC(udps_noport);
513 		if (m->m_flags & M_MCAST) {
514 			printf("UDP6: M_MCAST is set in a unicast packet.\n");
515 			UDPSTAT_INC(udps_noportmcast);
516 			goto badunlocked;
517 		}
518 		if (V_udp_blackhole && (V_udp_blackhole_local ||
519 		    !in6_localaddr(&ip6->ip6_src)))
520 			goto badunlocked;
521 		icmp6_error(m, ICMP6_DST_UNREACH, ICMP6_DST_UNREACH_NOPORT, 0);
522 		*mp = NULL;
523 		return (IPPROTO_DONE);
524 	}
525 	INP_RLOCK_ASSERT(inp);
526 	up = intoudpcb(inp);
527 	if (cscov_partial) {
528 		if (up->u_rxcslen == 0 || up->u_rxcslen > ulen) {
529 			INP_RUNLOCK(inp);
530 			m_freem(m);
531 			*mp = NULL;
532 			return (IPPROTO_DONE);
533 		}
534 	}
535 	if (nxt == IPPROTO_UDPLITE)
536 		UDPLITE_PROBE(receive, NULL, inp, ip6, inp, uh);
537 	else
538 		UDP_PROBE(receive, NULL, inp, ip6, inp, uh);
539 	if (udp6_append(inp, m, off, fromsa) == 0)
540 		INP_RUNLOCK(inp);
541 	*mp = NULL;
542 	return (IPPROTO_DONE);
543 
544 badunlocked:
545 	m_freem(m);
546 	*mp = NULL;
547 	return (IPPROTO_DONE);
548 }
549 
550 static void
551 udp6_common_ctlinput(int cmd, struct sockaddr *sa, void *d,
552     struct inpcbinfo *pcbinfo)
553 {
554 	struct udphdr uh;
555 	struct ip6_hdr *ip6;
556 	struct mbuf *m;
557 	int off = 0;
558 	struct ip6ctlparam *ip6cp = NULL;
559 	const struct sockaddr_in6 *sa6_src = NULL;
560 	void *cmdarg;
561 	struct inpcb *(*notify)(struct inpcb *, int) = udp_notify;
562 	struct udp_portonly {
563 		u_int16_t uh_sport;
564 		u_int16_t uh_dport;
565 	} *uhp;
566 
567 	if (sa->sa_family != AF_INET6 ||
568 	    sa->sa_len != sizeof(struct sockaddr_in6))
569 		return;
570 
571 	if ((unsigned)cmd >= PRC_NCMDS)
572 		return;
573 	if (PRC_IS_REDIRECT(cmd))
574 		notify = in6_rtchange, d = NULL;
575 	else if (cmd == PRC_HOSTDEAD)
576 		d = NULL;
577 	else if (inet6ctlerrmap[cmd] == 0)
578 		return;
579 
580 	/* if the parameter is from icmp6, decode it. */
581 	if (d != NULL) {
582 		ip6cp = (struct ip6ctlparam *)d;
583 		m = ip6cp->ip6c_m;
584 		ip6 = ip6cp->ip6c_ip6;
585 		off = ip6cp->ip6c_off;
586 		cmdarg = ip6cp->ip6c_cmdarg;
587 		sa6_src = ip6cp->ip6c_src;
588 	} else {
589 		m = NULL;
590 		ip6 = NULL;
591 		cmdarg = NULL;
592 		sa6_src = &sa6_any;
593 	}
594 
595 	if (ip6) {
596 		/*
597 		 * XXX: We assume that when IPV6 is non NULL,
598 		 * M and OFF are valid.
599 		 */
600 
601 		/* Check if we can safely examine src and dst ports. */
602 		if (m->m_pkthdr.len < off + sizeof(*uhp))
603 			return;
604 
605 		bzero(&uh, sizeof(uh));
606 		m_copydata(m, off, sizeof(*uhp), (caddr_t)&uh);
607 
608 		if (!PRC_IS_REDIRECT(cmd)) {
609 			/* Check to see if its tunneled */
610 			struct inpcb *inp;
611 			inp = in6_pcblookup_mbuf(pcbinfo, &ip6->ip6_dst,
612 			    uh.uh_dport, &ip6->ip6_src, uh.uh_sport,
613 			    INPLOOKUP_WILDCARD | INPLOOKUP_RLOCKPCB,
614 			    m->m_pkthdr.rcvif, m);
615 			if (inp != NULL) {
616 				struct udpcb *up;
617 
618 				up = intoudpcb(inp);
619 				if (up->u_icmp_func) {
620 					/* Yes it is. */
621 					INP_RUNLOCK(inp);
622 					(*up->u_icmp_func)(cmd, (struct sockaddr *)ip6cp->ip6c_src,
623 					      d, up->u_tun_ctx);
624 					return;
625 				} else {
626 					/* Can't find it. */
627 					INP_RUNLOCK(inp);
628 				}
629 			}
630 		}
631 		(void)in6_pcbnotify(pcbinfo, sa, uh.uh_dport,
632 		    (struct sockaddr *)ip6cp->ip6c_src, uh.uh_sport, cmd,
633 		    cmdarg, notify);
634 	} else
635 		(void)in6_pcbnotify(pcbinfo, sa, 0,
636 		    (const struct sockaddr *)sa6_src, 0, cmd, cmdarg, notify);
637 }
638 
639 void
640 udp6_ctlinput(int cmd, struct sockaddr *sa, void *d)
641 {
642 
643 	return (udp6_common_ctlinput(cmd, sa, d, &V_udbinfo));
644 }
645 
646 void
647 udplite6_ctlinput(int cmd, struct sockaddr *sa, void *d)
648 {
649 
650 	return (udp6_common_ctlinput(cmd, sa, d, &V_ulitecbinfo));
651 }
652 
653 static int
654 udp6_getcred(SYSCTL_HANDLER_ARGS)
655 {
656 	struct xucred xuc;
657 	struct sockaddr_in6 addrs[2];
658 	struct epoch_tracker et;
659 	struct inpcb *inp;
660 	int error;
661 
662 	error = priv_check(req->td, PRIV_NETINET_GETCRED);
663 	if (error)
664 		return (error);
665 
666 	if (req->newlen != sizeof(addrs))
667 		return (EINVAL);
668 	if (req->oldlen != sizeof(struct xucred))
669 		return (EINVAL);
670 	error = SYSCTL_IN(req, addrs, sizeof(addrs));
671 	if (error)
672 		return (error);
673 	if ((error = sa6_embedscope(&addrs[0], V_ip6_use_defzone)) != 0 ||
674 	    (error = sa6_embedscope(&addrs[1], V_ip6_use_defzone)) != 0) {
675 		return (error);
676 	}
677 	NET_EPOCH_ENTER(et);
678 	inp = in6_pcblookup(&V_udbinfo, &addrs[1].sin6_addr,
679 	    addrs[1].sin6_port, &addrs[0].sin6_addr, addrs[0].sin6_port,
680 	    INPLOOKUP_WILDCARD | INPLOOKUP_RLOCKPCB, NULL);
681 	NET_EPOCH_EXIT(et);
682 	if (inp != NULL) {
683 		INP_RLOCK_ASSERT(inp);
684 		if (inp->inp_socket == NULL)
685 			error = ENOENT;
686 		if (error == 0)
687 			error = cr_canseesocket(req->td->td_ucred,
688 			    inp->inp_socket);
689 		if (error == 0)
690 			cru2x(inp->inp_cred, &xuc);
691 		INP_RUNLOCK(inp);
692 	} else
693 		error = ENOENT;
694 	if (error == 0)
695 		error = SYSCTL_OUT(req, &xuc, sizeof(struct xucred));
696 	return (error);
697 }
698 
699 SYSCTL_PROC(_net_inet6_udp6, OID_AUTO, getcred,
700     CTLTYPE_OPAQUE | CTLFLAG_RW | CTLFLAG_MPSAFE,
701     0, 0, udp6_getcred, "S,xucred",
702     "Get the xucred of a UDP6 connection");
703 
704 static int
705 udp6_output(struct socket *so, int flags_arg, struct mbuf *m,
706     struct sockaddr *addr6, struct mbuf *control, struct thread *td)
707 {
708 	struct inpcb *inp;
709 	struct ip6_hdr *ip6;
710 	struct udphdr *udp6;
711 	struct in6_addr *laddr, *faddr, in6a;
712 	struct ip6_pktopts *optp, opt;
713 	struct sockaddr_in6 *sin6, tmp;
714 	struct epoch_tracker et;
715 	int cscov_partial, error, flags, hlen, scope_ambiguous;
716 	u_int32_t ulen, plen;
717 	uint16_t cscov;
718 	u_short fport;
719 	uint8_t nxt;
720 
721 	/* addr6 has been validated in udp6_send(). */
722 	sin6 = (struct sockaddr_in6 *)addr6;
723 
724 	/*
725 	 * In contrast to IPv4 we do not validate the max. packet length
726 	 * here due to IPv6 Jumbograms (RFC2675).
727 	 */
728 
729 	scope_ambiguous = 0;
730 	if (sin6) {
731 		/* Protect *addr6 from overwrites. */
732 		tmp = *sin6;
733 		sin6 = &tmp;
734 
735 		/*
736 		 * Application should provide a proper zone ID or the use of
737 		 * default zone IDs should be enabled.  Unfortunately, some
738 		 * applications do not behave as it should, so we need a
739 		 * workaround.  Even if an appropriate ID is not determined,
740 		 * we'll see if we can determine the outgoing interface.  If we
741 		 * can, determine the zone ID based on the interface below.
742 		 */
743 		if (sin6->sin6_scope_id == 0 && !V_ip6_use_defzone)
744 			scope_ambiguous = 1;
745 		if ((error = sa6_embedscope(sin6, V_ip6_use_defzone)) != 0) {
746 			if (control)
747 				m_freem(control);
748 			m_freem(m);
749 			return (error);
750 		}
751 	}
752 
753 	inp = sotoinpcb(so);
754 	KASSERT(inp != NULL, ("%s: inp == NULL", __func__));
755 	/*
756 	 * In the following cases we want a write lock on the inp for either
757 	 * local operations or for possible route cache updates in the IPv6
758 	 * output path:
759 	 * - on connected sockets (sin6 is NULL) for route cache updates,
760 	 * - when we are not bound to an address and source port (it is
761 	 *   in6_pcbsetport() which will require the write lock).
762 	 *
763 	 * We check the inp fields before actually locking the inp, so
764 	 * here exists a race, and we may WLOCK the inp and end with already
765 	 * bound one by other thread. This is fine.
766 	 */
767 	if (sin6 == NULL || (IN6_IS_ADDR_UNSPECIFIED(&inp->in6p_laddr) &&
768 	    inp->inp_lport == 0))
769 		INP_WLOCK(inp);
770 	else
771 		INP_RLOCK(inp);
772 
773 	nxt = (inp->inp_socket->so_proto->pr_protocol == IPPROTO_UDP) ?
774 	    IPPROTO_UDP : IPPROTO_UDPLITE;
775 
776 #ifdef INET
777 	if ((inp->inp_flags & IN6P_IPV6_V6ONLY) == 0) {
778 		int hasv4addr;
779 
780 		if (sin6 == NULL)
781 			hasv4addr = (inp->inp_vflag & INP_IPV4);
782 		else
783 			hasv4addr = IN6_IS_ADDR_V4MAPPED(&sin6->sin6_addr)
784 			    ? 1 : 0;
785 		if (hasv4addr) {
786 			/*
787 			 * XXXRW: We release UDP-layer locks before calling
788 			 * udp_send() in order to avoid recursion.  However,
789 			 * this does mean there is a short window where inp's
790 			 * fields are unstable.  Could this lead to a
791 			 * potential race in which the factors causing us to
792 			 * select the UDPv4 output routine are invalidated?
793 			 */
794 			INP_UNLOCK(inp);
795 			if (sin6)
796 				in6_sin6_2_sin_in_sock((struct sockaddr *)sin6);
797 			/* addr will just be freed in sendit(). */
798 			return (udp_send(so, flags_arg | PRUS_IPV6, m,
799 			    (struct sockaddr *)sin6, control, td));
800 		}
801 	} else
802 #endif
803 	if (sin6 && IN6_IS_ADDR_V4MAPPED(&sin6->sin6_addr)) {
804 		/*
805 		 * Given this is either an IPv6-only socket or no INET is
806 		 * supported we will fail the send if the given destination
807 		 * address is a v4mapped address.
808 		 *
809 		 * XXXGL: do we leak m and control?
810 		 */
811 		INP_UNLOCK(inp);
812 		return (EINVAL);
813 	}
814 
815 	NET_EPOCH_ENTER(et);
816 	if (control) {
817 		if ((error = ip6_setpktopts(control, &opt,
818 		    inp->in6p_outputopts, td->td_ucred, nxt)) != 0) {
819 			goto release;
820 		}
821 		optp = &opt;
822 	} else
823 		optp = inp->in6p_outputopts;
824 
825 	if (sin6) {
826 		/*
827 		 * Since we saw no essential reason for calling in_pcbconnect,
828 		 * we get rid of such kind of logic, and call in6_selectsrc
829 		 * and in6_pcbsetport in order to fill in the local address
830 		 * and the local port.
831 		 */
832 		if (sin6->sin6_port == 0) {
833 			error = EADDRNOTAVAIL;
834 			goto release;
835 		}
836 
837 		if (!IN6_IS_ADDR_UNSPECIFIED(&inp->in6p_faddr)) {
838 			/* how about ::ffff:0.0.0.0 case? */
839 			error = EISCONN;
840 			goto release;
841 		}
842 
843 		/*
844 		 * Given we handle the v4mapped case in the INET block above
845 		 * assert here that it must not happen anymore.
846 		 */
847 		KASSERT(!IN6_IS_ADDR_V4MAPPED(&sin6->sin6_addr),
848 		    ("%s: sin6(%p)->sin6_addr is v4mapped which we "
849 		    "should have handled.", __func__, sin6));
850 
851 		/* This only requires read-locking. */
852 		error = in6_selectsrc_socket(sin6, optp, inp,
853 		    td->td_ucred, scope_ambiguous, &in6a, NULL);
854 		if (error)
855 			goto release;
856 		laddr = &in6a;
857 
858 		if (inp->inp_lport == 0) {
859 			struct inpcbinfo *pcbinfo;
860 
861 			INP_WLOCK_ASSERT(inp);
862 
863 			pcbinfo = udp_get_inpcbinfo(so->so_proto->pr_protocol);
864 			INP_HASH_WLOCK(pcbinfo);
865 			error = in6_pcbsetport(laddr, inp, td->td_ucred);
866 			INP_HASH_WUNLOCK(pcbinfo);
867 			if (error != 0) {
868 				/* Undo an address bind that may have occurred. */
869 				inp->in6p_laddr = in6addr_any;
870 				goto release;
871 			}
872 		}
873 		faddr = &sin6->sin6_addr;
874 		fport = sin6->sin6_port; /* allow 0 port */
875 
876 	} else {
877 		if (IN6_IS_ADDR_UNSPECIFIED(&inp->in6p_faddr)) {
878 			error = ENOTCONN;
879 			goto release;
880 		}
881 		laddr = &inp->in6p_laddr;
882 		faddr = &inp->in6p_faddr;
883 		fport = inp->inp_fport;
884 	}
885 
886 	ulen = m->m_pkthdr.len;
887 	plen = sizeof(struct udphdr) + ulen;
888 	hlen = sizeof(struct ip6_hdr);
889 
890 	/*
891 	 * Calculate data length and get a mbuf
892 	 * for UDP and IP6 headers.
893 	 */
894 	M_PREPEND(m, hlen + sizeof(struct udphdr), M_NOWAIT);
895 	if (m == NULL) {
896 		error = ENOBUFS;
897 		goto release;
898 	}
899 
900 	/*
901 	 * Stuff checksum and output datagram.
902 	 */
903 	cscov = cscov_partial = 0;
904 	udp6 = (struct udphdr *)(mtod(m, caddr_t) + hlen);
905 	udp6->uh_sport = inp->inp_lport; /* lport is always set in the PCB */
906 	udp6->uh_dport = fport;
907 	if (nxt == IPPROTO_UDPLITE) {
908 		struct udpcb *up;
909 
910 		up = intoudpcb(inp);
911 		cscov = up->u_txcslen;
912 		if (cscov >= plen)
913 			cscov = 0;
914 		udp6->uh_ulen = htons(cscov);
915 		/*
916 		 * For UDP-Lite, checksum coverage length of zero means
917 		 * the entire UDPLite packet is covered by the checksum.
918 		 */
919 		cscov_partial = (cscov == 0) ? 0 : 1;
920 	} else if (plen <= 0xffff)
921 		udp6->uh_ulen = htons((u_short)plen);
922 	else
923 		udp6->uh_ulen = 0;
924 	udp6->uh_sum = 0;
925 
926 	ip6 = mtod(m, struct ip6_hdr *);
927 	ip6->ip6_flow	= inp->inp_flow & IPV6_FLOWINFO_MASK;
928 	ip6->ip6_vfc	&= ~IPV6_VERSION_MASK;
929 	ip6->ip6_vfc	|= IPV6_VERSION;
930 	ip6->ip6_plen	= htons((u_short)plen);
931 	ip6->ip6_nxt	= nxt;
932 	ip6->ip6_hlim	= in6_selecthlim(inp, NULL);
933 	ip6->ip6_src	= *laddr;
934 	ip6->ip6_dst	= *faddr;
935 
936 #ifdef MAC
937 	mac_inpcb_create_mbuf(inp, m);
938 #endif
939 
940 	if (cscov_partial) {
941 		if ((udp6->uh_sum = in6_cksum_partial(m, nxt,
942 		    sizeof(struct ip6_hdr), plen, cscov)) == 0)
943 			udp6->uh_sum = 0xffff;
944 	} else {
945 		udp6->uh_sum = in6_cksum_pseudo(ip6, plen, nxt, 0);
946 		m->m_pkthdr.csum_flags = CSUM_UDP_IPV6;
947 		m->m_pkthdr.csum_data = offsetof(struct udphdr, uh_sum);
948 	}
949 
950 	flags = 0;
951 #if defined(ROUTE_MPATH) || defined(RSS)
952 	if (CALC_FLOWID_OUTBOUND_SENDTO) {
953 		uint32_t hash_type, hash_val;
954 		uint8_t pr;
955 
956 		pr = inp->inp_socket->so_proto->pr_protocol;
957 
958 		hash_val = fib6_calc_packet_hash(laddr, faddr,
959 		    inp->inp_lport, fport, pr, &hash_type);
960 		m->m_pkthdr.flowid = hash_val;
961 		M_HASHTYPE_SET(m, hash_type);
962 	}
963 	/* do not use inp flowid */
964 	flags |= IP_NODEFAULTFLOWID;
965 #endif
966 
967 	UDPSTAT_INC(udps_opackets);
968 	if (nxt == IPPROTO_UDPLITE)
969 		UDPLITE_PROBE(send, NULL, inp, ip6, inp, udp6);
970 	else
971 		UDP_PROBE(send, NULL, inp, ip6, inp, udp6);
972 	error = ip6_output(m, optp,
973 	    INP_WLOCKED(inp) ? &inp->inp_route6 : NULL, flags,
974 	    inp->in6p_moptions, NULL, inp);
975 	INP_UNLOCK(inp);
976 	NET_EPOCH_EXIT(et);
977 
978 	if (control) {
979 		ip6_clearpktopts(&opt, -1);
980 		m_freem(control);
981 	}
982 	return (error);
983 
984 release:
985 	INP_UNLOCK(inp);
986 	NET_EPOCH_EXIT(et);
987 	if (control) {
988 		ip6_clearpktopts(&opt, -1);
989 		m_freem(control);
990 	}
991 	m_freem(m);
992 
993 	return (error);
994 }
995 
996 static void
997 udp6_abort(struct socket *so)
998 {
999 	struct inpcb *inp;
1000 	struct inpcbinfo *pcbinfo;
1001 
1002 	pcbinfo = udp_get_inpcbinfo(so->so_proto->pr_protocol);
1003 	inp = sotoinpcb(so);
1004 	KASSERT(inp != NULL, ("udp6_abort: inp == NULL"));
1005 
1006 	INP_WLOCK(inp);
1007 #ifdef INET
1008 	if (inp->inp_vflag & INP_IPV4) {
1009 		INP_WUNLOCK(inp);
1010 		udp_abort(so);
1011 		return;
1012 	}
1013 #endif
1014 
1015 	if (!IN6_IS_ADDR_UNSPECIFIED(&inp->in6p_faddr)) {
1016 		INP_HASH_WLOCK(pcbinfo);
1017 		in6_pcbdisconnect(inp);
1018 		inp->in6p_laddr = in6addr_any;
1019 		INP_HASH_WUNLOCK(pcbinfo);
1020 		soisdisconnected(so);
1021 	}
1022 	INP_WUNLOCK(inp);
1023 }
1024 
1025 static int
1026 udp6_attach(struct socket *so, int proto, struct thread *td)
1027 {
1028 	struct inpcb *inp;
1029 	struct inpcbinfo *pcbinfo;
1030 	int error;
1031 
1032 	pcbinfo = udp_get_inpcbinfo(so->so_proto->pr_protocol);
1033 	inp = sotoinpcb(so);
1034 	KASSERT(inp == NULL, ("udp6_attach: inp != NULL"));
1035 
1036 	if (so->so_snd.sb_hiwat == 0 || so->so_rcv.sb_hiwat == 0) {
1037 		error = soreserve(so, udp_sendspace, udp_recvspace);
1038 		if (error)
1039 			return (error);
1040 	}
1041 	error = in_pcballoc(so, pcbinfo);
1042 	if (error)
1043 		return (error);
1044 	inp = (struct inpcb *)so->so_pcb;
1045 	inp->in6p_cksum = -1;	/* just to be sure */
1046 	/*
1047 	 * XXX: ugly!!
1048 	 * IPv4 TTL initialization is necessary for an IPv6 socket as well,
1049 	 * because the socket may be bound to an IPv6 wildcard address,
1050 	 * which may match an IPv4-mapped IPv6 address.
1051 	 */
1052 	inp->inp_ip_ttl = V_ip_defttl;
1053 
1054 	error = udp_newudpcb(inp);
1055 	if (error) {
1056 		in_pcbdetach(inp);
1057 		in_pcbfree(inp);
1058 		return (error);
1059 	}
1060 	INP_WUNLOCK(inp);
1061 	return (0);
1062 }
1063 
1064 static int
1065 udp6_bind(struct socket *so, struct sockaddr *nam, struct thread *td)
1066 {
1067 	struct inpcb *inp;
1068 	struct inpcbinfo *pcbinfo;
1069 	int error;
1070 	u_char vflagsav;
1071 
1072 	pcbinfo = udp_get_inpcbinfo(so->so_proto->pr_protocol);
1073 	inp = sotoinpcb(so);
1074 	KASSERT(inp != NULL, ("udp6_bind: inp == NULL"));
1075 
1076 	if (nam->sa_family != AF_INET6)
1077 		return (EAFNOSUPPORT);
1078 	if (nam->sa_len != sizeof(struct sockaddr_in6))
1079 		return (EINVAL);
1080 
1081 	INP_WLOCK(inp);
1082 	INP_HASH_WLOCK(pcbinfo);
1083 	vflagsav = inp->inp_vflag;
1084 	inp->inp_vflag &= ~INP_IPV4;
1085 	inp->inp_vflag |= INP_IPV6;
1086 	if ((inp->inp_flags & IN6P_IPV6_V6ONLY) == 0) {
1087 		struct sockaddr_in6 *sin6_p;
1088 
1089 		sin6_p = (struct sockaddr_in6 *)nam;
1090 
1091 		if (IN6_IS_ADDR_UNSPECIFIED(&sin6_p->sin6_addr))
1092 			inp->inp_vflag |= INP_IPV4;
1093 #ifdef INET
1094 		else if (IN6_IS_ADDR_V4MAPPED(&sin6_p->sin6_addr)) {
1095 			struct sockaddr_in sin;
1096 
1097 			in6_sin6_2_sin(&sin, sin6_p);
1098 			inp->inp_vflag |= INP_IPV4;
1099 			inp->inp_vflag &= ~INP_IPV6;
1100 			error = in_pcbbind(inp, (struct sockaddr *)&sin,
1101 			    td->td_ucred);
1102 			goto out;
1103 		}
1104 #endif
1105 	}
1106 
1107 	error = in6_pcbbind(inp, nam, td->td_ucred);
1108 #ifdef INET
1109 out:
1110 #endif
1111 	if (error != 0)
1112 		inp->inp_vflag = vflagsav;
1113 	INP_HASH_WUNLOCK(pcbinfo);
1114 	INP_WUNLOCK(inp);
1115 	return (error);
1116 }
1117 
1118 static void
1119 udp6_close(struct socket *so)
1120 {
1121 	struct inpcb *inp;
1122 	struct inpcbinfo *pcbinfo;
1123 
1124 	pcbinfo = udp_get_inpcbinfo(so->so_proto->pr_protocol);
1125 	inp = sotoinpcb(so);
1126 	KASSERT(inp != NULL, ("udp6_close: inp == NULL"));
1127 
1128 	INP_WLOCK(inp);
1129 #ifdef INET
1130 	if (inp->inp_vflag & INP_IPV4) {
1131 		INP_WUNLOCK(inp);
1132 		(void)udp_disconnect(so);
1133 		return;
1134 	}
1135 #endif
1136 	if (!IN6_IS_ADDR_UNSPECIFIED(&inp->in6p_faddr)) {
1137 		INP_HASH_WLOCK(pcbinfo);
1138 		in6_pcbdisconnect(inp);
1139 		inp->in6p_laddr = in6addr_any;
1140 		INP_HASH_WUNLOCK(pcbinfo);
1141 		soisdisconnected(so);
1142 	}
1143 	INP_WUNLOCK(inp);
1144 }
1145 
1146 static int
1147 udp6_connect(struct socket *so, struct sockaddr *nam, struct thread *td)
1148 {
1149 #ifdef INET
1150 	struct epoch_tracker et;
1151 #endif
1152 	struct inpcb *inp;
1153 	struct inpcbinfo *pcbinfo;
1154 	struct sockaddr_in6 *sin6;
1155 	int error;
1156 	u_char vflagsav;
1157 
1158 	pcbinfo = udp_get_inpcbinfo(so->so_proto->pr_protocol);
1159 	inp = sotoinpcb(so);
1160 	KASSERT(inp != NULL, ("udp6_connect: inp == NULL"));
1161 
1162 	sin6 = (struct sockaddr_in6 *)nam;
1163 	if (sin6->sin6_family != AF_INET6)
1164 		return (EAFNOSUPPORT);
1165 	if (sin6->sin6_len != sizeof(*sin6))
1166 		return (EINVAL);
1167 
1168 	/*
1169 	 * XXXRW: Need to clarify locking of v4/v6 flags.
1170 	 */
1171 	INP_WLOCK(inp);
1172 #ifdef INET
1173 	if (IN6_IS_ADDR_V4MAPPED(&sin6->sin6_addr)) {
1174 		struct sockaddr_in sin;
1175 
1176 		if ((inp->inp_flags & IN6P_IPV6_V6ONLY) != 0) {
1177 			error = EINVAL;
1178 			goto out;
1179 		}
1180 		if ((inp->inp_vflag & INP_IPV4) == 0) {
1181 			error = EAFNOSUPPORT;
1182 			goto out;
1183 		}
1184 		if (inp->inp_faddr.s_addr != INADDR_ANY) {
1185 			error = EISCONN;
1186 			goto out;
1187 		}
1188 		in6_sin6_2_sin(&sin, sin6);
1189 		error = prison_remote_ip4(td->td_ucred, &sin.sin_addr);
1190 		if (error != 0)
1191 			goto out;
1192 		vflagsav = inp->inp_vflag;
1193 		inp->inp_vflag |= INP_IPV4;
1194 		inp->inp_vflag &= ~INP_IPV6;
1195 		NET_EPOCH_ENTER(et);
1196 		INP_HASH_WLOCK(pcbinfo);
1197 		error = in_pcbconnect(inp, (struct sockaddr *)&sin,
1198 		    td->td_ucred, true);
1199 		INP_HASH_WUNLOCK(pcbinfo);
1200 		NET_EPOCH_EXIT(et);
1201 		/*
1202 		 * If connect succeeds, mark socket as connected. If
1203 		 * connect fails and socket is unbound, reset inp_vflag
1204 		 * field.
1205 		 */
1206 		if (error == 0)
1207 			soisconnected(so);
1208 		else if (inp->inp_laddr.s_addr == INADDR_ANY &&
1209 		    inp->inp_lport == 0)
1210 			inp->inp_vflag = vflagsav;
1211 		goto out;
1212 	} else {
1213 		if ((inp->inp_vflag & INP_IPV6) == 0) {
1214 			error = EAFNOSUPPORT;
1215 			goto out;
1216 		}
1217 	}
1218 #endif
1219 	if (!IN6_IS_ADDR_UNSPECIFIED(&inp->in6p_faddr)) {
1220 		error = EISCONN;
1221 		goto out;
1222 	}
1223 	error = prison_remote_ip6(td->td_ucred, &sin6->sin6_addr);
1224 	if (error != 0)
1225 		goto out;
1226 	vflagsav = inp->inp_vflag;
1227 	inp->inp_vflag &= ~INP_IPV4;
1228 	inp->inp_vflag |= INP_IPV6;
1229 	INP_HASH_WLOCK(pcbinfo);
1230 	error = in6_pcbconnect(inp, nam, td->td_ucred);
1231 	INP_HASH_WUNLOCK(pcbinfo);
1232 	/*
1233 	 * If connect succeeds, mark socket as connected. If
1234 	 * connect fails and socket is unbound, reset inp_vflag
1235 	 * field.
1236 	 */
1237 	if (error == 0)
1238 		soisconnected(so);
1239 	else if (IN6_IS_ADDR_UNSPECIFIED(&inp->in6p_laddr) &&
1240 	    inp->inp_lport == 0)
1241 		inp->inp_vflag = vflagsav;
1242 out:
1243 	INP_WUNLOCK(inp);
1244 	return (error);
1245 }
1246 
1247 static void
1248 udp6_detach(struct socket *so)
1249 {
1250 	struct inpcb *inp;
1251 	struct udpcb *up;
1252 
1253 	inp = sotoinpcb(so);
1254 	KASSERT(inp != NULL, ("udp6_detach: inp == NULL"));
1255 
1256 	INP_WLOCK(inp);
1257 	up = intoudpcb(inp);
1258 	KASSERT(up != NULL, ("%s: up == NULL", __func__));
1259 	in_pcbdetach(inp);
1260 	in_pcbfree(inp);
1261 	udp_discardcb(up);
1262 }
1263 
1264 static int
1265 udp6_disconnect(struct socket *so)
1266 {
1267 	struct inpcb *inp;
1268 	struct inpcbinfo *pcbinfo;
1269 
1270 	pcbinfo = udp_get_inpcbinfo(so->so_proto->pr_protocol);
1271 	inp = sotoinpcb(so);
1272 	KASSERT(inp != NULL, ("udp6_disconnect: inp == NULL"));
1273 
1274 	INP_WLOCK(inp);
1275 #ifdef INET
1276 	if (inp->inp_vflag & INP_IPV4) {
1277 		INP_WUNLOCK(inp);
1278 		(void)udp_disconnect(so);
1279 		return (0);
1280 	}
1281 #endif
1282 
1283 	if (IN6_IS_ADDR_UNSPECIFIED(&inp->in6p_faddr)) {
1284 		INP_WUNLOCK(inp);
1285 		return (ENOTCONN);
1286 	}
1287 
1288 	INP_HASH_WLOCK(pcbinfo);
1289 	in6_pcbdisconnect(inp);
1290 	inp->in6p_laddr = in6addr_any;
1291 	INP_HASH_WUNLOCK(pcbinfo);
1292 	SOCK_LOCK(so);
1293 	so->so_state &= ~SS_ISCONNECTED;		/* XXX */
1294 	SOCK_UNLOCK(so);
1295 	INP_WUNLOCK(inp);
1296 	return (0);
1297 }
1298 
1299 static int
1300 udp6_send(struct socket *so, int flags, struct mbuf *m,
1301     struct sockaddr *addr, struct mbuf *control, struct thread *td)
1302 {
1303 	int error;
1304 
1305 	if (addr) {
1306 		if (addr->sa_len != sizeof(struct sockaddr_in6)) {
1307 			error = EINVAL;
1308 			goto bad;
1309 		}
1310 		if (addr->sa_family != AF_INET6) {
1311 			error = EAFNOSUPPORT;
1312 			goto bad;
1313 		}
1314 	}
1315 
1316 	return (udp6_output(so, flags, m, addr, control, td));
1317 
1318 bad:
1319 	if (control)
1320 		m_freem(control);
1321 	m_freem(m);
1322 	return (error);
1323 }
1324 
1325 #define	UDP6_PROTOSW							\
1326 	.pr_type =		SOCK_DGRAM,				\
1327 	.pr_flags =		PR_ATOMIC|PR_ADDR|PR_CAPATTACH,		\
1328 	.pr_ctloutput =		ip6_ctloutput,				\
1329 	.pr_abort =		udp6_abort,				\
1330 	.pr_attach =		udp6_attach,				\
1331 	.pr_bind =		udp6_bind,				\
1332 	.pr_connect =		udp6_connect,				\
1333 	.pr_control =		in6_control,				\
1334 	.pr_detach =		udp6_detach,				\
1335 	.pr_disconnect =	udp6_disconnect,			\
1336 	.pr_peeraddr =		in6_mapped_peeraddr,			\
1337 	.pr_send =		udp6_send,				\
1338 	.pr_shutdown =		udp_shutdown,				\
1339 	.pr_sockaddr =		in6_mapped_sockaddr,			\
1340 	.pr_soreceive =		soreceive_dgram,			\
1341 	.pr_sosend =		sosend_dgram,				\
1342 	.pr_sosetlabel =	in_pcbsosetlabel,			\
1343 	.pr_close =		udp6_close
1344 
1345 struct protosw udp6_protosw = {
1346 	.pr_protocol =		IPPROTO_UDP,
1347 	UDP6_PROTOSW
1348 };
1349 
1350 struct protosw udplite6_protosw = {
1351 	.pr_protocol =		IPPROTO_UDPLITE,
1352 	UDP6_PROTOSW
1353 };
1354 
1355 static void
1356 udp6_init(void *arg __unused)
1357 {
1358 
1359 	IP6PROTO_REGISTER(IPPROTO_UDP, udp6_input, udp6_ctlinput);
1360 	IP6PROTO_REGISTER(IPPROTO_UDPLITE, udp6_input, udplite6_ctlinput);
1361 }
1362 SYSINIT(udp6_init, SI_SUB_PROTO_DOMAIN, SI_ORDER_THIRD, udp6_init, NULL);
1363