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