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