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