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