xref: /freebsd/sys/netinet/udp_usrreq.c (revision 4f8f43b06ed07e96a250855488cc531799d5b78f)
1 /*-
2  * SPDX-License-Identifier: BSD-3-Clause
3  *
4  * Copyright (c) 1982, 1986, 1988, 1990, 1993, 1995
5  *	The Regents of the University of California.
6  * Copyright (c) 2008 Robert N. M. Watson
7  * Copyright (c) 2010-2011 Juniper Networks, Inc.
8  * Copyright (c) 2014 Kevin Lo
9  * All rights reserved.
10  *
11  * Portions of this software were developed by Robert N. M. Watson under
12  * contract to Juniper Networks, Inc.
13  *
14  * Redistribution and use in source and binary forms, with or without
15  * modification, are permitted provided that the following conditions
16  * are met:
17  * 1. Redistributions of source code must retain the above copyright
18  *    notice, this list of conditions and the following disclaimer.
19  * 2. Redistributions in binary form must reproduce the above copyright
20  *    notice, this list of conditions and the following disclaimer in the
21  *    documentation and/or other materials provided with the distribution.
22  * 3. Neither the name of the University nor the names of its contributors
23  *    may be used to endorse or promote products derived from this software
24  *    without specific prior written permission.
25  *
26  * THIS SOFTWARE IS PROVIDED BY THE REGENTS AND CONTRIBUTORS ``AS IS'' AND
27  * ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
28  * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE
29  * ARE DISCLAIMED.  IN NO EVENT SHALL THE REGENTS OR CONTRIBUTORS BE LIABLE
30  * FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL
31  * DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS
32  * OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION)
33  * HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT
34  * LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY
35  * OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF
36  * SUCH DAMAGE.
37  *
38  *	@(#)udp_usrreq.c	8.6 (Berkeley) 5/23/95
39  */
40 
41 #include <sys/cdefs.h>
42 #include "opt_inet.h"
43 #include "opt_inet6.h"
44 #include "opt_ipsec.h"
45 #include "opt_route.h"
46 #include "opt_rss.h"
47 
48 #include <sys/param.h>
49 #include <sys/domain.h>
50 #include <sys/eventhandler.h>
51 #include <sys/jail.h>
52 #include <sys/kernel.h>
53 #include <sys/lock.h>
54 #include <sys/malloc.h>
55 #include <sys/mbuf.h>
56 #include <sys/priv.h>
57 #include <sys/proc.h>
58 #include <sys/protosw.h>
59 #include <sys/sdt.h>
60 #include <sys/signalvar.h>
61 #include <sys/socket.h>
62 #include <sys/socketvar.h>
63 #include <sys/sx.h>
64 #include <sys/sysctl.h>
65 #include <sys/syslog.h>
66 #include <sys/systm.h>
67 
68 #include <vm/uma.h>
69 
70 #include <net/if.h>
71 #include <net/if_var.h>
72 #include <net/route.h>
73 #include <net/route/nhop.h>
74 #include <net/rss_config.h>
75 
76 #include <netinet/in.h>
77 #include <netinet/in_kdtrace.h>
78 #include <netinet/in_fib.h>
79 #include <netinet/in_pcb.h>
80 #include <netinet/in_systm.h>
81 #include <netinet/in_var.h>
82 #include <netinet/ip.h>
83 #ifdef INET6
84 #include <netinet/ip6.h>
85 #endif
86 #include <netinet/ip_icmp.h>
87 #include <netinet/icmp_var.h>
88 #include <netinet/ip_var.h>
89 #include <netinet/ip_options.h>
90 #ifdef INET6
91 #include <netinet6/ip6_var.h>
92 #endif
93 #include <netinet/udp.h>
94 #include <netinet/udp_var.h>
95 #include <netinet/udplite.h>
96 #include <netinet/in_rss.h>
97 
98 #include <netipsec/ipsec_support.h>
99 
100 #include <machine/in_cksum.h>
101 
102 #include <security/mac/mac_framework.h>
103 
104 /*
105  * UDP and UDP-Lite protocols implementation.
106  * Per RFC 768, August, 1980.
107  * Per RFC 3828, July, 2004.
108  */
109 
110 /*
111  * BSD 4.2 defaulted the udp checksum to be off.  Turning off udp checksums
112  * removes the only data integrity mechanism for packets and malformed
113  * packets that would otherwise be discarded due to bad checksums, and may
114  * cause problems (especially for NFS data blocks).
115  */
116 VNET_DEFINE(int, udp_cksum) = 1;
117 SYSCTL_INT(_net_inet_udp, UDPCTL_CHECKSUM, checksum, CTLFLAG_VNET | CTLFLAG_RW,
118     &VNET_NAME(udp_cksum), 0, "compute udp checksum");
119 
120 VNET_DEFINE(int, udp_log_in_vain) = 0;
121 SYSCTL_INT(_net_inet_udp, OID_AUTO, log_in_vain, CTLFLAG_VNET | CTLFLAG_RW,
122     &VNET_NAME(udp_log_in_vain), 0, "Log all incoming UDP packets");
123 
124 VNET_DEFINE(int, udp_blackhole) = 0;
125 SYSCTL_INT(_net_inet_udp, OID_AUTO, blackhole, CTLFLAG_VNET | CTLFLAG_RW,
126     &VNET_NAME(udp_blackhole), 0,
127     "Do not send port unreachables for refused connects");
128 VNET_DEFINE(bool, udp_blackhole_local) = false;
129 SYSCTL_BOOL(_net_inet_udp, OID_AUTO, blackhole_local, CTLFLAG_VNET |
130     CTLFLAG_RW, &VNET_NAME(udp_blackhole_local), false,
131     "Enforce net.inet.udp.blackhole for locally originated packets");
132 
133 u_long	udp_sendspace = 9216;		/* really max datagram size */
134 SYSCTL_ULONG(_net_inet_udp, UDPCTL_MAXDGRAM, maxdgram, CTLFLAG_RW,
135     &udp_sendspace, 0, "Maximum outgoing UDP datagram size");
136 
137 u_long	udp_recvspace = 40 * (1024 +
138 #ifdef INET6
139 				      sizeof(struct sockaddr_in6)
140 #else
141 				      sizeof(struct sockaddr_in)
142 #endif
143 				      );	/* 40 1K datagrams */
144 
145 SYSCTL_ULONG(_net_inet_udp, UDPCTL_RECVSPACE, recvspace, CTLFLAG_RW,
146     &udp_recvspace, 0, "Maximum space for incoming UDP datagrams");
147 
148 VNET_DEFINE(struct inpcbinfo, udbinfo);
149 VNET_DEFINE(struct inpcbinfo, ulitecbinfo);
150 
151 #ifndef UDBHASHSIZE
152 #define	UDBHASHSIZE	128
153 #endif
154 
155 VNET_PCPUSTAT_DEFINE(struct udpstat, udpstat);		/* from udp_var.h */
156 VNET_PCPUSTAT_SYSINIT(udpstat);
157 SYSCTL_VNET_PCPUSTAT(_net_inet_udp, UDPCTL_STATS, stats, struct udpstat,
158     udpstat, "UDP statistics (struct udpstat, netinet/udp_var.h)");
159 
160 #ifdef VIMAGE
161 VNET_PCPUSTAT_SYSUNINIT(udpstat);
162 #endif /* VIMAGE */
163 #ifdef INET
164 static void	udp_detach(struct socket *so);
165 #endif
166 
167 INPCBSTORAGE_DEFINE(udpcbstor, udpcb, "udpinp", "udp_inpcb", "udp", "udphash");
168 INPCBSTORAGE_DEFINE(udplitecbstor, udpcb, "udpliteinp", "udplite_inpcb",
169     "udplite", "udplitehash");
170 
171 static void
172 udp_vnet_init(void *arg __unused)
173 {
174 
175 	/*
176 	 * For now default to 2-tuple UDP hashing - until the fragment
177 	 * reassembly code can also update the flowid.
178 	 *
179 	 * Once we can calculate the flowid that way and re-establish
180 	 * a 4-tuple, flip this to 4-tuple.
181 	 */
182 	in_pcbinfo_init(&V_udbinfo, &udpcbstor, UDBHASHSIZE, UDBHASHSIZE);
183 	/* Additional pcbinfo for UDP-Lite */
184 	in_pcbinfo_init(&V_ulitecbinfo, &udplitecbstor, UDBHASHSIZE,
185 	    UDBHASHSIZE);
186 }
187 VNET_SYSINIT(udp_vnet_init, SI_SUB_PROTO_DOMAIN, SI_ORDER_FOURTH,
188     udp_vnet_init, NULL);
189 
190 /*
191  * Kernel module interface for updating udpstat.  The argument is an index
192  * into udpstat treated as an array of u_long.  While this encodes the
193  * general layout of udpstat into the caller, it doesn't encode its location,
194  * so that future changes to add, for example, per-CPU stats support won't
195  * cause binary compatibility problems for kernel modules.
196  */
197 void
198 kmod_udpstat_inc(int statnum)
199 {
200 
201 	counter_u64_add(VNET(udpstat)[statnum], 1);
202 }
203 
204 #ifdef VIMAGE
205 static void
206 udp_destroy(void *unused __unused)
207 {
208 
209 	in_pcbinfo_destroy(&V_udbinfo);
210 	in_pcbinfo_destroy(&V_ulitecbinfo);
211 }
212 VNET_SYSUNINIT(udp, SI_SUB_PROTO_DOMAIN, SI_ORDER_FOURTH, udp_destroy, NULL);
213 #endif
214 
215 #ifdef INET
216 /*
217  * Subroutine of udp_input(), which appends the provided mbuf chain to the
218  * passed pcb/socket.  The caller must provide a sockaddr_in via udp_in that
219  * contains the source address.  If the socket ends up being an IPv6 socket,
220  * udp_append() will convert to a sockaddr_in6 before passing the address
221  * into the socket code.
222  *
223  * In the normal case udp_append() will return 0, indicating that you
224  * must unlock the inp. However if a tunneling protocol is in place we increment
225  * the inpcb refcnt and unlock the inp, on return from the tunneling protocol we
226  * then decrement the reference count. If the inp_rele returns 1, indicating the
227  * inp is gone, we return that to the caller to tell them *not* to unlock
228  * the inp. In the case of multi-cast this will cause the distribution
229  * to stop (though most tunneling protocols known currently do *not* use
230  * multicast).
231  */
232 static int
233 udp_append(struct inpcb *inp, struct ip *ip, struct mbuf *n, int off,
234     struct sockaddr_in *udp_in)
235 {
236 	struct sockaddr *append_sa;
237 	struct socket *so;
238 	struct mbuf *tmpopts, *opts = NULL;
239 #ifdef INET6
240 	struct sockaddr_in6 udp_in6;
241 #endif
242 	struct udpcb *up;
243 	bool filtered;
244 
245 	INP_LOCK_ASSERT(inp);
246 
247 	/*
248 	 * Engage the tunneling protocol.
249 	 */
250 	up = intoudpcb(inp);
251 	if (up->u_tun_func != NULL) {
252 		in_pcbref(inp);
253 		INP_RUNLOCK(inp);
254 		filtered = (*up->u_tun_func)(n, off, inp, (struct sockaddr *)&udp_in[0],
255 		    up->u_tun_ctx);
256 		INP_RLOCK(inp);
257 		if (filtered)
258 			return (in_pcbrele_rlocked(inp));
259 	}
260 
261 	off += sizeof(struct udphdr);
262 
263 #if defined(IPSEC) || defined(IPSEC_SUPPORT)
264 	/* Check AH/ESP integrity. */
265 	if (IPSEC_ENABLED(ipv4) &&
266 	    IPSEC_CHECK_POLICY(ipv4, n, inp) != 0) {
267 		m_freem(n);
268 		return (0);
269 	}
270 	if (up->u_flags & UF_ESPINUDP) {/* IPSec UDP encaps. */
271 		if (IPSEC_ENABLED(ipv4) &&
272 		    UDPENCAP_INPUT(n, off, AF_INET) != 0)
273 			return (0);	/* Consumed. */
274 	}
275 #endif /* IPSEC */
276 #ifdef MAC
277 	if (mac_inpcb_check_deliver(inp, n) != 0) {
278 		m_freem(n);
279 		return (0);
280 	}
281 #endif /* MAC */
282 	if (inp->inp_flags & INP_CONTROLOPTS ||
283 	    inp->inp_socket->so_options & (SO_TIMESTAMP | SO_BINTIME)) {
284 #ifdef INET6
285 		if (inp->inp_vflag & INP_IPV6)
286 			(void)ip6_savecontrol_v4(inp, n, &opts, NULL);
287 		else
288 #endif /* INET6 */
289 			ip_savecontrol(inp, &opts, ip, n);
290 	}
291 	if ((inp->inp_vflag & INP_IPV4) && (inp->inp_flags2 & INP_ORIGDSTADDR)) {
292 		tmpopts = sbcreatecontrol(&udp_in[1],
293 		    sizeof(struct sockaddr_in), IP_ORIGDSTADDR, IPPROTO_IP,
294 		    M_NOWAIT);
295 		if (tmpopts) {
296 			if (opts) {
297 				tmpopts->m_next = opts;
298 				opts = tmpopts;
299 			} else
300 				opts = tmpopts;
301 		}
302 	}
303 #ifdef INET6
304 	if (inp->inp_vflag & INP_IPV6) {
305 		bzero(&udp_in6, sizeof(udp_in6));
306 		udp_in6.sin6_len = sizeof(udp_in6);
307 		udp_in6.sin6_family = AF_INET6;
308 		in6_sin_2_v4mapsin6(&udp_in[0], &udp_in6);
309 		append_sa = (struct sockaddr *)&udp_in6;
310 	} else
311 #endif /* INET6 */
312 		append_sa = (struct sockaddr *)&udp_in[0];
313 	m_adj(n, off);
314 
315 	so = inp->inp_socket;
316 	SOCKBUF_LOCK(&so->so_rcv);
317 	if (sbappendaddr_locked(&so->so_rcv, append_sa, n, opts) == 0) {
318 		soroverflow_locked(so);
319 		m_freem(n);
320 		if (opts)
321 			m_freem(opts);
322 		UDPSTAT_INC(udps_fullsock);
323 	} else
324 		sorwakeup_locked(so);
325 	return (0);
326 }
327 
328 static bool
329 udp_multi_match(const struct inpcb *inp, void *v)
330 {
331 	struct ip *ip = v;
332 	struct udphdr *uh = (struct udphdr *)(ip + 1);
333 
334 	if (inp->inp_lport != uh->uh_dport)
335 		return (false);
336 #ifdef INET6
337 	if ((inp->inp_vflag & INP_IPV4) == 0)
338 		return (false);
339 #endif
340 	if (inp->inp_laddr.s_addr != INADDR_ANY &&
341 	    inp->inp_laddr.s_addr != ip->ip_dst.s_addr)
342 		return (false);
343 	if (inp->inp_faddr.s_addr != INADDR_ANY &&
344 	    inp->inp_faddr.s_addr != ip->ip_src.s_addr)
345 		return (false);
346 	if (inp->inp_fport != 0 &&
347 	    inp->inp_fport != uh->uh_sport)
348 		return (false);
349 
350 	return (true);
351 }
352 
353 static int
354 udp_multi_input(struct mbuf *m, int proto, struct sockaddr_in *udp_in)
355 {
356 	struct ip *ip = mtod(m, struct ip *);
357 	struct inpcb_iterator inpi = INP_ITERATOR(udp_get_inpcbinfo(proto),
358 	    INPLOOKUP_RLOCKPCB, udp_multi_match, ip);
359 #ifdef KDTRACE_HOOKS
360 	struct udphdr *uh = (struct udphdr *)(ip + 1);
361 #endif
362 	struct inpcb *inp;
363 	struct mbuf *n;
364 	int appends = 0;
365 
366 	MPASS(ip->ip_hl == sizeof(struct ip) >> 2);
367 
368 	while ((inp = inp_next(&inpi)) != NULL) {
369 		/*
370 		 * XXXRW: Because we weren't holding either the inpcb
371 		 * or the hash lock when we checked for a match
372 		 * before, we should probably recheck now that the
373 		 * inpcb lock is held.
374 		 */
375 		/*
376 		 * Handle socket delivery policy for any-source
377 		 * and source-specific multicast. [RFC3678]
378 		 */
379 		if (IN_MULTICAST(ntohl(ip->ip_dst.s_addr))) {
380 			struct ip_moptions	*imo;
381 			struct sockaddr_in	 group;
382 			int			 blocked;
383 
384 			imo = inp->inp_moptions;
385 			if (imo == NULL)
386 				continue;
387 			bzero(&group, sizeof(struct sockaddr_in));
388 			group.sin_len = sizeof(struct sockaddr_in);
389 			group.sin_family = AF_INET;
390 			group.sin_addr = ip->ip_dst;
391 
392 			blocked = imo_multi_filter(imo, m->m_pkthdr.rcvif,
393 				(struct sockaddr *)&group,
394 				(struct sockaddr *)&udp_in[0]);
395 			if (blocked != MCAST_PASS) {
396 				if (blocked == MCAST_NOTGMEMBER)
397 					IPSTAT_INC(ips_notmember);
398 				if (blocked == MCAST_NOTSMEMBER ||
399 				    blocked == MCAST_MUTED)
400 					UDPSTAT_INC(udps_filtermcast);
401 				continue;
402 			}
403 		}
404 		if ((n = m_copym(m, 0, M_COPYALL, M_NOWAIT)) != NULL) {
405 			if (proto == IPPROTO_UDPLITE)
406 				UDPLITE_PROBE(receive, NULL, inp, ip, inp, uh);
407 			else
408 				UDP_PROBE(receive, NULL, inp, ip, inp, uh);
409 			if (udp_append(inp, ip, n, sizeof(struct ip), udp_in)) {
410 				break;
411 			} else
412 				appends++;
413 		}
414 		/*
415 		 * Don't look for additional matches if this one does
416 		 * not have either the SO_REUSEPORT or SO_REUSEADDR
417 		 * socket options set.  This heuristic avoids
418 		 * searching through all pcbs in the common case of a
419 		 * non-shared port.  It assumes that an application
420 		 * will never clear these options after setting them.
421 		 */
422 		if ((inp->inp_socket->so_options &
423 		    (SO_REUSEPORT|SO_REUSEPORT_LB|SO_REUSEADDR)) == 0) {
424 			INP_RUNLOCK(inp);
425 			break;
426 		}
427 	}
428 
429 	if (appends == 0) {
430 		/*
431 		 * No matching pcb found; discard datagram.  (No need
432 		 * to send an ICMP Port Unreachable for a broadcast
433 		 * or multicast datgram.)
434 		 */
435 		UDPSTAT_INC(udps_noport);
436 		if (IN_MULTICAST(ntohl(ip->ip_dst.s_addr)))
437 			UDPSTAT_INC(udps_noportmcast);
438 		else
439 			UDPSTAT_INC(udps_noportbcast);
440 	}
441 	m_freem(m);
442 
443 	return (IPPROTO_DONE);
444 }
445 
446 static int
447 udp_input(struct mbuf **mp, int *offp, int proto)
448 {
449 	struct ip *ip;
450 	struct udphdr *uh;
451 	struct ifnet *ifp;
452 	struct inpcb *inp;
453 	uint16_t len, ip_len;
454 	struct inpcbinfo *pcbinfo;
455 	struct sockaddr_in udp_in[2];
456 	struct mbuf *m;
457 	struct m_tag *fwd_tag;
458 	int cscov_partial, iphlen;
459 
460 	m = *mp;
461 	iphlen = *offp;
462 	ifp = m->m_pkthdr.rcvif;
463 	*mp = NULL;
464 	UDPSTAT_INC(udps_ipackets);
465 
466 	/*
467 	 * Strip IP options, if any; should skip this, make available to
468 	 * user, and use on returned packets, but we don't yet have a way to
469 	 * check the checksum with options still present.
470 	 */
471 	if (iphlen > sizeof (struct ip)) {
472 		ip_stripoptions(m);
473 		iphlen = sizeof(struct ip);
474 	}
475 
476 	/*
477 	 * Get IP and UDP header together in first mbuf.
478 	 */
479 	if (m->m_len < iphlen + sizeof(struct udphdr)) {
480 		if ((m = m_pullup(m, iphlen + sizeof(struct udphdr))) == NULL) {
481 			UDPSTAT_INC(udps_hdrops);
482 			return (IPPROTO_DONE);
483 		}
484 	}
485 	ip = mtod(m, struct ip *);
486 	uh = (struct udphdr *)((caddr_t)ip + iphlen);
487 	cscov_partial = (proto == IPPROTO_UDPLITE) ? 1 : 0;
488 
489 	/*
490 	 * Destination port of 0 is illegal, based on RFC768.
491 	 */
492 	if (uh->uh_dport == 0)
493 		goto badunlocked;
494 
495 	/*
496 	 * Construct sockaddr format source address.  Stuff source address
497 	 * and datagram in user buffer.
498 	 */
499 	bzero(&udp_in[0], sizeof(struct sockaddr_in) * 2);
500 	udp_in[0].sin_len = sizeof(struct sockaddr_in);
501 	udp_in[0].sin_family = AF_INET;
502 	udp_in[0].sin_port = uh->uh_sport;
503 	udp_in[0].sin_addr = ip->ip_src;
504 	udp_in[1].sin_len = sizeof(struct sockaddr_in);
505 	udp_in[1].sin_family = AF_INET;
506 	udp_in[1].sin_port = uh->uh_dport;
507 	udp_in[1].sin_addr = ip->ip_dst;
508 
509 	/*
510 	 * Make mbuf data length reflect UDP length.  If not enough data to
511 	 * reflect UDP length, drop.
512 	 */
513 	len = ntohs((u_short)uh->uh_ulen);
514 	ip_len = ntohs(ip->ip_len) - iphlen;
515 	if (proto == IPPROTO_UDPLITE && (len == 0 || len == ip_len)) {
516 		/* Zero means checksum over the complete packet. */
517 		if (len == 0)
518 			len = ip_len;
519 		cscov_partial = 0;
520 	}
521 	if (ip_len != len) {
522 		if (len > ip_len || len < sizeof(struct udphdr)) {
523 			UDPSTAT_INC(udps_badlen);
524 			goto badunlocked;
525 		}
526 		if (proto == IPPROTO_UDP)
527 			m_adj(m, len - ip_len);
528 	}
529 
530 	/*
531 	 * Checksum extended UDP header and data.
532 	 */
533 	if (uh->uh_sum) {
534 		u_short uh_sum;
535 
536 		if ((m->m_pkthdr.csum_flags & CSUM_DATA_VALID) &&
537 		    !cscov_partial) {
538 			if (m->m_pkthdr.csum_flags & CSUM_PSEUDO_HDR)
539 				uh_sum = m->m_pkthdr.csum_data;
540 			else
541 				uh_sum = in_pseudo(ip->ip_src.s_addr,
542 				    ip->ip_dst.s_addr, htonl((u_short)len +
543 				    m->m_pkthdr.csum_data + proto));
544 			uh_sum ^= 0xffff;
545 		} else {
546 			char b[offsetof(struct ipovly, ih_src)];
547 			struct ipovly *ipov = (struct ipovly *)ip;
548 
549 			bcopy(ipov, b, sizeof(b));
550 			bzero(ipov, sizeof(ipov->ih_x1));
551 			ipov->ih_len = (proto == IPPROTO_UDP) ?
552 			    uh->uh_ulen : htons(ip_len);
553 			uh_sum = in_cksum(m, len + sizeof (struct ip));
554 			bcopy(b, ipov, sizeof(b));
555 		}
556 		if (uh_sum) {
557 			UDPSTAT_INC(udps_badsum);
558 			m_freem(m);
559 			return (IPPROTO_DONE);
560 		}
561 	} else {
562 		if (proto == IPPROTO_UDP) {
563 			UDPSTAT_INC(udps_nosum);
564 		} else {
565 			/* UDPLite requires a checksum */
566 			/* XXX: What is the right UDPLite MIB counter here? */
567 			m_freem(m);
568 			return (IPPROTO_DONE);
569 		}
570 	}
571 
572 	if (IN_MULTICAST(ntohl(ip->ip_dst.s_addr)) ||
573 	    in_broadcast(ip->ip_dst, ifp))
574 		return (udp_multi_input(m, proto, udp_in));
575 
576 	pcbinfo = udp_get_inpcbinfo(proto);
577 
578 	/*
579 	 * Locate pcb for datagram.
580 	 *
581 	 * Grab info from PACKET_TAG_IPFORWARD tag prepended to the chain.
582 	 */
583 	if ((m->m_flags & M_IP_NEXTHOP) &&
584 	    (fwd_tag = m_tag_find(m, PACKET_TAG_IPFORWARD, NULL)) != NULL) {
585 		struct sockaddr_in *next_hop;
586 
587 		next_hop = (struct sockaddr_in *)(fwd_tag + 1);
588 
589 		/*
590 		 * Transparently forwarded. Pretend to be the destination.
591 		 * Already got one like this?
592 		 */
593 		inp = in_pcblookup_mbuf(pcbinfo, ip->ip_src, uh->uh_sport,
594 		    ip->ip_dst, uh->uh_dport, INPLOOKUP_RLOCKPCB, ifp, m);
595 		if (!inp) {
596 			/*
597 			 * It's new.  Try to find the ambushing socket.
598 			 * Because we've rewritten the destination address,
599 			 * any hardware-generated hash is ignored.
600 			 */
601 			inp = in_pcblookup(pcbinfo, ip->ip_src,
602 			    uh->uh_sport, next_hop->sin_addr,
603 			    next_hop->sin_port ? htons(next_hop->sin_port) :
604 			    uh->uh_dport, INPLOOKUP_WILDCARD |
605 			    INPLOOKUP_RLOCKPCB, ifp);
606 		}
607 		/* Remove the tag from the packet. We don't need it anymore. */
608 		m_tag_delete(m, fwd_tag);
609 		m->m_flags &= ~M_IP_NEXTHOP;
610 	} else
611 		inp = in_pcblookup_mbuf(pcbinfo, ip->ip_src, uh->uh_sport,
612 		    ip->ip_dst, uh->uh_dport, INPLOOKUP_WILDCARD |
613 		    INPLOOKUP_RLOCKPCB, ifp, m);
614 	if (inp == NULL) {
615 		if (V_udp_log_in_vain) {
616 			char src[INET_ADDRSTRLEN];
617 			char dst[INET_ADDRSTRLEN];
618 
619 			log(LOG_INFO,
620 			    "Connection attempt to UDP %s:%d from %s:%d\n",
621 			    inet_ntoa_r(ip->ip_dst, dst), ntohs(uh->uh_dport),
622 			    inet_ntoa_r(ip->ip_src, src), ntohs(uh->uh_sport));
623 		}
624 		if (proto == IPPROTO_UDPLITE)
625 			UDPLITE_PROBE(receive, NULL, NULL, ip, NULL, uh);
626 		else
627 			UDP_PROBE(receive, NULL, NULL, ip, NULL, uh);
628 		UDPSTAT_INC(udps_noport);
629 		if (m->m_flags & (M_BCAST | M_MCAST)) {
630 			UDPSTAT_INC(udps_noportbcast);
631 			goto badunlocked;
632 		}
633 		if (V_udp_blackhole && (V_udp_blackhole_local ||
634 		    !in_localip(ip->ip_src)))
635 			goto badunlocked;
636 		if (badport_bandlim(BANDLIM_ICMP_UNREACH) < 0)
637 			goto badunlocked;
638 		icmp_error(m, ICMP_UNREACH, ICMP_UNREACH_PORT, 0, 0);
639 		return (IPPROTO_DONE);
640 	}
641 
642 	/*
643 	 * Check the minimum TTL for socket.
644 	 */
645 	INP_RLOCK_ASSERT(inp);
646 	if (inp->inp_ip_minttl && inp->inp_ip_minttl > ip->ip_ttl) {
647 		if (proto == IPPROTO_UDPLITE)
648 			UDPLITE_PROBE(receive, NULL, inp, ip, inp, uh);
649 		else
650 			UDP_PROBE(receive, NULL, inp, ip, inp, uh);
651 		INP_RUNLOCK(inp);
652 		m_freem(m);
653 		return (IPPROTO_DONE);
654 	}
655 	if (cscov_partial) {
656 		struct udpcb *up;
657 
658 		up = intoudpcb(inp);
659 		if (up->u_rxcslen == 0 || up->u_rxcslen > len) {
660 			INP_RUNLOCK(inp);
661 			m_freem(m);
662 			return (IPPROTO_DONE);
663 		}
664 	}
665 
666 	if (proto == IPPROTO_UDPLITE)
667 		UDPLITE_PROBE(receive, NULL, inp, ip, inp, uh);
668 	else
669 		UDP_PROBE(receive, NULL, inp, ip, inp, uh);
670 	if (udp_append(inp, ip, m, iphlen, udp_in) == 0)
671 		INP_RUNLOCK(inp);
672 	return (IPPROTO_DONE);
673 
674 badunlocked:
675 	m_freem(m);
676 	return (IPPROTO_DONE);
677 }
678 #endif /* INET */
679 
680 /*
681  * Notify a udp user of an asynchronous error; just wake up so that they can
682  * collect error status.
683  */
684 struct inpcb *
685 udp_notify(struct inpcb *inp, int errno)
686 {
687 
688 	INP_WLOCK_ASSERT(inp);
689 	if ((errno == EHOSTUNREACH || errno == ENETUNREACH ||
690 	     errno == EHOSTDOWN) && inp->inp_route.ro_nh) {
691 		NH_FREE(inp->inp_route.ro_nh);
692 		inp->inp_route.ro_nh = (struct nhop_object *)NULL;
693 	}
694 
695 	inp->inp_socket->so_error = errno;
696 	sorwakeup(inp->inp_socket);
697 	sowwakeup(inp->inp_socket);
698 	return (inp);
699 }
700 
701 #ifdef INET
702 static void
703 udp_common_ctlinput(struct icmp *icmp, struct inpcbinfo *pcbinfo)
704 {
705 	struct ip *ip = &icmp->icmp_ip;
706 	struct udphdr *uh;
707 	struct inpcb *inp;
708 
709 	if (icmp_errmap(icmp) == 0)
710 		return;
711 
712 	uh = (struct udphdr *)((caddr_t)ip + (ip->ip_hl << 2));
713 	inp = in_pcblookup(pcbinfo, ip->ip_dst, uh->uh_dport, ip->ip_src,
714 	    uh->uh_sport, INPLOOKUP_WLOCKPCB, NULL);
715 	if (inp != NULL) {
716 		INP_WLOCK_ASSERT(inp);
717 		if (inp->inp_socket != NULL)
718 			udp_notify(inp, icmp_errmap(icmp));
719 		INP_WUNLOCK(inp);
720 	} else {
721 		inp = in_pcblookup(pcbinfo, ip->ip_dst, uh->uh_dport,
722 		    ip->ip_src, uh->uh_sport,
723 		    INPLOOKUP_WILDCARD | INPLOOKUP_RLOCKPCB, NULL);
724 		if (inp != NULL) {
725 			struct udpcb *up;
726 			udp_tun_icmp_t *func;
727 
728 			up = intoudpcb(inp);
729 			func = up->u_icmp_func;
730 			INP_RUNLOCK(inp);
731 			if (func != NULL)
732 				func(icmp);
733 		}
734 	}
735 }
736 
737 static void
738 udp_ctlinput(struct icmp *icmp)
739 {
740 
741 	return (udp_common_ctlinput(icmp, &V_udbinfo));
742 }
743 
744 static void
745 udplite_ctlinput(struct icmp *icmp)
746 {
747 
748 	return (udp_common_ctlinput(icmp, &V_ulitecbinfo));
749 }
750 #endif /* INET */
751 
752 static int
753 udp_pcblist(SYSCTL_HANDLER_ARGS)
754 {
755 	struct inpcb_iterator inpi = INP_ALL_ITERATOR(&V_udbinfo,
756 	    INPLOOKUP_RLOCKPCB);
757 	struct xinpgen xig;
758 	struct inpcb *inp;
759 	int error;
760 
761 	if (req->newptr != 0)
762 		return (EPERM);
763 
764 	if (req->oldptr == 0) {
765 		int n;
766 
767 		n = V_udbinfo.ipi_count;
768 		n += imax(n / 8, 10);
769 		req->oldidx = 2 * (sizeof xig) + n * sizeof(struct xinpcb);
770 		return (0);
771 	}
772 
773 	if ((error = sysctl_wire_old_buffer(req, 0)) != 0)
774 		return (error);
775 
776 	bzero(&xig, sizeof(xig));
777 	xig.xig_len = sizeof xig;
778 	xig.xig_count = V_udbinfo.ipi_count;
779 	xig.xig_gen = V_udbinfo.ipi_gencnt;
780 	xig.xig_sogen = so_gencnt;
781 	error = SYSCTL_OUT(req, &xig, sizeof xig);
782 	if (error)
783 		return (error);
784 
785 	while ((inp = inp_next(&inpi)) != NULL) {
786 		if (inp->inp_gencnt <= xig.xig_gen &&
787 		    cr_canseeinpcb(req->td->td_ucred, inp) == 0) {
788 			struct xinpcb xi;
789 
790 			in_pcbtoxinpcb(inp, &xi);
791 			error = SYSCTL_OUT(req, &xi, sizeof xi);
792 			if (error) {
793 				INP_RUNLOCK(inp);
794 				break;
795 			}
796 		}
797 	}
798 
799 	if (!error) {
800 		/*
801 		 * Give the user an updated idea of our state.  If the
802 		 * generation differs from what we told her before, she knows
803 		 * that something happened while we were processing this
804 		 * request, and it might be necessary to retry.
805 		 */
806 		xig.xig_gen = V_udbinfo.ipi_gencnt;
807 		xig.xig_sogen = so_gencnt;
808 		xig.xig_count = V_udbinfo.ipi_count;
809 		error = SYSCTL_OUT(req, &xig, sizeof xig);
810 	}
811 
812 	return (error);
813 }
814 
815 SYSCTL_PROC(_net_inet_udp, UDPCTL_PCBLIST, pcblist,
816     CTLTYPE_OPAQUE | CTLFLAG_RD | CTLFLAG_MPSAFE, NULL, 0,
817     udp_pcblist, "S,xinpcb",
818     "List of active UDP sockets");
819 
820 #ifdef INET
821 static int
822 udp_getcred(SYSCTL_HANDLER_ARGS)
823 {
824 	struct xucred xuc;
825 	struct sockaddr_in addrs[2];
826 	struct epoch_tracker et;
827 	struct inpcb *inp;
828 	int error;
829 
830 	error = priv_check(req->td, PRIV_NETINET_GETCRED);
831 	if (error)
832 		return (error);
833 	error = SYSCTL_IN(req, addrs, sizeof(addrs));
834 	if (error)
835 		return (error);
836 	NET_EPOCH_ENTER(et);
837 	inp = in_pcblookup(&V_udbinfo, addrs[1].sin_addr, addrs[1].sin_port,
838 	    addrs[0].sin_addr, addrs[0].sin_port,
839 	    INPLOOKUP_WILDCARD | INPLOOKUP_RLOCKPCB, NULL);
840 	NET_EPOCH_EXIT(et);
841 	if (inp != NULL) {
842 		INP_RLOCK_ASSERT(inp);
843 		if (inp->inp_socket == NULL)
844 			error = ENOENT;
845 		if (error == 0)
846 			error = cr_canseeinpcb(req->td->td_ucred, inp);
847 		if (error == 0)
848 			cru2x(inp->inp_cred, &xuc);
849 		INP_RUNLOCK(inp);
850 	} else
851 		error = ENOENT;
852 	if (error == 0)
853 		error = SYSCTL_OUT(req, &xuc, sizeof(struct xucred));
854 	return (error);
855 }
856 
857 SYSCTL_PROC(_net_inet_udp, OID_AUTO, getcred,
858     CTLTYPE_OPAQUE | CTLFLAG_RW | CTLFLAG_PRISON | CTLFLAG_MPSAFE,
859     0, 0, udp_getcred, "S,xucred",
860     "Get the xucred of a UDP connection");
861 #endif /* INET */
862 
863 int
864 udp_ctloutput(struct socket *so, struct sockopt *sopt)
865 {
866 	struct inpcb *inp;
867 	struct udpcb *up;
868 	int isudplite, error, optval;
869 
870 	error = 0;
871 	isudplite = (so->so_proto->pr_protocol == IPPROTO_UDPLITE) ? 1 : 0;
872 	inp = sotoinpcb(so);
873 	KASSERT(inp != NULL, ("%s: inp == NULL", __func__));
874 	INP_WLOCK(inp);
875 	if (sopt->sopt_level != so->so_proto->pr_protocol) {
876 #ifdef INET6
877 		if (INP_CHECK_SOCKAF(so, AF_INET6)) {
878 			INP_WUNLOCK(inp);
879 			error = ip6_ctloutput(so, sopt);
880 		}
881 #endif
882 #if defined(INET) && defined(INET6)
883 		else
884 #endif
885 #ifdef INET
886 		{
887 			INP_WUNLOCK(inp);
888 			error = ip_ctloutput(so, sopt);
889 		}
890 #endif
891 		return (error);
892 	}
893 
894 	switch (sopt->sopt_dir) {
895 	case SOPT_SET:
896 		switch (sopt->sopt_name) {
897 #if defined(IPSEC) || defined(IPSEC_SUPPORT)
898 #ifdef INET
899 		case UDP_ENCAP:
900 			if (!IPSEC_ENABLED(ipv4)) {
901 				INP_WUNLOCK(inp);
902 				return (ENOPROTOOPT);
903 			}
904 			error = UDPENCAP_PCBCTL(inp, sopt);
905 			break;
906 #endif /* INET */
907 #endif /* IPSEC */
908 		case UDPLITE_SEND_CSCOV:
909 		case UDPLITE_RECV_CSCOV:
910 			if (!isudplite) {
911 				INP_WUNLOCK(inp);
912 				error = ENOPROTOOPT;
913 				break;
914 			}
915 			INP_WUNLOCK(inp);
916 			error = sooptcopyin(sopt, &optval, sizeof(optval),
917 			    sizeof(optval));
918 			if (error != 0)
919 				break;
920 			inp = sotoinpcb(so);
921 			KASSERT(inp != NULL, ("%s: inp == NULL", __func__));
922 			INP_WLOCK(inp);
923 			up = intoudpcb(inp);
924 			KASSERT(up != NULL, ("%s: up == NULL", __func__));
925 			if ((optval != 0 && optval < 8) || (optval > 65535)) {
926 				INP_WUNLOCK(inp);
927 				error = EINVAL;
928 				break;
929 			}
930 			if (sopt->sopt_name == UDPLITE_SEND_CSCOV)
931 				up->u_txcslen = optval;
932 			else
933 				up->u_rxcslen = optval;
934 			INP_WUNLOCK(inp);
935 			break;
936 		default:
937 			INP_WUNLOCK(inp);
938 			error = ENOPROTOOPT;
939 			break;
940 		}
941 		break;
942 	case SOPT_GET:
943 		switch (sopt->sopt_name) {
944 #if defined(IPSEC) || defined(IPSEC_SUPPORT)
945 #ifdef INET
946 		case UDP_ENCAP:
947 			if (!IPSEC_ENABLED(ipv4)) {
948 				INP_WUNLOCK(inp);
949 				return (ENOPROTOOPT);
950 			}
951 			error = UDPENCAP_PCBCTL(inp, sopt);
952 			break;
953 #endif /* INET */
954 #endif /* IPSEC */
955 		case UDPLITE_SEND_CSCOV:
956 		case UDPLITE_RECV_CSCOV:
957 			if (!isudplite) {
958 				INP_WUNLOCK(inp);
959 				error = ENOPROTOOPT;
960 				break;
961 			}
962 			up = intoudpcb(inp);
963 			KASSERT(up != NULL, ("%s: up == NULL", __func__));
964 			if (sopt->sopt_name == UDPLITE_SEND_CSCOV)
965 				optval = up->u_txcslen;
966 			else
967 				optval = up->u_rxcslen;
968 			INP_WUNLOCK(inp);
969 			error = sooptcopyout(sopt, &optval, sizeof(optval));
970 			break;
971 		default:
972 			INP_WUNLOCK(inp);
973 			error = ENOPROTOOPT;
974 			break;
975 		}
976 		break;
977 	}
978 	return (error);
979 }
980 
981 #ifdef INET
982 #ifdef INET6
983 /* The logic here is derived from ip6_setpktopt(). See comments there. */
984 static int
985 udp_v4mapped_pktinfo(struct cmsghdr *cm, struct sockaddr_in * src,
986     struct inpcb *inp, int flags)
987 {
988 	struct ifnet *ifp;
989 	struct in6_pktinfo *pktinfo;
990 	struct in_addr ia;
991 
992 	if ((flags & PRUS_IPV6) == 0)
993 		return (0);
994 
995 	if (cm->cmsg_level != IPPROTO_IPV6)
996 		return (0);
997 
998 	if  (cm->cmsg_type != IPV6_2292PKTINFO &&
999 	    cm->cmsg_type != IPV6_PKTINFO)
1000 		return (0);
1001 
1002 	if (cm->cmsg_len !=
1003 	    CMSG_LEN(sizeof(struct in6_pktinfo)))
1004 		return (EINVAL);
1005 
1006 	pktinfo = (struct in6_pktinfo *)CMSG_DATA(cm);
1007 	if (!IN6_IS_ADDR_V4MAPPED(&pktinfo->ipi6_addr) &&
1008 	    !IN6_IS_ADDR_UNSPECIFIED(&pktinfo->ipi6_addr))
1009 		return (EINVAL);
1010 
1011 	/* Validate the interface index if specified. */
1012 	if (pktinfo->ipi6_ifindex) {
1013 		struct epoch_tracker et;
1014 
1015 		NET_EPOCH_ENTER(et);
1016 		ifp = ifnet_byindex(pktinfo->ipi6_ifindex);
1017 		NET_EPOCH_EXIT(et);	/* XXXGL: unsafe ifp */
1018 		if (ifp == NULL)
1019 			return (ENXIO);
1020 	} else
1021 		ifp = NULL;
1022 	if (ifp != NULL && !IN6_IS_ADDR_UNSPECIFIED(&pktinfo->ipi6_addr)) {
1023 		ia.s_addr = pktinfo->ipi6_addr.s6_addr32[3];
1024 		if (in_ifhasaddr(ifp, ia) == 0)
1025 			return (EADDRNOTAVAIL);
1026 	}
1027 
1028 	bzero(src, sizeof(*src));
1029 	src->sin_family = AF_INET;
1030 	src->sin_len = sizeof(*src);
1031 	src->sin_port = inp->inp_lport;
1032 	src->sin_addr.s_addr = pktinfo->ipi6_addr.s6_addr32[3];
1033 
1034 	return (0);
1035 }
1036 #endif	/* INET6 */
1037 
1038 int
1039 udp_send(struct socket *so, int flags, struct mbuf *m, struct sockaddr *addr,
1040     struct mbuf *control, struct thread *td)
1041 {
1042 	struct inpcb *inp;
1043 	struct udpiphdr *ui;
1044 	int len, error = 0;
1045 	struct in_addr faddr, laddr;
1046 	struct cmsghdr *cm;
1047 	struct inpcbinfo *pcbinfo;
1048 	struct sockaddr_in *sin, src;
1049 	struct epoch_tracker et;
1050 	int cscov_partial = 0;
1051 	int ipflags = 0;
1052 	u_short fport, lport;
1053 	u_char tos, vflagsav;
1054 	uint8_t pr;
1055 	uint16_t cscov = 0;
1056 	uint32_t flowid = 0;
1057 	uint8_t flowtype = M_HASHTYPE_NONE;
1058 
1059 	inp = sotoinpcb(so);
1060 	KASSERT(inp != NULL, ("udp_send: inp == NULL"));
1061 
1062 	if (addr != NULL) {
1063 		if (addr->sa_family != AF_INET)
1064 			error = EAFNOSUPPORT;
1065 		else if (addr->sa_len != sizeof(struct sockaddr_in))
1066 			error = EINVAL;
1067 		if (__predict_false(error != 0)) {
1068 			m_freem(control);
1069 			m_freem(m);
1070 			return (error);
1071 		}
1072 	}
1073 
1074 	len = m->m_pkthdr.len;
1075 	if (len + sizeof(struct udpiphdr) > IP_MAXPACKET) {
1076 		if (control)
1077 			m_freem(control);
1078 		m_freem(m);
1079 		return (EMSGSIZE);
1080 	}
1081 
1082 	src.sin_family = 0;
1083 	sin = (struct sockaddr_in *)addr;
1084 
1085 	/*
1086 	 * udp_send() may need to temporarily bind or connect the current
1087 	 * inpcb.  As such, we don't know up front whether we will need the
1088 	 * pcbinfo lock or not.  Do any work to decide what is needed up
1089 	 * front before acquiring any locks.
1090 	 *
1091 	 * We will need network epoch in either case, to safely lookup into
1092 	 * pcb hash.
1093 	 */
1094 	if (sin == NULL ||
1095 	    (inp->inp_laddr.s_addr == INADDR_ANY && inp->inp_lport == 0) ||
1096 	    (flags & PRUS_IPV6) != 0)
1097 		INP_WLOCK(inp);
1098 	else
1099 		INP_RLOCK(inp);
1100 	NET_EPOCH_ENTER(et);
1101 	tos = inp->inp_ip_tos;
1102 	if (control != NULL) {
1103 		/*
1104 		 * XXX: Currently, we assume all the optional information is
1105 		 * stored in a single mbuf.
1106 		 */
1107 		if (control->m_next) {
1108 			m_freem(control);
1109 			error = EINVAL;
1110 			goto release;
1111 		}
1112 		for (; control->m_len > 0;
1113 		    control->m_data += CMSG_ALIGN(cm->cmsg_len),
1114 		    control->m_len -= CMSG_ALIGN(cm->cmsg_len)) {
1115 			cm = mtod(control, struct cmsghdr *);
1116 			if (control->m_len < sizeof(*cm) || cm->cmsg_len == 0
1117 			    || cm->cmsg_len > control->m_len) {
1118 				error = EINVAL;
1119 				break;
1120 			}
1121 #ifdef INET6
1122 			error = udp_v4mapped_pktinfo(cm, &src, inp, flags);
1123 			if (error != 0)
1124 				break;
1125 #endif
1126 			if (cm->cmsg_level != IPPROTO_IP)
1127 				continue;
1128 
1129 			switch (cm->cmsg_type) {
1130 			case IP_SENDSRCADDR:
1131 				if (cm->cmsg_len !=
1132 				    CMSG_LEN(sizeof(struct in_addr))) {
1133 					error = EINVAL;
1134 					break;
1135 				}
1136 				bzero(&src, sizeof(src));
1137 				src.sin_family = AF_INET;
1138 				src.sin_len = sizeof(src);
1139 				src.sin_port = inp->inp_lport;
1140 				src.sin_addr =
1141 				    *(struct in_addr *)CMSG_DATA(cm);
1142 				break;
1143 
1144 			case IP_TOS:
1145 				if (cm->cmsg_len != CMSG_LEN(sizeof(u_char))) {
1146 					error = EINVAL;
1147 					break;
1148 				}
1149 				tos = *(u_char *)CMSG_DATA(cm);
1150 				break;
1151 
1152 			case IP_FLOWID:
1153 				if (cm->cmsg_len != CMSG_LEN(sizeof(uint32_t))) {
1154 					error = EINVAL;
1155 					break;
1156 				}
1157 				flowid = *(uint32_t *) CMSG_DATA(cm);
1158 				break;
1159 
1160 			case IP_FLOWTYPE:
1161 				if (cm->cmsg_len != CMSG_LEN(sizeof(uint32_t))) {
1162 					error = EINVAL;
1163 					break;
1164 				}
1165 				flowtype = *(uint32_t *) CMSG_DATA(cm);
1166 				break;
1167 
1168 #ifdef	RSS
1169 			case IP_RSSBUCKETID:
1170 				if (cm->cmsg_len != CMSG_LEN(sizeof(uint32_t))) {
1171 					error = EINVAL;
1172 					break;
1173 				}
1174 				/* This is just a placeholder for now */
1175 				break;
1176 #endif	/* RSS */
1177 			default:
1178 				error = ENOPROTOOPT;
1179 				break;
1180 			}
1181 			if (error)
1182 				break;
1183 		}
1184 		m_freem(control);
1185 		control = NULL;
1186 	}
1187 	if (error)
1188 		goto release;
1189 
1190 	pr = inp->inp_socket->so_proto->pr_protocol;
1191 	pcbinfo = udp_get_inpcbinfo(pr);
1192 
1193 	/*
1194 	 * If the IP_SENDSRCADDR control message was specified, override the
1195 	 * source address for this datagram.  Its use is invalidated if the
1196 	 * address thus specified is incomplete or clobbers other inpcbs.
1197 	 */
1198 	laddr = inp->inp_laddr;
1199 	lport = inp->inp_lport;
1200 	if (src.sin_family == AF_INET) {
1201 		if ((lport == 0) ||
1202 		    (laddr.s_addr == INADDR_ANY &&
1203 		     src.sin_addr.s_addr == INADDR_ANY)) {
1204 			error = EINVAL;
1205 			goto release;
1206 		}
1207 		if ((flags & PRUS_IPV6) != 0) {
1208 			vflagsav = inp->inp_vflag;
1209 			inp->inp_vflag |= INP_IPV4;
1210 			inp->inp_vflag &= ~INP_IPV6;
1211 		}
1212 		INP_HASH_WLOCK(pcbinfo);
1213 		error = in_pcbbind_setup(inp, &src, &laddr.s_addr, &lport,
1214 		    td->td_ucred);
1215 		INP_HASH_WUNLOCK(pcbinfo);
1216 		if ((flags & PRUS_IPV6) != 0)
1217 			inp->inp_vflag = vflagsav;
1218 		if (error)
1219 			goto release;
1220 	}
1221 
1222 	/*
1223 	 * If a UDP socket has been connected, then a local address/port will
1224 	 * have been selected and bound.
1225 	 *
1226 	 * If a UDP socket has not been connected to, then an explicit
1227 	 * destination address must be used, in which case a local
1228 	 * address/port may not have been selected and bound.
1229 	 */
1230 	if (sin != NULL) {
1231 		INP_LOCK_ASSERT(inp);
1232 		if (inp->inp_faddr.s_addr != INADDR_ANY) {
1233 			error = EISCONN;
1234 			goto release;
1235 		}
1236 
1237 		/*
1238 		 * Jail may rewrite the destination address, so let it do
1239 		 * that before we use it.
1240 		 */
1241 		error = prison_remote_ip4(td->td_ucred, &sin->sin_addr);
1242 		if (error)
1243 			goto release;
1244 
1245 		/*
1246 		 * If a local address or port hasn't yet been selected, or if
1247 		 * the destination address needs to be rewritten due to using
1248 		 * a special INADDR_ constant, invoke in_pcbconnect_setup()
1249 		 * to do the heavy lifting.  Once a port is selected, we
1250 		 * commit the binding back to the socket; we also commit the
1251 		 * binding of the address if in jail.
1252 		 *
1253 		 * If we already have a valid binding and we're not
1254 		 * requesting a destination address rewrite, use a fast path.
1255 		 */
1256 		if (inp->inp_laddr.s_addr == INADDR_ANY ||
1257 		    inp->inp_lport == 0 ||
1258 		    sin->sin_addr.s_addr == INADDR_ANY ||
1259 		    sin->sin_addr.s_addr == INADDR_BROADCAST) {
1260 			if ((flags & PRUS_IPV6) != 0) {
1261 				vflagsav = inp->inp_vflag;
1262 				inp->inp_vflag |= INP_IPV4;
1263 				inp->inp_vflag &= ~INP_IPV6;
1264 			}
1265 			INP_HASH_WLOCK(pcbinfo);
1266 			error = in_pcbconnect_setup(inp, sin, &laddr.s_addr,
1267 			    &lport, &faddr.s_addr, &fport, td->td_ucred);
1268 			if ((flags & PRUS_IPV6) != 0)
1269 				inp->inp_vflag = vflagsav;
1270 			if (error) {
1271 				INP_HASH_WUNLOCK(pcbinfo);
1272 				goto release;
1273 			}
1274 
1275 			/*
1276 			 * XXXRW: Why not commit the port if the address is
1277 			 * !INADDR_ANY?
1278 			 */
1279 			/* Commit the local port if newly assigned. */
1280 			if (inp->inp_laddr.s_addr == INADDR_ANY &&
1281 			    inp->inp_lport == 0) {
1282 				INP_WLOCK_ASSERT(inp);
1283 				/*
1284 				 * Remember addr if jailed, to prevent
1285 				 * rebinding.
1286 				 */
1287 				if (prison_flag(td->td_ucred, PR_IP4))
1288 					inp->inp_laddr = laddr;
1289 				inp->inp_lport = lport;
1290 				error = in_pcbinshash(inp);
1291 				INP_HASH_WUNLOCK(pcbinfo);
1292 				if (error != 0) {
1293 					inp->inp_lport = 0;
1294 					error = EAGAIN;
1295 					goto release;
1296 				}
1297 				inp->inp_flags |= INP_ANONPORT;
1298 			} else
1299 				INP_HASH_WUNLOCK(pcbinfo);
1300 		} else {
1301 			faddr = sin->sin_addr;
1302 			fport = sin->sin_port;
1303 		}
1304 	} else {
1305 		INP_LOCK_ASSERT(inp);
1306 		faddr = inp->inp_faddr;
1307 		fport = inp->inp_fport;
1308 		if (faddr.s_addr == INADDR_ANY) {
1309 			error = ENOTCONN;
1310 			goto release;
1311 		}
1312 	}
1313 
1314 	/*
1315 	 * Calculate data length and get a mbuf for UDP, IP, and possible
1316 	 * link-layer headers.  Immediate slide the data pointer back forward
1317 	 * since we won't use that space at this layer.
1318 	 */
1319 	M_PREPEND(m, sizeof(struct udpiphdr) + max_linkhdr, M_NOWAIT);
1320 	if (m == NULL) {
1321 		error = ENOBUFS;
1322 		goto release;
1323 	}
1324 	m->m_data += max_linkhdr;
1325 	m->m_len -= max_linkhdr;
1326 	m->m_pkthdr.len -= max_linkhdr;
1327 
1328 	/*
1329 	 * Fill in mbuf with extended UDP header and addresses and length put
1330 	 * into network format.
1331 	 */
1332 	ui = mtod(m, struct udpiphdr *);
1333 	bzero(ui->ui_x1, sizeof(ui->ui_x1));	/* XXX still needed? */
1334 	ui->ui_v = IPVERSION << 4;
1335 	ui->ui_pr = pr;
1336 	ui->ui_src = laddr;
1337 	ui->ui_dst = faddr;
1338 	ui->ui_sport = lport;
1339 	ui->ui_dport = fport;
1340 	ui->ui_ulen = htons((u_short)len + sizeof(struct udphdr));
1341 	if (pr == IPPROTO_UDPLITE) {
1342 		struct udpcb *up;
1343 		uint16_t plen;
1344 
1345 		up = intoudpcb(inp);
1346 		cscov = up->u_txcslen;
1347 		plen = (u_short)len + sizeof(struct udphdr);
1348 		if (cscov >= plen)
1349 			cscov = 0;
1350 		ui->ui_len = htons(plen);
1351 		ui->ui_ulen = htons(cscov);
1352 		/*
1353 		 * For UDP-Lite, checksum coverage length of zero means
1354 		 * the entire UDPLite packet is covered by the checksum.
1355 		 */
1356 		cscov_partial = (cscov == 0) ? 0 : 1;
1357 	}
1358 
1359 	/*
1360 	 * Set the Don't Fragment bit in the IP header.
1361 	 */
1362 	if (inp->inp_flags & INP_DONTFRAG) {
1363 		struct ip *ip;
1364 
1365 		ip = (struct ip *)&ui->ui_i;
1366 		ip->ip_off |= htons(IP_DF);
1367 	}
1368 
1369 	if (inp->inp_socket->so_options & SO_DONTROUTE)
1370 		ipflags |= IP_ROUTETOIF;
1371 	if (inp->inp_socket->so_options & SO_BROADCAST)
1372 		ipflags |= IP_ALLOWBROADCAST;
1373 	if (inp->inp_flags & INP_ONESBCAST)
1374 		ipflags |= IP_SENDONES;
1375 
1376 #ifdef MAC
1377 	mac_inpcb_create_mbuf(inp, m);
1378 #endif
1379 
1380 	/*
1381 	 * Set up checksum and output datagram.
1382 	 */
1383 	ui->ui_sum = 0;
1384 	if (pr == IPPROTO_UDPLITE) {
1385 		if (inp->inp_flags & INP_ONESBCAST)
1386 			faddr.s_addr = INADDR_BROADCAST;
1387 		if (cscov_partial) {
1388 			if ((ui->ui_sum = in_cksum(m, sizeof(struct ip) + cscov)) == 0)
1389 				ui->ui_sum = 0xffff;
1390 		} else {
1391 			if ((ui->ui_sum = in_cksum(m, sizeof(struct udpiphdr) + len)) == 0)
1392 				ui->ui_sum = 0xffff;
1393 		}
1394 	} else if (V_udp_cksum) {
1395 		if (inp->inp_flags & INP_ONESBCAST)
1396 			faddr.s_addr = INADDR_BROADCAST;
1397 		ui->ui_sum = in_pseudo(ui->ui_src.s_addr, faddr.s_addr,
1398 		    htons((u_short)len + sizeof(struct udphdr) + pr));
1399 		m->m_pkthdr.csum_flags = CSUM_UDP;
1400 		m->m_pkthdr.csum_data = offsetof(struct udphdr, uh_sum);
1401 	}
1402 	((struct ip *)ui)->ip_len = htons(sizeof(struct udpiphdr) + len);
1403 	((struct ip *)ui)->ip_ttl = inp->inp_ip_ttl;	/* XXX */
1404 	((struct ip *)ui)->ip_tos = tos;		/* XXX */
1405 	UDPSTAT_INC(udps_opackets);
1406 
1407 	/*
1408 	 * Setup flowid / RSS information for outbound socket.
1409 	 *
1410 	 * Once the UDP code decides to set a flowid some other way,
1411 	 * this allows the flowid to be overridden by userland.
1412 	 */
1413 	if (flowtype != M_HASHTYPE_NONE) {
1414 		m->m_pkthdr.flowid = flowid;
1415 		M_HASHTYPE_SET(m, flowtype);
1416 	}
1417 #if defined(ROUTE_MPATH) || defined(RSS)
1418 	else if (CALC_FLOWID_OUTBOUND_SENDTO) {
1419 		uint32_t hash_val, hash_type;
1420 
1421 		hash_val = fib4_calc_packet_hash(laddr, faddr,
1422 		    lport, fport, pr, &hash_type);
1423 		m->m_pkthdr.flowid = hash_val;
1424 		M_HASHTYPE_SET(m, hash_type);
1425 	}
1426 
1427 	/*
1428 	 * Don't override with the inp cached flowid value.
1429 	 *
1430 	 * Depending upon the kind of send being done, the inp
1431 	 * flowid/flowtype values may actually not be appropriate
1432 	 * for this particular socket send.
1433 	 *
1434 	 * We should either leave the flowid at zero (which is what is
1435 	 * currently done) or set it to some software generated
1436 	 * hash value based on the packet contents.
1437 	 */
1438 	ipflags |= IP_NODEFAULTFLOWID;
1439 #endif	/* RSS */
1440 
1441 	if (pr == IPPROTO_UDPLITE)
1442 		UDPLITE_PROBE(send, NULL, inp, &ui->ui_i, inp, &ui->ui_u);
1443 	else
1444 		UDP_PROBE(send, NULL, inp, &ui->ui_i, inp, &ui->ui_u);
1445 	error = ip_output(m, inp->inp_options,
1446 	    INP_WLOCKED(inp) ? &inp->inp_route : NULL, ipflags,
1447 	    inp->inp_moptions, inp);
1448 	INP_UNLOCK(inp);
1449 	NET_EPOCH_EXIT(et);
1450 	return (error);
1451 
1452 release:
1453 	INP_UNLOCK(inp);
1454 	NET_EPOCH_EXIT(et);
1455 	m_freem(m);
1456 	return (error);
1457 }
1458 
1459 void
1460 udp_abort(struct socket *so)
1461 {
1462 	struct inpcb *inp;
1463 	struct inpcbinfo *pcbinfo;
1464 
1465 	pcbinfo = udp_get_inpcbinfo(so->so_proto->pr_protocol);
1466 	inp = sotoinpcb(so);
1467 	KASSERT(inp != NULL, ("udp_abort: inp == NULL"));
1468 	INP_WLOCK(inp);
1469 	if (inp->inp_faddr.s_addr != INADDR_ANY) {
1470 		INP_HASH_WLOCK(pcbinfo);
1471 		in_pcbdisconnect(inp);
1472 		INP_HASH_WUNLOCK(pcbinfo);
1473 		soisdisconnected(so);
1474 	}
1475 	INP_WUNLOCK(inp);
1476 }
1477 
1478 static int
1479 udp_attach(struct socket *so, int proto, struct thread *td)
1480 {
1481 	static uint32_t udp_flowid;
1482 	struct inpcbinfo *pcbinfo;
1483 	struct inpcb *inp;
1484 	struct udpcb *up;
1485 	int error;
1486 
1487 	pcbinfo = udp_get_inpcbinfo(so->so_proto->pr_protocol);
1488 	inp = sotoinpcb(so);
1489 	KASSERT(inp == NULL, ("udp_attach: inp != NULL"));
1490 	error = soreserve(so, udp_sendspace, udp_recvspace);
1491 	if (error)
1492 		return (error);
1493 	error = in_pcballoc(so, pcbinfo);
1494 	if (error)
1495 		return (error);
1496 
1497 	inp = sotoinpcb(so);
1498 	inp->inp_ip_ttl = V_ip_defttl;
1499 	inp->inp_flowid = atomic_fetchadd_int(&udp_flowid, 1);
1500 	inp->inp_flowtype = M_HASHTYPE_OPAQUE;
1501 	up = intoudpcb(inp);
1502 	bzero(&up->u_start_zero, u_zero_size);
1503 	INP_WUNLOCK(inp);
1504 
1505 	return (0);
1506 }
1507 #endif /* INET */
1508 
1509 int
1510 udp_set_kernel_tunneling(struct socket *so, udp_tun_func_t f, udp_tun_icmp_t i, void *ctx)
1511 {
1512 	struct inpcb *inp;
1513 	struct udpcb *up;
1514 
1515 	KASSERT(so->so_type == SOCK_DGRAM,
1516 	    ("udp_set_kernel_tunneling: !dgram"));
1517 	inp = sotoinpcb(so);
1518 	KASSERT(inp != NULL, ("udp_set_kernel_tunneling: inp == NULL"));
1519 	INP_WLOCK(inp);
1520 	up = intoudpcb(inp);
1521 	if ((f != NULL || i != NULL) && ((up->u_tun_func != NULL) ||
1522 	    (up->u_icmp_func != NULL))) {
1523 		INP_WUNLOCK(inp);
1524 		return (EBUSY);
1525 	}
1526 	up->u_tun_func = f;
1527 	up->u_icmp_func = i;
1528 	up->u_tun_ctx = ctx;
1529 	INP_WUNLOCK(inp);
1530 	return (0);
1531 }
1532 
1533 #ifdef INET
1534 static int
1535 udp_bind(struct socket *so, struct sockaddr *nam, struct thread *td)
1536 {
1537 	struct inpcb *inp;
1538 	struct inpcbinfo *pcbinfo;
1539 	struct sockaddr_in *sinp;
1540 	int error;
1541 
1542 	pcbinfo = udp_get_inpcbinfo(so->so_proto->pr_protocol);
1543 	inp = sotoinpcb(so);
1544 	KASSERT(inp != NULL, ("udp_bind: inp == NULL"));
1545 
1546 	sinp = (struct sockaddr_in *)nam;
1547 	if (nam->sa_family != AF_INET) {
1548 		/*
1549 		 * Preserve compatibility with old programs.
1550 		 */
1551 		if (nam->sa_family != AF_UNSPEC ||
1552 		    nam->sa_len < offsetof(struct sockaddr_in, sin_zero) ||
1553 		    sinp->sin_addr.s_addr != INADDR_ANY)
1554 			return (EAFNOSUPPORT);
1555 		nam->sa_family = AF_INET;
1556 	}
1557 	if (nam->sa_len != sizeof(struct sockaddr_in))
1558 		return (EINVAL);
1559 
1560 	INP_WLOCK(inp);
1561 	INP_HASH_WLOCK(pcbinfo);
1562 	error = in_pcbbind(inp, sinp, td->td_ucred);
1563 	INP_HASH_WUNLOCK(pcbinfo);
1564 	INP_WUNLOCK(inp);
1565 	return (error);
1566 }
1567 
1568 static void
1569 udp_close(struct socket *so)
1570 {
1571 	struct inpcb *inp;
1572 	struct inpcbinfo *pcbinfo;
1573 
1574 	pcbinfo = udp_get_inpcbinfo(so->so_proto->pr_protocol);
1575 	inp = sotoinpcb(so);
1576 	KASSERT(inp != NULL, ("udp_close: inp == NULL"));
1577 	INP_WLOCK(inp);
1578 	if (inp->inp_faddr.s_addr != INADDR_ANY) {
1579 		INP_HASH_WLOCK(pcbinfo);
1580 		in_pcbdisconnect(inp);
1581 		INP_HASH_WUNLOCK(pcbinfo);
1582 		soisdisconnected(so);
1583 	}
1584 	INP_WUNLOCK(inp);
1585 }
1586 
1587 static int
1588 udp_connect(struct socket *so, struct sockaddr *nam, struct thread *td)
1589 {
1590 	struct epoch_tracker et;
1591 	struct inpcb *inp;
1592 	struct inpcbinfo *pcbinfo;
1593 	struct sockaddr_in *sin;
1594 	int error;
1595 
1596 	pcbinfo = udp_get_inpcbinfo(so->so_proto->pr_protocol);
1597 	inp = sotoinpcb(so);
1598 	KASSERT(inp != NULL, ("udp_connect: inp == NULL"));
1599 
1600 	sin = (struct sockaddr_in *)nam;
1601 	if (sin->sin_family != AF_INET)
1602 		return (EAFNOSUPPORT);
1603 	if (sin->sin_len != sizeof(*sin))
1604 		return (EINVAL);
1605 
1606 	INP_WLOCK(inp);
1607 	if (inp->inp_faddr.s_addr != INADDR_ANY) {
1608 		INP_WUNLOCK(inp);
1609 		return (EISCONN);
1610 	}
1611 	error = prison_remote_ip4(td->td_ucred, &sin->sin_addr);
1612 	if (error != 0) {
1613 		INP_WUNLOCK(inp);
1614 		return (error);
1615 	}
1616 	NET_EPOCH_ENTER(et);
1617 	INP_HASH_WLOCK(pcbinfo);
1618 	error = in_pcbconnect(inp, sin, td->td_ucred, true);
1619 	INP_HASH_WUNLOCK(pcbinfo);
1620 	NET_EPOCH_EXIT(et);
1621 	if (error == 0)
1622 		soisconnected(so);
1623 	INP_WUNLOCK(inp);
1624 	return (error);
1625 }
1626 
1627 static void
1628 udp_detach(struct socket *so)
1629 {
1630 	struct inpcb *inp;
1631 
1632 	inp = sotoinpcb(so);
1633 	KASSERT(inp != NULL, ("udp_detach: inp == NULL"));
1634 	KASSERT(inp->inp_faddr.s_addr == INADDR_ANY,
1635 	    ("udp_detach: not disconnected"));
1636 	INP_WLOCK(inp);
1637 	in_pcbdetach(inp);
1638 	in_pcbfree(inp);
1639 }
1640 
1641 int
1642 udp_disconnect(struct socket *so)
1643 {
1644 	struct inpcb *inp;
1645 	struct inpcbinfo *pcbinfo;
1646 
1647 	pcbinfo = udp_get_inpcbinfo(so->so_proto->pr_protocol);
1648 	inp = sotoinpcb(so);
1649 	KASSERT(inp != NULL, ("udp_disconnect: inp == NULL"));
1650 	INP_WLOCK(inp);
1651 	if (inp->inp_faddr.s_addr == INADDR_ANY) {
1652 		INP_WUNLOCK(inp);
1653 		return (ENOTCONN);
1654 	}
1655 	INP_HASH_WLOCK(pcbinfo);
1656 	in_pcbdisconnect(inp);
1657 	INP_HASH_WUNLOCK(pcbinfo);
1658 	SOCK_LOCK(so);
1659 	so->so_state &= ~SS_ISCONNECTED;		/* XXX */
1660 	SOCK_UNLOCK(so);
1661 	INP_WUNLOCK(inp);
1662 	return (0);
1663 }
1664 #endif /* INET */
1665 
1666 int
1667 udp_shutdown(struct socket *so)
1668 {
1669 	struct inpcb *inp;
1670 
1671 	inp = sotoinpcb(so);
1672 	KASSERT(inp != NULL, ("udp_shutdown: inp == NULL"));
1673 	INP_WLOCK(inp);
1674 	socantsendmore(so);
1675 	INP_WUNLOCK(inp);
1676 	return (0);
1677 }
1678 
1679 #ifdef INET
1680 #define	UDP_PROTOSW							\
1681 	.pr_type =		SOCK_DGRAM,				\
1682 	.pr_flags =		PR_ATOMIC | PR_ADDR | PR_CAPATTACH,	\
1683 	.pr_ctloutput =		udp_ctloutput,				\
1684 	.pr_abort =		udp_abort,				\
1685 	.pr_attach =		udp_attach,				\
1686 	.pr_bind =		udp_bind,				\
1687 	.pr_connect =		udp_connect,				\
1688 	.pr_control =		in_control,				\
1689 	.pr_detach =		udp_detach,				\
1690 	.pr_disconnect =	udp_disconnect,				\
1691 	.pr_peeraddr =		in_getpeeraddr,				\
1692 	.pr_send =		udp_send,				\
1693 	.pr_soreceive =		soreceive_dgram,			\
1694 	.pr_sosend =		sosend_dgram,				\
1695 	.pr_shutdown =		udp_shutdown,				\
1696 	.pr_sockaddr =		in_getsockaddr,				\
1697 	.pr_sosetlabel =	in_pcbsosetlabel,			\
1698 	.pr_close =		udp_close
1699 
1700 struct protosw udp_protosw = {
1701 	.pr_protocol =		IPPROTO_UDP,
1702 	UDP_PROTOSW
1703 };
1704 
1705 struct protosw udplite_protosw = {
1706 	.pr_protocol =		IPPROTO_UDPLITE,
1707 	UDP_PROTOSW
1708 };
1709 
1710 static void
1711 udp_init(void *arg __unused)
1712 {
1713 
1714 	IPPROTO_REGISTER(IPPROTO_UDP, udp_input, udp_ctlinput);
1715 	IPPROTO_REGISTER(IPPROTO_UDPLITE, udp_input, udplite_ctlinput);
1716 }
1717 SYSINIT(udp_init, SI_SUB_PROTO_DOMAIN, SI_ORDER_THIRD, udp_init, NULL);
1718 #endif /* INET */
1719