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