xref: /freebsd/sys/netinet/udp_usrreq.c (revision aa79fe245de7616cda41b69a296a5ce209c95c45)
1 /*-
2  * Copyright (c) 1982, 1986, 1988, 1990, 1993, 1995
3  *	The Regents of the University of California.
4  * Copyright (c) 2008 Robert N. M. Watson
5  * All rights reserved.
6  *
7  * Redistribution and use in source and binary forms, with or without
8  * modification, are permitted provided that the following conditions
9  * are met:
10  * 1. Redistributions of source code must retain the above copyright
11  *    notice, this list of conditions and the following disclaimer.
12  * 2. Redistributions in binary form must reproduce the above copyright
13  *    notice, this list of conditions and the following disclaimer in the
14  *    documentation and/or other materials provided with the distribution.
15  * 4. Neither the name of the University nor the names of its contributors
16  *    may be used to endorse or promote products derived from this software
17  *    without specific prior written permission.
18  *
19  * THIS SOFTWARE IS PROVIDED BY THE REGENTS AND CONTRIBUTORS ``AS IS'' AND
20  * ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
21  * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE
22  * ARE DISCLAIMED.  IN NO EVENT SHALL THE REGENTS OR CONTRIBUTORS BE LIABLE
23  * FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL
24  * DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS
25  * OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION)
26  * HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT
27  * LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY
28  * OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF
29  * SUCH DAMAGE.
30  *
31  *	@(#)udp_usrreq.c	8.6 (Berkeley) 5/23/95
32  */
33 
34 #include <sys/cdefs.h>
35 __FBSDID("$FreeBSD$");
36 
37 #include "opt_ipfw.h"
38 #include "opt_inet6.h"
39 #include "opt_ipsec.h"
40 
41 #include <sys/param.h>
42 #include <sys/domain.h>
43 #include <sys/eventhandler.h>
44 #include <sys/jail.h>
45 #include <sys/kernel.h>
46 #include <sys/lock.h>
47 #include <sys/malloc.h>
48 #include <sys/mbuf.h>
49 #include <sys/priv.h>
50 #include <sys/proc.h>
51 #include <sys/protosw.h>
52 #include <sys/signalvar.h>
53 #include <sys/socket.h>
54 #include <sys/socketvar.h>
55 #include <sys/sx.h>
56 #include <sys/sysctl.h>
57 #include <sys/syslog.h>
58 #include <sys/systm.h>
59 #include <sys/vimage.h>
60 
61 #include <vm/uma.h>
62 
63 #include <net/if.h>
64 #include <net/route.h>
65 
66 #include <netinet/in.h>
67 #include <netinet/in_pcb.h>
68 #include <netinet/in_systm.h>
69 #include <netinet/in_var.h>
70 #include <netinet/ip.h>
71 #ifdef INET6
72 #include <netinet/ip6.h>
73 #endif
74 #include <netinet/ip_icmp.h>
75 #include <netinet/icmp_var.h>
76 #include <netinet/ip_var.h>
77 #include <netinet/ip_options.h>
78 #ifdef INET6
79 #include <netinet6/ip6_var.h>
80 #endif
81 #include <netinet/udp.h>
82 #include <netinet/udp_var.h>
83 #include <netinet/vinet.h>
84 
85 #ifdef IPSEC
86 #include <netipsec/ipsec.h>
87 #include <netipsec/esp.h>
88 #endif
89 
90 #include <machine/in_cksum.h>
91 
92 #include <security/mac/mac_framework.h>
93 
94 /*
95  * UDP protocol implementation.
96  * Per RFC 768, August, 1980.
97  */
98 
99 #ifdef VIMAGE_GLOBALS
100 int	udp_blackhole;
101 #endif
102 
103 /*
104  * BSD 4.2 defaulted the udp checksum to be off.  Turning off udp checksums
105  * removes the only data integrity mechanism for packets and malformed
106  * packets that would otherwise be discarded due to bad checksums, and may
107  * cause problems (especially for NFS data blocks).
108  */
109 static int	udp_cksum = 1;
110 SYSCTL_INT(_net_inet_udp, UDPCTL_CHECKSUM, checksum, CTLFLAG_RW, &udp_cksum,
111     0, "compute udp checksum");
112 
113 int	udp_log_in_vain = 0;
114 SYSCTL_INT(_net_inet_udp, OID_AUTO, log_in_vain, CTLFLAG_RW,
115     &udp_log_in_vain, 0, "Log all incoming UDP packets");
116 
117 SYSCTL_V_INT(V_NET, vnet_inet, _net_inet_udp, OID_AUTO, blackhole,
118     CTLFLAG_RW, udp_blackhole, 0,
119     "Do not send port unreachables for refused connects");
120 
121 u_long	udp_sendspace = 9216;		/* really max datagram size */
122 					/* 40 1K datagrams */
123 SYSCTL_ULONG(_net_inet_udp, UDPCTL_MAXDGRAM, maxdgram, CTLFLAG_RW,
124     &udp_sendspace, 0, "Maximum outgoing UDP datagram size");
125 
126 u_long	udp_recvspace = 40 * (1024 +
127 #ifdef INET6
128 				      sizeof(struct sockaddr_in6)
129 #else
130 				      sizeof(struct sockaddr_in)
131 #endif
132 				      );
133 
134 SYSCTL_ULONG(_net_inet_udp, UDPCTL_RECVSPACE, recvspace, CTLFLAG_RW,
135     &udp_recvspace, 0, "Maximum space for incoming UDP datagrams");
136 
137 #ifdef VIMAGE_GLOBALS
138 struct inpcbhead	udb;		/* from udp_var.h */
139 struct inpcbinfo	udbinfo;
140 static uma_zone_t	udpcb_zone;
141 struct udpstat		udpstat;	/* from udp_var.h */
142 #endif
143 
144 #ifndef UDBHASHSIZE
145 #define	UDBHASHSIZE	128
146 #endif
147 
148 SYSCTL_V_STRUCT(V_NET, vnet_inet, _net_inet_udp, UDPCTL_STATS, stats,
149     CTLFLAG_RW, udpstat, udpstat,
150     "UDP statistics (struct udpstat, netinet/udp_var.h)");
151 
152 static void	udp_detach(struct socket *so);
153 static int	udp_output(struct inpcb *, struct mbuf *, struct sockaddr *,
154 		    struct mbuf *, struct thread *);
155 #ifdef IPSEC
156 #ifdef IPSEC_NAT_T
157 #define	UF_ESPINUDP_ALL	(UF_ESPINUDP_NON_IKE|UF_ESPINUDP)
158 #ifdef INET
159 static struct mbuf *udp4_espdecap(struct inpcb *, struct mbuf *, int);
160 #endif
161 #endif /* IPSEC_NAT_T */
162 #endif /* IPSEC */
163 
164 static void
165 udp_zone_change(void *tag)
166 {
167 	INIT_VNET_INET(curvnet);
168 
169 	uma_zone_set_max(V_udbinfo.ipi_zone, maxsockets);
170 	uma_zone_set_max(V_udpcb_zone, maxsockets);
171 }
172 
173 static int
174 udp_inpcb_init(void *mem, int size, int flags)
175 {
176 	struct inpcb *inp;
177 
178 	inp = mem;
179 	INP_LOCK_INIT(inp, "inp", "udpinp");
180 	return (0);
181 }
182 
183 void
184 udp_init(void)
185 {
186 	INIT_VNET_INET(curvnet);
187 
188 	V_udp_blackhole = 0;
189 
190 	INP_INFO_LOCK_INIT(&V_udbinfo, "udp");
191 	LIST_INIT(&V_udb);
192 #ifdef VIMAGE
193 	V_udbinfo.ipi_vnet = curvnet;
194 #endif
195 	V_udbinfo.ipi_listhead = &V_udb;
196 	V_udbinfo.ipi_hashbase = hashinit(UDBHASHSIZE, M_PCB,
197 	    &V_udbinfo.ipi_hashmask);
198 	V_udbinfo.ipi_porthashbase = hashinit(UDBHASHSIZE, M_PCB,
199 	    &V_udbinfo.ipi_porthashmask);
200 	V_udbinfo.ipi_zone = uma_zcreate("udp_inpcb", sizeof(struct inpcb),
201 	    NULL, NULL, udp_inpcb_init, NULL, UMA_ALIGN_PTR, UMA_ZONE_NOFREE);
202 	uma_zone_set_max(V_udbinfo.ipi_zone, maxsockets);
203 
204 	V_udpcb_zone = uma_zcreate("udpcb", sizeof(struct udpcb),
205 	    NULL, NULL, NULL, NULL, UMA_ALIGN_PTR, UMA_ZONE_NOFREE);
206 	uma_zone_set_max(V_udpcb_zone, maxsockets);
207 
208 	EVENTHANDLER_REGISTER(maxsockets_change, udp_zone_change, NULL,
209 	    EVENTHANDLER_PRI_ANY);
210 }
211 
212 int
213 udp_newudpcb(struct inpcb *inp)
214 {
215 	INIT_VNET_INET(curvnet);
216 	struct udpcb *up;
217 
218 	up = uma_zalloc(V_udpcb_zone, M_NOWAIT | M_ZERO);
219 	if (up == NULL)
220 		return (ENOBUFS);
221 	inp->inp_ppcb = up;
222 	return (0);
223 }
224 
225 void
226 udp_discardcb(struct udpcb *up)
227 {
228 	INIT_VNET_INET(curvnet);
229 
230 	uma_zfree(V_udpcb_zone, up);
231 }
232 
233 #ifdef VIMAGE
234 void
235 udp_destroy(void)
236 {
237 	INIT_VNET_INET(curvnet);
238 
239 	hashdestroy(V_udbinfo.ipi_hashbase, M_PCB,
240 	    V_udbinfo.ipi_hashmask);
241 	hashdestroy(V_udbinfo.ipi_porthashbase, M_PCB,
242 	    V_udbinfo.ipi_porthashmask);
243 	INP_INFO_LOCK_DESTROY(&V_udbinfo);
244 }
245 #endif
246 
247 /*
248  * Subroutine of udp_input(), which appends the provided mbuf chain to the
249  * passed pcb/socket.  The caller must provide a sockaddr_in via udp_in that
250  * contains the source address.  If the socket ends up being an IPv6 socket,
251  * udp_append() will convert to a sockaddr_in6 before passing the address
252  * into the socket code.
253  */
254 static void
255 udp_append(struct inpcb *inp, struct ip *ip, struct mbuf *n, int off,
256     struct sockaddr_in *udp_in)
257 {
258 	struct sockaddr *append_sa;
259 	struct socket *so;
260 	struct mbuf *opts = 0;
261 #ifdef INET6
262 	struct sockaddr_in6 udp_in6;
263 #endif
264 #ifdef IPSEC
265 #ifdef IPSEC_NAT_T
266 #ifdef INET
267 	struct udpcb *up;
268 #endif
269 #endif
270 #endif
271 
272 	INP_RLOCK_ASSERT(inp);
273 
274 #ifdef IPSEC
275 	/* Check AH/ESP integrity. */
276 	if (ipsec4_in_reject(n, inp)) {
277 		INIT_VNET_IPSEC(curvnet);
278 		m_freem(n);
279 		V_ipsec4stat.in_polvio++;
280 		return;
281 	}
282 #ifdef IPSEC_NAT_T
283 #ifdef INET
284 	up = intoudpcb(inp);
285 	KASSERT(up != NULL, ("%s: udpcb NULL", __func__));
286 	if (up->u_flags & UF_ESPINUDP_ALL) {	/* IPSec UDP encaps. */
287 		n = udp4_espdecap(inp, n, off);
288 		if (n == NULL)				/* Consumed. */
289 			return;
290 	}
291 #endif /* INET */
292 #endif /* IPSEC_NAT_T */
293 #endif /* IPSEC */
294 #ifdef MAC
295 	if (mac_inpcb_check_deliver(inp, n) != 0) {
296 		m_freem(n);
297 		return;
298 	}
299 #endif
300 	if (inp->inp_flags & INP_CONTROLOPTS ||
301 	    inp->inp_socket->so_options & (SO_TIMESTAMP | SO_BINTIME)) {
302 #ifdef INET6
303 		if (inp->inp_vflag & INP_IPV6)
304 			(void)ip6_savecontrol_v4(inp, n, &opts, NULL);
305 		else
306 #endif
307 			ip_savecontrol(inp, &opts, ip, n);
308 	}
309 #ifdef INET6
310 	if (inp->inp_vflag & INP_IPV6) {
311 		bzero(&udp_in6, sizeof(udp_in6));
312 		udp_in6.sin6_len = sizeof(udp_in6);
313 		udp_in6.sin6_family = AF_INET6;
314 		in6_sin_2_v4mapsin6(udp_in, &udp_in6);
315 		append_sa = (struct sockaddr *)&udp_in6;
316 	} else
317 #endif
318 		append_sa = (struct sockaddr *)udp_in;
319 	m_adj(n, off);
320 
321 	so = inp->inp_socket;
322 	SOCKBUF_LOCK(&so->so_rcv);
323 	if (sbappendaddr_locked(&so->so_rcv, append_sa, n, opts) == 0) {
324 		INIT_VNET_INET(so->so_vnet);
325 		SOCKBUF_UNLOCK(&so->so_rcv);
326 		m_freem(n);
327 		if (opts)
328 			m_freem(opts);
329 		UDPSTAT_INC(udps_fullsock);
330 	} else
331 		sorwakeup_locked(so);
332 }
333 
334 void
335 udp_input(struct mbuf *m, int off)
336 {
337 	INIT_VNET_INET(curvnet);
338 	int iphlen = off;
339 	struct ip *ip;
340 	struct udphdr *uh;
341 	struct ifnet *ifp;
342 	struct inpcb *inp;
343 	struct udpcb *up;
344 	int len;
345 	struct ip save_ip;
346 	struct sockaddr_in udp_in;
347 #ifdef IPFIREWALL_FORWARD
348 	struct m_tag *fwd_tag;
349 #endif
350 
351 	ifp = m->m_pkthdr.rcvif;
352 	UDPSTAT_INC(udps_ipackets);
353 
354 	/*
355 	 * Strip IP options, if any; should skip this, make available to
356 	 * user, and use on returned packets, but we don't yet have a way to
357 	 * check the checksum with options still present.
358 	 */
359 	if (iphlen > sizeof (struct ip)) {
360 		ip_stripoptions(m, (struct mbuf *)0);
361 		iphlen = sizeof(struct ip);
362 	}
363 
364 	/*
365 	 * Get IP and UDP header together in first mbuf.
366 	 */
367 	ip = mtod(m, struct ip *);
368 	if (m->m_len < iphlen + sizeof(struct udphdr)) {
369 		if ((m = m_pullup(m, iphlen + sizeof(struct udphdr))) == 0) {
370 			UDPSTAT_INC(udps_hdrops);
371 			return;
372 		}
373 		ip = mtod(m, struct ip *);
374 	}
375 	uh = (struct udphdr *)((caddr_t)ip + iphlen);
376 
377 	/*
378 	 * Destination port of 0 is illegal, based on RFC768.
379 	 */
380 	if (uh->uh_dport == 0)
381 		goto badunlocked;
382 
383 	/*
384 	 * Construct sockaddr format source address.  Stuff source address
385 	 * and datagram in user buffer.
386 	 */
387 	bzero(&udp_in, sizeof(udp_in));
388 	udp_in.sin_len = sizeof(udp_in);
389 	udp_in.sin_family = AF_INET;
390 	udp_in.sin_port = uh->uh_sport;
391 	udp_in.sin_addr = ip->ip_src;
392 
393 	/*
394 	 * Make mbuf data length reflect UDP length.  If not enough data to
395 	 * reflect UDP length, drop.
396 	 */
397 	len = ntohs((u_short)uh->uh_ulen);
398 	if (ip->ip_len != len) {
399 		if (len > ip->ip_len || len < sizeof(struct udphdr)) {
400 			UDPSTAT_INC(udps_badlen);
401 			goto badunlocked;
402 		}
403 		m_adj(m, len - ip->ip_len);
404 		/* ip->ip_len = len; */
405 	}
406 
407 	/*
408 	 * Save a copy of the IP header in case we want restore it for
409 	 * sending an ICMP error message in response.
410 	 */
411 	if (!V_udp_blackhole)
412 		save_ip = *ip;
413 	else
414 		memset(&save_ip, 0, sizeof(save_ip));
415 
416 	/*
417 	 * Checksum extended UDP header and data.
418 	 */
419 	if (uh->uh_sum) {
420 		u_short uh_sum;
421 
422 		if (m->m_pkthdr.csum_flags & CSUM_DATA_VALID) {
423 			if (m->m_pkthdr.csum_flags & CSUM_PSEUDO_HDR)
424 				uh_sum = m->m_pkthdr.csum_data;
425 			else
426 				uh_sum = in_pseudo(ip->ip_src.s_addr,
427 				    ip->ip_dst.s_addr, htonl((u_short)len +
428 				    m->m_pkthdr.csum_data + IPPROTO_UDP));
429 			uh_sum ^= 0xffff;
430 		} else {
431 			char b[9];
432 
433 			bcopy(((struct ipovly *)ip)->ih_x1, b, 9);
434 			bzero(((struct ipovly *)ip)->ih_x1, 9);
435 			((struct ipovly *)ip)->ih_len = uh->uh_ulen;
436 			uh_sum = in_cksum(m, len + sizeof (struct ip));
437 			bcopy(b, ((struct ipovly *)ip)->ih_x1, 9);
438 		}
439 		if (uh_sum) {
440 			UDPSTAT_INC(udps_badsum);
441 			m_freem(m);
442 			return;
443 		}
444 	} else
445 		UDPSTAT_INC(udps_nosum);
446 
447 #ifdef IPFIREWALL_FORWARD
448 	/*
449 	 * Grab info from PACKET_TAG_IPFORWARD tag prepended to the chain.
450 	 */
451 	fwd_tag = m_tag_find(m, PACKET_TAG_IPFORWARD, NULL);
452 	if (fwd_tag != NULL) {
453 		struct sockaddr_in *next_hop;
454 
455 		/*
456 		 * Do the hack.
457 		 */
458 		next_hop = (struct sockaddr_in *)(fwd_tag + 1);
459 		ip->ip_dst = next_hop->sin_addr;
460 		uh->uh_dport = ntohs(next_hop->sin_port);
461 
462 		/*
463 		 * Remove the tag from the packet.  We don't need it anymore.
464 		 */
465 		m_tag_delete(m, fwd_tag);
466 	}
467 #endif
468 
469 	INP_INFO_RLOCK(&V_udbinfo);
470 	if (IN_MULTICAST(ntohl(ip->ip_dst.s_addr)) ||
471 	    in_broadcast(ip->ip_dst, ifp)) {
472 		struct inpcb *last;
473 		struct ip_moptions *imo;
474 
475 		last = NULL;
476 		LIST_FOREACH(inp, &V_udb, inp_list) {
477 			if (inp->inp_lport != uh->uh_dport)
478 				continue;
479 #ifdef INET6
480 			if ((inp->inp_vflag & INP_IPV4) == 0)
481 				continue;
482 #endif
483 			if (inp->inp_laddr.s_addr != INADDR_ANY &&
484 			    inp->inp_laddr.s_addr != ip->ip_dst.s_addr)
485 				continue;
486 			if (inp->inp_faddr.s_addr != INADDR_ANY &&
487 			    inp->inp_faddr.s_addr != ip->ip_src.s_addr)
488 				continue;
489 			if (inp->inp_fport != 0 &&
490 			    inp->inp_fport != uh->uh_sport)
491 				continue;
492 
493 			INP_RLOCK(inp);
494 
495 			/*
496 			 * Handle socket delivery policy for any-source
497 			 * and source-specific multicast. [RFC3678]
498 			 */
499 			imo = inp->inp_moptions;
500 			if (IN_MULTICAST(ntohl(ip->ip_dst.s_addr)) &&
501 			    imo != NULL) {
502 				struct sockaddr_in	 group;
503 				int			 blocked;
504 
505 				bzero(&group, sizeof(struct sockaddr_in));
506 				group.sin_len = sizeof(struct sockaddr_in);
507 				group.sin_family = AF_INET;
508 				group.sin_addr = ip->ip_dst;
509 
510 				blocked = imo_multi_filter(imo, ifp,
511 					(struct sockaddr *)&group,
512 					(struct sockaddr *)&udp_in);
513 				if (blocked != MCAST_PASS) {
514 					if (blocked == MCAST_NOTGMEMBER)
515 						IPSTAT_INC(ips_notmember);
516 					if (blocked == MCAST_NOTSMEMBER ||
517 					    blocked == MCAST_MUTED)
518 						UDPSTAT_INC(udps_filtermcast);
519 					INP_RUNLOCK(inp);
520 					continue;
521 				}
522 			}
523 			if (last != NULL) {
524 				struct mbuf *n;
525 
526 				n = m_copy(m, 0, M_COPYALL);
527 				up = intoudpcb(last);
528 				if (up->u_tun_func == NULL) {
529 					if (n != NULL)
530 						udp_append(last,
531 						    ip, n,
532 						    iphlen +
533 						    sizeof(struct udphdr),
534 						    &udp_in);
535 				} else {
536 					/*
537 					 * Engage the tunneling protocol we
538 					 * will have to leave the info_lock
539 					 * up, since we are hunting through
540 					 * multiple UDP's.
541 					 */
542 
543 					(*up->u_tun_func)(n, iphlen, last);
544 				}
545 				INP_RUNLOCK(last);
546 			}
547 			last = inp;
548 			/*
549 			 * Don't look for additional matches if this one does
550 			 * not have either the SO_REUSEPORT or SO_REUSEADDR
551 			 * socket options set.  This heuristic avoids
552 			 * searching through all pcbs in the common case of a
553 			 * non-shared port.  It assumes that an application
554 			 * will never clear these options after setting them.
555 			 */
556 			if ((last->inp_socket->so_options &
557 			    (SO_REUSEPORT|SO_REUSEADDR)) == 0)
558 				break;
559 		}
560 
561 		if (last == NULL) {
562 			/*
563 			 * No matching pcb found; discard datagram.  (No need
564 			 * to send an ICMP Port Unreachable for a broadcast
565 			 * or multicast datgram.)
566 			 */
567 			UDPSTAT_INC(udps_noportbcast);
568 			goto badheadlocked;
569 		}
570 		up = intoudpcb(last);
571 		if (up->u_tun_func == NULL) {
572 			udp_append(last, ip, m, iphlen + sizeof(struct udphdr),
573 			    &udp_in);
574 		} else {
575 			/*
576 			 * Engage the tunneling protocol.
577 			 */
578 			(*up->u_tun_func)(m, iphlen, last);
579 		}
580 		INP_RUNLOCK(last);
581 		INP_INFO_RUNLOCK(&V_udbinfo);
582 		return;
583 	}
584 
585 	/*
586 	 * Locate pcb for datagram.
587 	 */
588 	inp = in_pcblookup_hash(&V_udbinfo, ip->ip_src, uh->uh_sport,
589 	    ip->ip_dst, uh->uh_dport, 1, ifp);
590 	if (inp == NULL) {
591 		if (udp_log_in_vain) {
592 			char buf[4*sizeof "123"];
593 
594 			strcpy(buf, inet_ntoa(ip->ip_dst));
595 			log(LOG_INFO,
596 			    "Connection attempt to UDP %s:%d from %s:%d\n",
597 			    buf, ntohs(uh->uh_dport), inet_ntoa(ip->ip_src),
598 			    ntohs(uh->uh_sport));
599 		}
600 		UDPSTAT_INC(udps_noport);
601 		if (m->m_flags & (M_BCAST | M_MCAST)) {
602 			UDPSTAT_INC(udps_noportbcast);
603 			goto badheadlocked;
604 		}
605 		if (V_udp_blackhole)
606 			goto badheadlocked;
607 		if (badport_bandlim(BANDLIM_ICMP_UNREACH) < 0)
608 			goto badheadlocked;
609 		*ip = save_ip;
610 		ip->ip_len += iphlen;
611 		icmp_error(m, ICMP_UNREACH, ICMP_UNREACH_PORT, 0, 0);
612 		INP_INFO_RUNLOCK(&V_udbinfo);
613 		return;
614 	}
615 
616 	/*
617 	 * Check the minimum TTL for socket.
618 	 */
619 	INP_RLOCK(inp);
620 	INP_INFO_RUNLOCK(&V_udbinfo);
621 	if (inp->inp_ip_minttl && inp->inp_ip_minttl > ip->ip_ttl) {
622 		INP_RUNLOCK(inp);
623 		goto badunlocked;
624 	}
625 	up = intoudpcb(inp);
626 	if (up->u_tun_func == NULL) {
627 		udp_append(inp, ip, m, iphlen + sizeof(struct udphdr), &udp_in);
628 	} else {
629 		/*
630 		 * Engage the tunneling protocol.
631 		 */
632 
633 		(*up->u_tun_func)(m, iphlen, inp);
634 	}
635 	INP_RUNLOCK(inp);
636 	return;
637 
638 badheadlocked:
639 	if (inp)
640 		INP_RUNLOCK(inp);
641 	INP_INFO_RUNLOCK(&V_udbinfo);
642 badunlocked:
643 	m_freem(m);
644 }
645 
646 /*
647  * Notify a udp user of an asynchronous error; just wake up so that they can
648  * collect error status.
649  */
650 struct inpcb *
651 udp_notify(struct inpcb *inp, int errno)
652 {
653 
654 	/*
655 	 * While udp_ctlinput() always calls udp_notify() with a read lock
656 	 * when invoking it directly, in_pcbnotifyall() currently uses write
657 	 * locks due to sharing code with TCP.  For now, accept either a read
658 	 * or a write lock, but a read lock is sufficient.
659 	 */
660 	INP_LOCK_ASSERT(inp);
661 
662 	inp->inp_socket->so_error = errno;
663 	sorwakeup(inp->inp_socket);
664 	sowwakeup(inp->inp_socket);
665 	return (inp);
666 }
667 
668 void
669 udp_ctlinput(int cmd, struct sockaddr *sa, void *vip)
670 {
671 	INIT_VNET_INET(curvnet);
672 	struct ip *ip = vip;
673 	struct udphdr *uh;
674 	struct in_addr faddr;
675 	struct inpcb *inp;
676 
677 	faddr = ((struct sockaddr_in *)sa)->sin_addr;
678 	if (sa->sa_family != AF_INET || faddr.s_addr == INADDR_ANY)
679 		return;
680 
681 	/*
682 	 * Redirects don't need to be handled up here.
683 	 */
684 	if (PRC_IS_REDIRECT(cmd))
685 		return;
686 
687 	/*
688 	 * Hostdead is ugly because it goes linearly through all PCBs.
689 	 *
690 	 * XXX: We never get this from ICMP, otherwise it makes an excellent
691 	 * DoS attack on machines with many connections.
692 	 */
693 	if (cmd == PRC_HOSTDEAD)
694 		ip = NULL;
695 	else if ((unsigned)cmd >= PRC_NCMDS || inetctlerrmap[cmd] == 0)
696 		return;
697 	if (ip != NULL) {
698 		uh = (struct udphdr *)((caddr_t)ip + (ip->ip_hl << 2));
699 		INP_INFO_RLOCK(&V_udbinfo);
700 		inp = in_pcblookup_hash(&V_udbinfo, faddr, uh->uh_dport,
701 		    ip->ip_src, uh->uh_sport, 0, NULL);
702 		if (inp != NULL) {
703 			INP_RLOCK(inp);
704 			if (inp->inp_socket != NULL) {
705 				udp_notify(inp, inetctlerrmap[cmd]);
706 			}
707 			INP_RUNLOCK(inp);
708 		}
709 		INP_INFO_RUNLOCK(&V_udbinfo);
710 	} else
711 		in_pcbnotifyall(&V_udbinfo, faddr, inetctlerrmap[cmd],
712 		    udp_notify);
713 }
714 
715 static int
716 udp_pcblist(SYSCTL_HANDLER_ARGS)
717 {
718 	INIT_VNET_INET(curvnet);
719 	int error, i, n;
720 	struct inpcb *inp, **inp_list;
721 	inp_gen_t gencnt;
722 	struct xinpgen xig;
723 
724 	/*
725 	 * The process of preparing the PCB list is too time-consuming and
726 	 * resource-intensive to repeat twice on every request.
727 	 */
728 	if (req->oldptr == 0) {
729 		n = V_udbinfo.ipi_count;
730 		req->oldidx = 2 * (sizeof xig)
731 			+ (n + n/8) * sizeof(struct xinpcb);
732 		return (0);
733 	}
734 
735 	if (req->newptr != 0)
736 		return (EPERM);
737 
738 	/*
739 	 * OK, now we're committed to doing something.
740 	 */
741 	INP_INFO_RLOCK(&V_udbinfo);
742 	gencnt = V_udbinfo.ipi_gencnt;
743 	n = V_udbinfo.ipi_count;
744 	INP_INFO_RUNLOCK(&V_udbinfo);
745 
746 	error = sysctl_wire_old_buffer(req, 2 * (sizeof xig)
747 		+ n * sizeof(struct xinpcb));
748 	if (error != 0)
749 		return (error);
750 
751 	xig.xig_len = sizeof xig;
752 	xig.xig_count = n;
753 	xig.xig_gen = gencnt;
754 	xig.xig_sogen = so_gencnt;
755 	error = SYSCTL_OUT(req, &xig, sizeof xig);
756 	if (error)
757 		return (error);
758 
759 	inp_list = malloc(n * sizeof *inp_list, M_TEMP, M_WAITOK);
760 	if (inp_list == 0)
761 		return (ENOMEM);
762 
763 	INP_INFO_RLOCK(&V_udbinfo);
764 	for (inp = LIST_FIRST(V_udbinfo.ipi_listhead), i = 0; inp && i < n;
765 	     inp = LIST_NEXT(inp, inp_list)) {
766 		INP_RLOCK(inp);
767 		if (inp->inp_gencnt <= gencnt &&
768 		    cr_canseeinpcb(req->td->td_ucred, inp) == 0)
769 			inp_list[i++] = inp;
770 		INP_RUNLOCK(inp);
771 	}
772 	INP_INFO_RUNLOCK(&V_udbinfo);
773 	n = i;
774 
775 	error = 0;
776 	for (i = 0; i < n; i++) {
777 		inp = inp_list[i];
778 		INP_RLOCK(inp);
779 		if (inp->inp_gencnt <= gencnt) {
780 			struct xinpcb xi;
781 			bzero(&xi, sizeof(xi));
782 			xi.xi_len = sizeof xi;
783 			/* XXX should avoid extra copy */
784 			bcopy(inp, &xi.xi_inp, sizeof *inp);
785 			if (inp->inp_socket)
786 				sotoxsocket(inp->inp_socket, &xi.xi_socket);
787 			xi.xi_inp.inp_gencnt = inp->inp_gencnt;
788 			INP_RUNLOCK(inp);
789 			error = SYSCTL_OUT(req, &xi, sizeof xi);
790 		} else
791 			INP_RUNLOCK(inp);
792 	}
793 	if (!error) {
794 		/*
795 		 * Give the user an updated idea of our state.  If the
796 		 * generation differs from what we told her before, she knows
797 		 * that something happened while we were processing this
798 		 * request, and it might be necessary to retry.
799 		 */
800 		INP_INFO_RLOCK(&V_udbinfo);
801 		xig.xig_gen = V_udbinfo.ipi_gencnt;
802 		xig.xig_sogen = so_gencnt;
803 		xig.xig_count = V_udbinfo.ipi_count;
804 		INP_INFO_RUNLOCK(&V_udbinfo);
805 		error = SYSCTL_OUT(req, &xig, sizeof xig);
806 	}
807 	free(inp_list, M_TEMP);
808 	return (error);
809 }
810 
811 SYSCTL_PROC(_net_inet_udp, UDPCTL_PCBLIST, pcblist, CTLFLAG_RD, 0, 0,
812     udp_pcblist, "S,xinpcb", "List of active UDP sockets");
813 
814 static int
815 udp_getcred(SYSCTL_HANDLER_ARGS)
816 {
817 	INIT_VNET_INET(curvnet);
818 	struct xucred xuc;
819 	struct sockaddr_in addrs[2];
820 	struct inpcb *inp;
821 	int error;
822 
823 	error = priv_check(req->td, PRIV_NETINET_GETCRED);
824 	if (error)
825 		return (error);
826 	error = SYSCTL_IN(req, addrs, sizeof(addrs));
827 	if (error)
828 		return (error);
829 	INP_INFO_RLOCK(&V_udbinfo);
830 	inp = in_pcblookup_hash(&V_udbinfo, addrs[1].sin_addr, addrs[1].sin_port,
831 				addrs[0].sin_addr, addrs[0].sin_port, 1, NULL);
832 	if (inp != NULL) {
833 		INP_RLOCK(inp);
834 		INP_INFO_RUNLOCK(&V_udbinfo);
835 		if (inp->inp_socket == NULL)
836 			error = ENOENT;
837 		if (error == 0)
838 			error = cr_canseeinpcb(req->td->td_ucred, inp);
839 		if (error == 0)
840 			cru2x(inp->inp_cred, &xuc);
841 		INP_RUNLOCK(inp);
842 	} else {
843 		INP_INFO_RUNLOCK(&V_udbinfo);
844 		error = ENOENT;
845 	}
846 	if (error == 0)
847 		error = SYSCTL_OUT(req, &xuc, sizeof(struct xucred));
848 	return (error);
849 }
850 
851 SYSCTL_PROC(_net_inet_udp, OID_AUTO, getcred,
852     CTLTYPE_OPAQUE|CTLFLAG_RW|CTLFLAG_PRISON, 0, 0,
853     udp_getcred, "S,xucred", "Get the xucred of a UDP connection");
854 
855 int
856 udp_ctloutput(struct socket *so, struct sockopt *sopt)
857 {
858 	int error = 0, optval;
859 	struct inpcb *inp;
860 #ifdef IPSEC_NAT_T
861 	struct udpcb *up;
862 #endif
863 
864 	inp = sotoinpcb(so);
865 	KASSERT(inp != NULL, ("%s: inp == NULL", __func__));
866 	INP_WLOCK(inp);
867 	if (sopt->sopt_level != IPPROTO_UDP) {
868 #ifdef INET6
869 		if (INP_CHECK_SOCKAF(so, AF_INET6)) {
870 			INP_WUNLOCK(inp);
871 			error = ip6_ctloutput(so, sopt);
872 		} else {
873 #endif
874 			INP_WUNLOCK(inp);
875 			error = ip_ctloutput(so, sopt);
876 #ifdef INET6
877 		}
878 #endif
879 		return (error);
880 	}
881 
882 	switch (sopt->sopt_dir) {
883 	case SOPT_SET:
884 		switch (sopt->sopt_name) {
885 		case UDP_ENCAP:
886 			INP_WUNLOCK(inp);
887 			error = sooptcopyin(sopt, &optval, sizeof optval,
888 					    sizeof optval);
889 			if (error)
890 				break;
891 			inp = sotoinpcb(so);
892 			KASSERT(inp != NULL, ("%s: inp == NULL", __func__));
893 			INP_WLOCK(inp);
894 #ifdef IPSEC_NAT_T
895 			up = intoudpcb(inp);
896 			KASSERT(up != NULL, ("%s: up == NULL", __func__));
897 #endif
898 			switch (optval) {
899 			case 0:
900 				/* Clear all UDP encap. */
901 #ifdef IPSEC_NAT_T
902 				up->u_flags &= ~UF_ESPINUDP_ALL;
903 #endif
904 				break;
905 #ifdef IPSEC_NAT_T
906 			case UDP_ENCAP_ESPINUDP:
907 			case UDP_ENCAP_ESPINUDP_NON_IKE:
908 				up->u_flags &= ~UF_ESPINUDP_ALL;
909 				if (optval == UDP_ENCAP_ESPINUDP)
910 					up->u_flags |= UF_ESPINUDP;
911 				else if (optval == UDP_ENCAP_ESPINUDP_NON_IKE)
912 					up->u_flags |= UF_ESPINUDP_NON_IKE;
913 				break;
914 #endif
915 			default:
916 				error = EINVAL;
917 				break;
918 			}
919 			INP_WUNLOCK(inp);
920 			break;
921 		default:
922 			INP_WUNLOCK(inp);
923 			error = ENOPROTOOPT;
924 			break;
925 		}
926 		break;
927 	case SOPT_GET:
928 		switch (sopt->sopt_name) {
929 #ifdef IPSEC_NAT_T
930 		case UDP_ENCAP:
931 			up = intoudpcb(inp);
932 			KASSERT(up != NULL, ("%s: up == NULL", __func__));
933 			optval = up->u_flags & UF_ESPINUDP_ALL;
934 			INP_WUNLOCK(inp);
935 			error = sooptcopyout(sopt, &optval, sizeof optval);
936 			break;
937 #endif
938 		default:
939 			INP_WUNLOCK(inp);
940 			error = ENOPROTOOPT;
941 			break;
942 		}
943 		break;
944 	}
945 	return (error);
946 }
947 
948 static int
949 udp_output(struct inpcb *inp, struct mbuf *m, struct sockaddr *addr,
950     struct mbuf *control, struct thread *td)
951 {
952 	INIT_VNET_INET(inp->inp_vnet);
953 	struct udpiphdr *ui;
954 	int len = m->m_pkthdr.len;
955 	struct in_addr faddr, laddr;
956 	struct cmsghdr *cm;
957 	struct sockaddr_in *sin, src;
958 	int error = 0;
959 	int ipflags;
960 	u_short fport, lport;
961 	int unlock_udbinfo;
962 
963 	/*
964 	 * udp_output() may need to temporarily bind or connect the current
965 	 * inpcb.  As such, we don't know up front whether we will need the
966 	 * pcbinfo lock or not.  Do any work to decide what is needed up
967 	 * front before acquiring any locks.
968 	 */
969 	if (len + sizeof(struct udpiphdr) > IP_MAXPACKET) {
970 		if (control)
971 			m_freem(control);
972 		m_freem(m);
973 		return (EMSGSIZE);
974 	}
975 
976 	src.sin_family = 0;
977 	if (control != NULL) {
978 		/*
979 		 * XXX: Currently, we assume all the optional information is
980 		 * stored in a single mbuf.
981 		 */
982 		if (control->m_next) {
983 			m_freem(control);
984 			m_freem(m);
985 			return (EINVAL);
986 		}
987 		for (; control->m_len > 0;
988 		    control->m_data += CMSG_ALIGN(cm->cmsg_len),
989 		    control->m_len -= CMSG_ALIGN(cm->cmsg_len)) {
990 			cm = mtod(control, struct cmsghdr *);
991 			if (control->m_len < sizeof(*cm) || cm->cmsg_len == 0
992 			    || cm->cmsg_len > control->m_len) {
993 				error = EINVAL;
994 				break;
995 			}
996 			if (cm->cmsg_level != IPPROTO_IP)
997 				continue;
998 
999 			switch (cm->cmsg_type) {
1000 			case IP_SENDSRCADDR:
1001 				if (cm->cmsg_len !=
1002 				    CMSG_LEN(sizeof(struct in_addr))) {
1003 					error = EINVAL;
1004 					break;
1005 				}
1006 				bzero(&src, sizeof(src));
1007 				src.sin_family = AF_INET;
1008 				src.sin_len = sizeof(src);
1009 				src.sin_port = inp->inp_lport;
1010 				src.sin_addr =
1011 				    *(struct in_addr *)CMSG_DATA(cm);
1012 				break;
1013 
1014 			default:
1015 				error = ENOPROTOOPT;
1016 				break;
1017 			}
1018 			if (error)
1019 				break;
1020 		}
1021 		m_freem(control);
1022 	}
1023 	if (error) {
1024 		m_freem(m);
1025 		return (error);
1026 	}
1027 
1028 	/*
1029 	 * Depending on whether or not the application has bound or connected
1030 	 * the socket, we may have to do varying levels of work.  The optimal
1031 	 * case is for a connected UDP socket, as a global lock isn't
1032 	 * required at all.
1033 	 *
1034 	 * In order to decide which we need, we require stability of the
1035 	 * inpcb binding, which we ensure by acquiring a read lock on the
1036 	 * inpcb.  This doesn't strictly follow the lock order, so we play
1037 	 * the trylock and retry game; note that we may end up with more
1038 	 * conservative locks than required the second time around, so later
1039 	 * assertions have to accept that.  Further analysis of the number of
1040 	 * misses under contention is required.
1041 	 */
1042 	sin = (struct sockaddr_in *)addr;
1043 	INP_RLOCK(inp);
1044 	if (sin != NULL &&
1045 	    (inp->inp_laddr.s_addr == INADDR_ANY && inp->inp_lport == 0)) {
1046 		INP_RUNLOCK(inp);
1047 		INP_INFO_WLOCK(&V_udbinfo);
1048 		INP_WLOCK(inp);
1049 		unlock_udbinfo = 2;
1050 	} else if ((sin != NULL && (
1051 	    (sin->sin_addr.s_addr == INADDR_ANY) ||
1052 	    (sin->sin_addr.s_addr == INADDR_BROADCAST) ||
1053 	    (inp->inp_laddr.s_addr == INADDR_ANY) ||
1054 	    (inp->inp_lport == 0))) ||
1055 	    (src.sin_family == AF_INET)) {
1056 		if (!INP_INFO_TRY_RLOCK(&V_udbinfo)) {
1057 			INP_RUNLOCK(inp);
1058 			INP_INFO_RLOCK(&V_udbinfo);
1059 			INP_RLOCK(inp);
1060 		}
1061 		unlock_udbinfo = 1;
1062 	} else
1063 		unlock_udbinfo = 0;
1064 
1065 	/*
1066 	 * If the IP_SENDSRCADDR control message was specified, override the
1067 	 * source address for this datagram.  Its use is invalidated if the
1068 	 * address thus specified is incomplete or clobbers other inpcbs.
1069 	 */
1070 	laddr = inp->inp_laddr;
1071 	lport = inp->inp_lport;
1072 	if (src.sin_family == AF_INET) {
1073 		INP_INFO_LOCK_ASSERT(&V_udbinfo);
1074 		if ((lport == 0) ||
1075 		    (laddr.s_addr == INADDR_ANY &&
1076 		     src.sin_addr.s_addr == INADDR_ANY)) {
1077 			error = EINVAL;
1078 			goto release;
1079 		}
1080 		error = in_pcbbind_setup(inp, (struct sockaddr *)&src,
1081 		    &laddr.s_addr, &lport, td->td_ucred);
1082 		if (error)
1083 			goto release;
1084 	}
1085 
1086 	/*
1087 	 * If a UDP socket has been connected, then a local address/port will
1088 	 * have been selected and bound.
1089 	 *
1090 	 * If a UDP socket has not been connected to, then an explicit
1091 	 * destination address must be used, in which case a local
1092 	 * address/port may not have been selected and bound.
1093 	 */
1094 	if (sin != NULL) {
1095 		INP_LOCK_ASSERT(inp);
1096 		if (inp->inp_faddr.s_addr != INADDR_ANY) {
1097 			error = EISCONN;
1098 			goto release;
1099 		}
1100 
1101 		/*
1102 		 * Jail may rewrite the destination address, so let it do
1103 		 * that before we use it.
1104 		 */
1105 		error = prison_remote_ip4(td->td_ucred, &sin->sin_addr);
1106 		if (error)
1107 			goto release;
1108 
1109 		/*
1110 		 * If a local address or port hasn't yet been selected, or if
1111 		 * the destination address needs to be rewritten due to using
1112 		 * a special INADDR_ constant, invoke in_pcbconnect_setup()
1113 		 * to do the heavy lifting.  Once a port is selected, we
1114 		 * commit the binding back to the socket; we also commit the
1115 		 * binding of the address if in jail.
1116 		 *
1117 		 * If we already have a valid binding and we're not
1118 		 * requesting a destination address rewrite, use a fast path.
1119 		 */
1120 		if (inp->inp_laddr.s_addr == INADDR_ANY ||
1121 		    inp->inp_lport == 0 ||
1122 		    sin->sin_addr.s_addr == INADDR_ANY ||
1123 		    sin->sin_addr.s_addr == INADDR_BROADCAST) {
1124 			INP_INFO_LOCK_ASSERT(&V_udbinfo);
1125 			error = in_pcbconnect_setup(inp, addr, &laddr.s_addr,
1126 			    &lport, &faddr.s_addr, &fport, NULL,
1127 			    td->td_ucred);
1128 			if (error)
1129 				goto release;
1130 
1131 			/*
1132 			 * XXXRW: Why not commit the port if the address is
1133 			 * !INADDR_ANY?
1134 			 */
1135 			/* Commit the local port if newly assigned. */
1136 			if (inp->inp_laddr.s_addr == INADDR_ANY &&
1137 			    inp->inp_lport == 0) {
1138 				INP_INFO_WLOCK_ASSERT(&V_udbinfo);
1139 				INP_WLOCK_ASSERT(inp);
1140 				/*
1141 				 * Remember addr if jailed, to prevent
1142 				 * rebinding.
1143 				 */
1144 				if (prison_flag(td->td_ucred, PR_IP4))
1145 					inp->inp_laddr = laddr;
1146 				inp->inp_lport = lport;
1147 				if (in_pcbinshash(inp) != 0) {
1148 					inp->inp_lport = 0;
1149 					error = EAGAIN;
1150 					goto release;
1151 				}
1152 				inp->inp_flags |= INP_ANONPORT;
1153 			}
1154 		} else {
1155 			faddr = sin->sin_addr;
1156 			fport = sin->sin_port;
1157 		}
1158 	} else {
1159 		INP_LOCK_ASSERT(inp);
1160 		faddr = inp->inp_faddr;
1161 		fport = inp->inp_fport;
1162 		if (faddr.s_addr == INADDR_ANY) {
1163 			error = ENOTCONN;
1164 			goto release;
1165 		}
1166 	}
1167 
1168 	/*
1169 	 * Calculate data length and get a mbuf for UDP, IP, and possible
1170 	 * link-layer headers.  Immediate slide the data pointer back forward
1171 	 * since we won't use that space at this layer.
1172 	 */
1173 	M_PREPEND(m, sizeof(struct udpiphdr) + max_linkhdr, M_DONTWAIT);
1174 	if (m == NULL) {
1175 		error = ENOBUFS;
1176 		goto release;
1177 	}
1178 	m->m_data += max_linkhdr;
1179 	m->m_len -= max_linkhdr;
1180 	m->m_pkthdr.len -= max_linkhdr;
1181 
1182 	/*
1183 	 * Fill in mbuf with extended UDP header and addresses and length put
1184 	 * into network format.
1185 	 */
1186 	ui = mtod(m, struct udpiphdr *);
1187 	bzero(ui->ui_x1, sizeof(ui->ui_x1));	/* XXX still needed? */
1188 	ui->ui_pr = IPPROTO_UDP;
1189 	ui->ui_src = laddr;
1190 	ui->ui_dst = faddr;
1191 	ui->ui_sport = lport;
1192 	ui->ui_dport = fport;
1193 	ui->ui_ulen = htons((u_short)len + sizeof(struct udphdr));
1194 
1195 	/*
1196 	 * Set the Don't Fragment bit in the IP header.
1197 	 */
1198 	if (inp->inp_flags & INP_DONTFRAG) {
1199 		struct ip *ip;
1200 
1201 		ip = (struct ip *)&ui->ui_i;
1202 		ip->ip_off |= IP_DF;
1203 	}
1204 
1205 	ipflags = 0;
1206 	if (inp->inp_socket->so_options & SO_DONTROUTE)
1207 		ipflags |= IP_ROUTETOIF;
1208 	if (inp->inp_socket->so_options & SO_BROADCAST)
1209 		ipflags |= IP_ALLOWBROADCAST;
1210 	if (inp->inp_flags & INP_ONESBCAST)
1211 		ipflags |= IP_SENDONES;
1212 
1213 #ifdef MAC
1214 	mac_inpcb_create_mbuf(inp, m);
1215 #endif
1216 
1217 	/*
1218 	 * Set up checksum and output datagram.
1219 	 */
1220 	if (udp_cksum) {
1221 		if (inp->inp_flags & INP_ONESBCAST)
1222 			faddr.s_addr = INADDR_BROADCAST;
1223 		ui->ui_sum = in_pseudo(ui->ui_src.s_addr, faddr.s_addr,
1224 		    htons((u_short)len + sizeof(struct udphdr) + IPPROTO_UDP));
1225 		m->m_pkthdr.csum_flags = CSUM_UDP;
1226 		m->m_pkthdr.csum_data = offsetof(struct udphdr, uh_sum);
1227 	} else
1228 		ui->ui_sum = 0;
1229 	((struct ip *)ui)->ip_len = sizeof (struct udpiphdr) + len;
1230 	((struct ip *)ui)->ip_ttl = inp->inp_ip_ttl;	/* XXX */
1231 	((struct ip *)ui)->ip_tos = inp->inp_ip_tos;	/* XXX */
1232 	UDPSTAT_INC(udps_opackets);
1233 
1234 	if (unlock_udbinfo == 2)
1235 		INP_INFO_WUNLOCK(&V_udbinfo);
1236 	else if (unlock_udbinfo == 1)
1237 		INP_INFO_RUNLOCK(&V_udbinfo);
1238 	error = ip_output(m, inp->inp_options, NULL, ipflags,
1239 	    inp->inp_moptions, inp);
1240 	if (unlock_udbinfo == 2)
1241 		INP_WUNLOCK(inp);
1242 	else
1243 		INP_RUNLOCK(inp);
1244 	return (error);
1245 
1246 release:
1247 	if (unlock_udbinfo == 2) {
1248 		INP_WUNLOCK(inp);
1249 		INP_INFO_WUNLOCK(&V_udbinfo);
1250 	} else if (unlock_udbinfo == 1) {
1251 		INP_RUNLOCK(inp);
1252 		INP_INFO_RUNLOCK(&V_udbinfo);
1253 	} else
1254 		INP_RUNLOCK(inp);
1255 	m_freem(m);
1256 	return (error);
1257 }
1258 
1259 
1260 #if defined(IPSEC) && defined(IPSEC_NAT_T)
1261 #ifdef INET
1262 /*
1263  * Potentially decap ESP in UDP frame.  Check for an ESP header
1264  * and optional marker; if present, strip the UDP header and
1265  * push the result through IPSec.
1266  *
1267  * Returns mbuf to be processed (potentially re-allocated) or
1268  * NULL if consumed and/or processed.
1269  */
1270 static struct mbuf *
1271 udp4_espdecap(struct inpcb *inp, struct mbuf *m, int off)
1272 {
1273 	INIT_VNET_IPSEC(curvnet);
1274 	size_t minlen, payload, skip, iphlen;
1275 	caddr_t data;
1276 	struct udpcb *up;
1277 	struct m_tag *tag;
1278 	struct udphdr *udphdr;
1279 	struct ip *ip;
1280 
1281 	INP_RLOCK_ASSERT(inp);
1282 
1283 	/*
1284 	 * Pull up data so the longest case is contiguous:
1285 	 *    IP/UDP hdr + non ESP marker + ESP hdr.
1286 	 */
1287 	minlen = off + sizeof(uint64_t) + sizeof(struct esp);
1288 	if (minlen > m->m_pkthdr.len)
1289 		minlen = m->m_pkthdr.len;
1290 	if ((m = m_pullup(m, minlen)) == NULL) {
1291 		V_ipsec4stat.in_inval++;
1292 		return (NULL);		/* Bypass caller processing. */
1293 	}
1294 	data = mtod(m, caddr_t);	/* Points to ip header. */
1295 	payload = m->m_len - off;	/* Size of payload. */
1296 
1297 	if (payload == 1 && data[off] == '\xff')
1298 		return (m);		/* NB: keepalive packet, no decap. */
1299 
1300 	up = intoudpcb(inp);
1301 	KASSERT(up != NULL, ("%s: udpcb NULL", __func__));
1302 	KASSERT((up->u_flags & UF_ESPINUDP_ALL) != 0,
1303 	    ("u_flags 0x%x", up->u_flags));
1304 
1305 	/*
1306 	 * Check that the payload is large enough to hold an
1307 	 * ESP header and compute the amount of data to remove.
1308 	 *
1309 	 * NB: the caller has already done a pullup for us.
1310 	 * XXX can we assume alignment and eliminate bcopys?
1311 	 */
1312 	if (up->u_flags & UF_ESPINUDP_NON_IKE) {
1313 		/*
1314 		 * draft-ietf-ipsec-nat-t-ike-0[01].txt and
1315 		 * draft-ietf-ipsec-udp-encaps-(00/)01.txt, ignoring
1316 		 * possible AH mode non-IKE marker+non-ESP marker
1317 		 * from draft-ietf-ipsec-udp-encaps-00.txt.
1318 		 */
1319 		uint64_t marker;
1320 
1321 		if (payload <= sizeof(uint64_t) + sizeof(struct esp))
1322 			return (m);	/* NB: no decap. */
1323 		bcopy(data + off, &marker, sizeof(uint64_t));
1324 		if (marker != 0)	/* Non-IKE marker. */
1325 			return (m);	/* NB: no decap. */
1326 		skip = sizeof(uint64_t) + sizeof(struct udphdr);
1327 	} else {
1328 		uint32_t spi;
1329 
1330 		if (payload <= sizeof(struct esp)) {
1331 			V_ipsec4stat.in_inval++;
1332 			m_freem(m);
1333 			return (NULL);	/* Discard. */
1334 		}
1335 		bcopy(data + off, &spi, sizeof(uint32_t));
1336 		if (spi == 0)		/* Non-ESP marker. */
1337 			return (m);	/* NB: no decap. */
1338 		skip = sizeof(struct udphdr);
1339 	}
1340 
1341 	/*
1342 	 * Setup a PACKET_TAG_IPSEC_NAT_T_PORT tag to remember
1343 	 * the UDP ports. This is required if we want to select
1344 	 * the right SPD for multiple hosts behind same NAT.
1345 	 *
1346 	 * NB: ports are maintained in network byte order everywhere
1347 	 *     in the NAT-T code.
1348 	 */
1349 	tag = m_tag_get(PACKET_TAG_IPSEC_NAT_T_PORTS,
1350 		2 * sizeof(uint16_t), M_NOWAIT);
1351 	if (tag == NULL) {
1352 		V_ipsec4stat.in_nomem++;
1353 		m_freem(m);
1354 		return (NULL);		/* Discard. */
1355 	}
1356 	iphlen = off - sizeof(struct udphdr);
1357 	udphdr = (struct udphdr *)(data + iphlen);
1358 	((uint16_t *)(tag + 1))[0] = udphdr->uh_sport;
1359 	((uint16_t *)(tag + 1))[1] = udphdr->uh_dport;
1360 	m_tag_prepend(m, tag);
1361 
1362 	/*
1363 	 * Remove the UDP header (and possibly the non ESP marker)
1364 	 * IP header length is iphlen
1365 	 * Before:
1366 	 *   <--- off --->
1367 	 *   +----+------+-----+
1368 	 *   | IP |  UDP | ESP |
1369 	 *   +----+------+-----+
1370 	 *        <-skip->
1371 	 * After:
1372 	 *          +----+-----+
1373 	 *          | IP | ESP |
1374 	 *          +----+-----+
1375 	 *   <-skip->
1376 	 */
1377 	ovbcopy(data, data + skip, iphlen);
1378 	m_adj(m, skip);
1379 
1380 	ip = mtod(m, struct ip *);
1381 	ip->ip_len -= skip;
1382 	ip->ip_p = IPPROTO_ESP;
1383 
1384 	/*
1385 	 * We cannot yet update the cksums so clear any
1386 	 * h/w cksum flags as they are no longer valid.
1387 	 */
1388 	if (m->m_pkthdr.csum_flags & CSUM_DATA_VALID)
1389 		m->m_pkthdr.csum_flags &= ~(CSUM_DATA_VALID|CSUM_PSEUDO_HDR);
1390 
1391 	(void) ipsec4_common_input(m, iphlen, ip->ip_p);
1392 	return (NULL);			/* NB: consumed, bypass processing. */
1393 }
1394 #endif /* INET */
1395 #endif /* defined(IPSEC) && defined(IPSEC_NAT_T) */
1396 
1397 static void
1398 udp_abort(struct socket *so)
1399 {
1400 	INIT_VNET_INET(so->so_vnet);
1401 	struct inpcb *inp;
1402 
1403 	inp = sotoinpcb(so);
1404 	KASSERT(inp != NULL, ("udp_abort: inp == NULL"));
1405 	INP_INFO_WLOCK(&V_udbinfo);
1406 	INP_WLOCK(inp);
1407 	if (inp->inp_faddr.s_addr != INADDR_ANY) {
1408 		in_pcbdisconnect(inp);
1409 		inp->inp_laddr.s_addr = INADDR_ANY;
1410 		soisdisconnected(so);
1411 	}
1412 	INP_WUNLOCK(inp);
1413 	INP_INFO_WUNLOCK(&V_udbinfo);
1414 }
1415 
1416 static int
1417 udp_attach(struct socket *so, int proto, struct thread *td)
1418 {
1419 	INIT_VNET_INET(so->so_vnet);
1420 	struct inpcb *inp;
1421 	int error;
1422 
1423 	inp = sotoinpcb(so);
1424 	KASSERT(inp == NULL, ("udp_attach: inp != NULL"));
1425 	error = soreserve(so, udp_sendspace, udp_recvspace);
1426 	if (error)
1427 		return (error);
1428 	INP_INFO_WLOCK(&V_udbinfo);
1429 	error = in_pcballoc(so, &V_udbinfo);
1430 	if (error) {
1431 		INP_INFO_WUNLOCK(&V_udbinfo);
1432 		return (error);
1433 	}
1434 
1435 	inp = (struct inpcb *)so->so_pcb;
1436 	inp->inp_vflag |= INP_IPV4;
1437 	inp->inp_ip_ttl = V_ip_defttl;
1438 
1439 	error = udp_newudpcb(inp);
1440 	if (error) {
1441 		in_pcbdetach(inp);
1442 		in_pcbfree(inp);
1443 		INP_INFO_WUNLOCK(&V_udbinfo);
1444 		return (error);
1445 	}
1446 
1447 	INP_WUNLOCK(inp);
1448 	INP_INFO_WUNLOCK(&V_udbinfo);
1449 	return (0);
1450 }
1451 
1452 int
1453 udp_set_kernel_tunneling(struct socket *so, udp_tun_func_t f)
1454 {
1455 	struct inpcb *inp;
1456 	struct udpcb *up;
1457 
1458 	KASSERT(so->so_type == SOCK_DGRAM, ("udp_set_kernel_tunneling: !dgram"));
1459 	KASSERT(so->so_pcb != NULL, ("udp_set_kernel_tunneling: NULL inp"));
1460 	if (so->so_type != SOCK_DGRAM) {
1461 		/* Not UDP socket... sorry! */
1462 		return (ENOTSUP);
1463 	}
1464 	inp = (struct inpcb *)so->so_pcb;
1465 	if (inp == NULL) {
1466 		/* NULL INP? */
1467 		return (EINVAL);
1468 	}
1469 	INP_WLOCK(inp);
1470 	up = intoudpcb(inp);
1471 	if (up->u_tun_func != NULL) {
1472 		INP_WUNLOCK(inp);
1473 		return (EBUSY);
1474 	}
1475 	up->u_tun_func = f;
1476 	INP_WUNLOCK(inp);
1477 	return (0);
1478 }
1479 
1480 static int
1481 udp_bind(struct socket *so, struct sockaddr *nam, struct thread *td)
1482 {
1483 	INIT_VNET_INET(so->so_vnet);
1484 	struct inpcb *inp;
1485 	int error;
1486 
1487 	inp = sotoinpcb(so);
1488 	KASSERT(inp != NULL, ("udp_bind: inp == NULL"));
1489 	INP_INFO_WLOCK(&V_udbinfo);
1490 	INP_WLOCK(inp);
1491 	error = in_pcbbind(inp, nam, td->td_ucred);
1492 	INP_WUNLOCK(inp);
1493 	INP_INFO_WUNLOCK(&V_udbinfo);
1494 	return (error);
1495 }
1496 
1497 static void
1498 udp_close(struct socket *so)
1499 {
1500 	INIT_VNET_INET(so->so_vnet);
1501 	struct inpcb *inp;
1502 
1503 	inp = sotoinpcb(so);
1504 	KASSERT(inp != NULL, ("udp_close: inp == NULL"));
1505 	INP_INFO_WLOCK(&V_udbinfo);
1506 	INP_WLOCK(inp);
1507 	if (inp->inp_faddr.s_addr != INADDR_ANY) {
1508 		in_pcbdisconnect(inp);
1509 		inp->inp_laddr.s_addr = INADDR_ANY;
1510 		soisdisconnected(so);
1511 	}
1512 	INP_WUNLOCK(inp);
1513 	INP_INFO_WUNLOCK(&V_udbinfo);
1514 }
1515 
1516 static int
1517 udp_connect(struct socket *so, struct sockaddr *nam, struct thread *td)
1518 {
1519 	INIT_VNET_INET(so->so_vnet);
1520 	struct inpcb *inp;
1521 	int error;
1522 	struct sockaddr_in *sin;
1523 
1524 	inp = sotoinpcb(so);
1525 	KASSERT(inp != NULL, ("udp_connect: inp == NULL"));
1526 	INP_INFO_WLOCK(&V_udbinfo);
1527 	INP_WLOCK(inp);
1528 	if (inp->inp_faddr.s_addr != INADDR_ANY) {
1529 		INP_WUNLOCK(inp);
1530 		INP_INFO_WUNLOCK(&V_udbinfo);
1531 		return (EISCONN);
1532 	}
1533 	sin = (struct sockaddr_in *)nam;
1534 	error = prison_remote_ip4(td->td_ucred, &sin->sin_addr);
1535 	if (error != 0) {
1536 		INP_WUNLOCK(inp);
1537 		INP_INFO_WUNLOCK(&V_udbinfo);
1538 		return (error);
1539 	}
1540 	error = in_pcbconnect(inp, nam, td->td_ucred);
1541 	if (error == 0)
1542 		soisconnected(so);
1543 	INP_WUNLOCK(inp);
1544 	INP_INFO_WUNLOCK(&V_udbinfo);
1545 	return (error);
1546 }
1547 
1548 static void
1549 udp_detach(struct socket *so)
1550 {
1551 	INIT_VNET_INET(so->so_vnet);
1552 	struct inpcb *inp;
1553 	struct udpcb *up;
1554 
1555 	inp = sotoinpcb(so);
1556 	KASSERT(inp != NULL, ("udp_detach: inp == NULL"));
1557 	KASSERT(inp->inp_faddr.s_addr == INADDR_ANY,
1558 	    ("udp_detach: not disconnected"));
1559 	INP_INFO_WLOCK(&V_udbinfo);
1560 	INP_WLOCK(inp);
1561 	up = intoudpcb(inp);
1562 	KASSERT(up != NULL, ("%s: up == NULL", __func__));
1563 	inp->inp_ppcb = NULL;
1564 	in_pcbdetach(inp);
1565 	in_pcbfree(inp);
1566 	INP_INFO_WUNLOCK(&V_udbinfo);
1567 	udp_discardcb(up);
1568 }
1569 
1570 static int
1571 udp_disconnect(struct socket *so)
1572 {
1573 	INIT_VNET_INET(so->so_vnet);
1574 	struct inpcb *inp;
1575 
1576 	inp = sotoinpcb(so);
1577 	KASSERT(inp != NULL, ("udp_disconnect: inp == NULL"));
1578 	INP_INFO_WLOCK(&V_udbinfo);
1579 	INP_WLOCK(inp);
1580 	if (inp->inp_faddr.s_addr == INADDR_ANY) {
1581 		INP_WUNLOCK(inp);
1582 		INP_INFO_WUNLOCK(&V_udbinfo);
1583 		return (ENOTCONN);
1584 	}
1585 
1586 	in_pcbdisconnect(inp);
1587 	inp->inp_laddr.s_addr = INADDR_ANY;
1588 	SOCK_LOCK(so);
1589 	so->so_state &= ~SS_ISCONNECTED;		/* XXX */
1590 	SOCK_UNLOCK(so);
1591 	INP_WUNLOCK(inp);
1592 	INP_INFO_WUNLOCK(&V_udbinfo);
1593 	return (0);
1594 }
1595 
1596 static int
1597 udp_send(struct socket *so, int flags, struct mbuf *m, struct sockaddr *addr,
1598     struct mbuf *control, struct thread *td)
1599 {
1600 	struct inpcb *inp;
1601 
1602 	inp = sotoinpcb(so);
1603 	KASSERT(inp != NULL, ("udp_send: inp == NULL"));
1604 	return (udp_output(inp, m, addr, control, td));
1605 }
1606 
1607 int
1608 udp_shutdown(struct socket *so)
1609 {
1610 	struct inpcb *inp;
1611 
1612 	inp = sotoinpcb(so);
1613 	KASSERT(inp != NULL, ("udp_shutdown: inp == NULL"));
1614 	INP_WLOCK(inp);
1615 	socantsendmore(so);
1616 	INP_WUNLOCK(inp);
1617 	return (0);
1618 }
1619 
1620 struct pr_usrreqs udp_usrreqs = {
1621 	.pru_abort =		udp_abort,
1622 	.pru_attach =		udp_attach,
1623 	.pru_bind =		udp_bind,
1624 	.pru_connect =		udp_connect,
1625 	.pru_control =		in_control,
1626 	.pru_detach =		udp_detach,
1627 	.pru_disconnect =	udp_disconnect,
1628 	.pru_peeraddr =		in_getpeeraddr,
1629 	.pru_send =		udp_send,
1630 	.pru_soreceive =	soreceive_dgram,
1631 	.pru_sosend =		sosend_dgram,
1632 	.pru_shutdown =		udp_shutdown,
1633 	.pru_sockaddr =		in_getsockaddr,
1634 	.pru_sosetlabel =	in_pcbsosetlabel,
1635 	.pru_close =		udp_close,
1636 };
1637