xref: /dflybsd-src/sys/netinet/udp_usrreq.c (revision 17ea22213f86a5c5966c1e6bf8e95f022ebb92b9)
1 /*
2  * Copyright (c) 2004 Jeffrey M. Hsu.  All rights reserved.
3  * Copyright (c) 2004 The DragonFly Project.  All rights reserved.
4  *
5  * This code is derived from software contributed to The DragonFly Project
6  * by Jeffrey M. Hsu.
7  *
8  * Redistribution and use in source and binary forms, with or without
9  * modification, are permitted provided that the following conditions
10  * are met:
11  * 1. Redistributions of source code must retain the above copyright
12  *    notice, this list of conditions and the following disclaimer.
13  * 2. Redistributions in binary form must reproduce the above copyright
14  *    notice, this list of conditions and the following disclaimer in the
15  *    documentation and/or other materials provided with the distribution.
16  * 3. Neither the name of The DragonFly Project nor the names of its
17  *    contributors may be used to endorse or promote products derived
18  *    from this software without specific, prior written permission.
19  *
20  * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS
21  * ``AS IS'' AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT
22  * LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS
23  * FOR A PARTICULAR PURPOSE ARE DISCLAIMED.  IN NO EVENT SHALL THE
24  * COPYRIGHT HOLDERS OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT,
25  * INCIDENTAL, SPECIAL, EXEMPLARY OR CONSEQUENTIAL DAMAGES (INCLUDING,
26  * BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES;
27  * LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED
28  * AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY,
29  * OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT
30  * OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF
31  * SUCH DAMAGE.
32  */
33 
34 /*
35  * Copyright (c) 2004 Jeffrey M. Hsu.  All rights reserved.
36  *
37  * License terms: all terms for the DragonFly license above plus the following:
38  *
39  * 4. All advertising materials mentioning features or use of this software
40  *    must display the following acknowledgement:
41  *
42  *	This product includes software developed by Jeffrey M. Hsu
43  *	for the DragonFly Project.
44  *
45  *    This requirement may be waived with permission from Jeffrey Hsu.
46  *    This requirement will sunset and may be removed on July 8 2005,
47  *    after which the standard DragonFly license (as shown above) will
48  *    apply.
49  */
50 
51 /*
52  * Copyright (c) 1982, 1986, 1988, 1990, 1993, 1995
53  *	The Regents of the University of California.  All rights reserved.
54  *
55  * Redistribution and use in source and binary forms, with or without
56  * modification, are permitted provided that the following conditions
57  * are met:
58  * 1. Redistributions of source code must retain the above copyright
59  *    notice, this list of conditions and the following disclaimer.
60  * 2. Redistributions in binary form must reproduce the above copyright
61  *    notice, this list of conditions and the following disclaimer in the
62  *    documentation and/or other materials provided with the distribution.
63  * 3. All advertising materials mentioning features or use of this software
64  *    must display the following acknowledgement:
65  *	This product includes software developed by the University of
66  *	California, Berkeley and its contributors.
67  * 4. Neither the name of the University nor the names of its contributors
68  *    may be used to endorse or promote products derived from this software
69  *    without specific prior written permission.
70  *
71  * THIS SOFTWARE IS PROVIDED BY THE REGENTS AND CONTRIBUTORS ``AS IS'' AND
72  * ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
73  * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE
74  * ARE DISCLAIMED.  IN NO EVENT SHALL THE REGENTS OR CONTRIBUTORS BE LIABLE
75  * FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL
76  * DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS
77  * OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION)
78  * HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT
79  * LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY
80  * OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF
81  * SUCH DAMAGE.
82  *
83  *	@(#)udp_usrreq.c	8.6 (Berkeley) 5/23/95
84  * $FreeBSD: src/sys/netinet/udp_usrreq.c,v 1.64.2.18 2003/01/24 05:11:34 sam Exp $
85  * $DragonFly: src/sys/netinet/udp_usrreq.c,v 1.32 2005/01/06 09:14:13 hsu Exp $
86  */
87 
88 #include "opt_ipsec.h"
89 #include "opt_inet6.h"
90 
91 #include <sys/param.h>
92 #include <sys/systm.h>
93 #include <sys/kernel.h>
94 #include <sys/malloc.h>
95 #include <sys/mbuf.h>
96 #include <sys/domain.h>
97 #include <sys/proc.h>
98 #include <sys/protosw.h>
99 #include <sys/socket.h>
100 #include <sys/socketvar.h>
101 #include <sys/sysctl.h>
102 #include <sys/syslog.h>
103 #include <sys/in_cksum.h>
104 
105 #include <machine/stdarg.h>
106 
107 #include <vm/vm_zone.h>
108 
109 #include <net/if.h>
110 #include <net/route.h>
111 
112 #include <netinet/in.h>
113 #include <netinet/in_systm.h>
114 #include <netinet/ip.h>
115 #ifdef INET6
116 #include <netinet/ip6.h>
117 #endif
118 #include <netinet/in_pcb.h>
119 #include <netinet/in_var.h>
120 #include <netinet/ip_var.h>
121 #ifdef INET6
122 #include <netinet6/ip6_var.h>
123 #endif
124 #include <netinet/ip_icmp.h>
125 #include <netinet/icmp_var.h>
126 #include <netinet/udp.h>
127 #include <netinet/udp_var.h>
128 
129 #ifdef FAST_IPSEC
130 #include <netproto/ipsec/ipsec.h>
131 #endif
132 
133 #ifdef IPSEC
134 #include <netinet6/ipsec.h>
135 #endif
136 
137 /*
138  * UDP protocol implementation.
139  * Per RFC 768, August, 1980.
140  */
141 #ifndef	COMPAT_42
142 static int	udpcksum = 1;
143 #else
144 static int	udpcksum = 0;		/* XXX */
145 #endif
146 SYSCTL_INT(_net_inet_udp, UDPCTL_CHECKSUM, checksum, CTLFLAG_RW,
147 		&udpcksum, 0, "");
148 
149 int	log_in_vain = 0;
150 SYSCTL_INT(_net_inet_udp, OID_AUTO, log_in_vain, CTLFLAG_RW,
151     &log_in_vain, 0, "Log all incoming UDP packets");
152 
153 static int	blackhole = 0;
154 SYSCTL_INT(_net_inet_udp, OID_AUTO, blackhole, CTLFLAG_RW,
155 	&blackhole, 0, "Do not send port unreachables for refused connects");
156 
157 static int	strict_mcast_mship = 1;
158 SYSCTL_INT(_net_inet_udp, OID_AUTO, strict_mcast_mship, CTLFLAG_RW,
159 	&strict_mcast_mship, 0, "Only send multicast to member sockets");
160 
161 struct	inpcbinfo udbinfo;
162 
163 #ifndef UDBHASHSIZE
164 #define UDBHASHSIZE 16
165 #endif
166 
167 struct	udpstat udpstat;	/* from udp_var.h */
168 SYSCTL_STRUCT(_net_inet_udp, UDPCTL_STATS, stats, CTLFLAG_RW,
169     &udpstat, udpstat, "UDP statistics (struct udpstat, netinet/udp_var.h)");
170 
171 static struct	sockaddr_in udp_in = { sizeof udp_in, AF_INET };
172 #ifdef INET6
173 struct udp_in6 {
174 	struct sockaddr_in6	uin6_sin;
175 	u_char			uin6_init_done : 1;
176 } udp_in6 = {
177 	{ sizeof udp_in6.uin6_sin, AF_INET6 },
178 	0
179 };
180 struct udp_ip6 {
181 	struct ip6_hdr		uip6_ip6;
182 	u_char			uip6_init_done : 1;
183 } udp_ip6;
184 #endif /* INET6 */
185 
186 static void udp_append (struct inpcb *last, struct ip *ip,
187 			    struct mbuf *n, int off);
188 #ifdef INET6
189 static void ip_2_ip6_hdr (struct ip6_hdr *ip6, struct ip *ip);
190 #endif
191 
192 static int udp_detach (struct socket *so);
193 static	int udp_output (struct inpcb *, struct mbuf *, struct sockaddr *,
194 			    struct mbuf *, struct thread *);
195 
196 void
197 udp_init()
198 {
199 	in_pcbinfo_init(&udbinfo);
200 	udbinfo.hashbase = hashinit(UDBHASHSIZE, M_PCB, &udbinfo.hashmask);
201 	udbinfo.porthashbase = hashinit(UDBHASHSIZE, M_PCB,
202 					&udbinfo.porthashmask);
203 	udbinfo.wildcardhashbase = hashinit(UDBHASHSIZE, M_PCB,
204 					    &udbinfo.wildcardhashmask);
205 	udbinfo.ipi_zone = zinit("udpcb", sizeof(struct inpcb), maxsockets,
206 				 ZONE_INTERRUPT, 0);
207 	udp_thread_init();
208 }
209 
210 /*
211  * Check multicast packets to make sure they are only sent to sockets with
212  * multicast memberships for the packet's destination address and arrival
213  * interface.  Multicast packets to multicast-unaware sockets are also
214  * disallowed.
215  *
216  * Returns 0 if the packet is acceptable, -1 if it is not.
217  */
218 static __inline int
219 check_multicast_membership(struct ip *ip, struct inpcb *inp, struct mbuf *m)
220 {
221 	int mshipno;
222 	struct ip_moptions *mopt;
223 
224 	if (strict_mcast_mship == 0 ||
225 	    !IN_MULTICAST(ntohl(ip->ip_dst.s_addr))) {
226 		return (0);
227 	}
228 	mopt = inp->inp_moptions;
229 	if (mopt == NULL)
230 		return (-1);
231 	for (mshipno = 0; mshipno <= mopt->imo_num_memberships; ++mshipno) {
232 		struct in_multi *maddr = mopt->imo_membership[mshipno];
233 
234 		if (ip->ip_dst.s_addr == maddr->inm_addr.s_addr &&
235 		    m->m_pkthdr.rcvif == maddr->inm_ifp) {
236 			return (0);
237 		}
238 	}
239 	return (-1);
240 }
241 
242 void
243 udp_input(struct mbuf *m, ...)
244 {
245 	int iphlen;
246 	struct ip *ip;
247 	struct udphdr *uh;
248 	struct inpcb *inp;
249 	struct mbuf *opts = NULL;
250 	int len, off, proto;
251 	struct ip save_ip;
252 	struct sockaddr *append_sa;
253 	__va_list ap;
254 
255 	__va_start(ap, m);
256 	off = __va_arg(ap, int);
257 	proto = __va_arg(ap, int);
258 	__va_end(ap);
259 
260 	iphlen = off;
261 	udpstat.udps_ipackets++;
262 
263 	/*
264 	 * Strip IP options, if any; should skip this,
265 	 * make available to user, and use on returned packets,
266 	 * but we don't yet have a way to check the checksum
267 	 * with options still present.
268 	 */
269 	if (iphlen > sizeof(struct ip)) {
270 		ip_stripoptions(m);
271 		iphlen = sizeof(struct ip);
272 	}
273 
274 	/*
275 	 * IP and UDP headers are together in first mbuf.
276 	 * Already checked and pulled up in ip_demux().
277 	 */
278 	KASSERT(m->m_len >= iphlen + sizeof(struct udphdr),
279 	    ("UDP header not in one mbuf"));
280 
281 	ip = mtod(m, struct ip *);
282 	uh = (struct udphdr *)((caddr_t)ip + iphlen);
283 
284 	/* destination port of 0 is illegal, based on RFC768. */
285 	if (uh->uh_dport == 0)
286 		goto bad;
287 
288 	/*
289 	 * Make mbuf data length reflect UDP length.
290 	 * If not enough data to reflect UDP length, drop.
291 	 */
292 	len = ntohs((u_short)uh->uh_ulen);
293 	if (ip->ip_len != len) {
294 		if (len > ip->ip_len || len < sizeof(struct udphdr)) {
295 			udpstat.udps_badlen++;
296 			goto bad;
297 		}
298 		m_adj(m, len - ip->ip_len);
299 		/* ip->ip_len = len; */
300 	}
301 	/*
302 	 * Save a copy of the IP header in case we want restore it
303 	 * for sending an ICMP error message in response.
304 	 */
305 	save_ip = *ip;
306 
307 	/*
308 	 * Checksum extended UDP header and data.
309 	 */
310 	if (uh->uh_sum) {
311 		if (m->m_pkthdr.csum_flags & CSUM_DATA_VALID) {
312 			if (m->m_pkthdr.csum_flags & CSUM_PSEUDO_HDR)
313 				uh->uh_sum = m->m_pkthdr.csum_data;
314 			else
315 				uh->uh_sum = in_pseudo(ip->ip_src.s_addr,
316 				    ip->ip_dst.s_addr, htonl((u_short)len +
317 				    m->m_pkthdr.csum_data + IPPROTO_UDP));
318 			uh->uh_sum ^= 0xffff;
319 		} else {
320 			char b[9];
321 
322 			bcopy(((struct ipovly *)ip)->ih_x1, b, 9);
323 			bzero(((struct ipovly *)ip)->ih_x1, 9);
324 			((struct ipovly *)ip)->ih_len = uh->uh_ulen;
325 			uh->uh_sum = in_cksum(m, len + sizeof(struct ip));
326 			bcopy(b, ((struct ipovly *)ip)->ih_x1, 9);
327 		}
328 		if (uh->uh_sum) {
329 			udpstat.udps_badsum++;
330 			m_freem(m);
331 			return;
332 		}
333 	} else
334 		udpstat.udps_nosum++;
335 
336 	if (IN_MULTICAST(ntohl(ip->ip_dst.s_addr)) ||
337 	    in_broadcast(ip->ip_dst, m->m_pkthdr.rcvif)) {
338 		struct inpcb *last;
339 
340 		/*
341 		 * Deliver a multicast or broadcast datagram to *all* sockets
342 		 * for which the local and remote addresses and ports match
343 		 * those of the incoming datagram.  This allows more than
344 		 * one process to receive multi/broadcasts on the same port.
345 		 * (This really ought to be done for unicast datagrams as
346 		 * well, but that would cause problems with existing
347 		 * applications that open both address-specific sockets and
348 		 * a wildcard socket listening to the same port -- they would
349 		 * end up receiving duplicates of every unicast datagram.
350 		 * Those applications open the multiple sockets to overcome an
351 		 * inadequacy of the UDP socket interface, but for backwards
352 		 * compatibility we avoid the problem here rather than
353 		 * fixing the interface.  Maybe 4.5BSD will remedy this?)
354 		 */
355 
356 		/*
357 		 * Construct sockaddr format source address.
358 		 */
359 		udp_in.sin_port = uh->uh_sport;
360 		udp_in.sin_addr = ip->ip_src;
361 		/*
362 		 * Locate pcb(s) for datagram.
363 		 * (Algorithm copied from raw_intr().)
364 		 */
365 		last = NULL;
366 #ifdef INET6
367 		udp_in6.uin6_init_done = udp_ip6.uip6_init_done = 0;
368 #endif
369 		LIST_FOREACH(inp, &udbinfo.pcblisthead, inp_list) {
370 			if (inp->inp_flags & INP_PLACEMARKER)
371 				continue;
372 #ifdef INET6
373 			if (!(inp->inp_vflag & INP_IPV4))
374 				continue;
375 #endif
376 			if (inp->inp_lport != uh->uh_dport)
377 				continue;
378 			if (inp->inp_laddr.s_addr != INADDR_ANY) {
379 				if (inp->inp_laddr.s_addr !=
380 				    ip->ip_dst.s_addr)
381 					continue;
382 			}
383 			if (inp->inp_faddr.s_addr != INADDR_ANY) {
384 				if (inp->inp_faddr.s_addr !=
385 				    ip->ip_src.s_addr ||
386 				    inp->inp_fport != uh->uh_sport)
387 					continue;
388 			}
389 
390 			if (check_multicast_membership(ip, inp, m) < 0)
391 				continue;
392 
393 			if (last != NULL) {
394 				struct mbuf *n;
395 
396 #ifdef IPSEC
397 				/* check AH/ESP integrity. */
398 				if (ipsec4_in_reject_so(m, last->inp_socket))
399 					ipsecstat.in_polvio++;
400 					/* do not inject data to pcb */
401 				else
402 #endif /*IPSEC*/
403 #ifdef FAST_IPSEC
404 				/* check AH/ESP integrity. */
405 				if (ipsec4_in_reject(m, last))
406 					;
407 				else
408 #endif /*FAST_IPSEC*/
409 				if ((n = m_copypacket(m, MB_DONTWAIT)) != NULL)
410 					udp_append(last, ip, n,
411 						   iphlen +
412 						   sizeof(struct udphdr));
413 			}
414 			last = inp;
415 			/*
416 			 * Don't look for additional matches if this one does
417 			 * not have either the SO_REUSEPORT or SO_REUSEADDR
418 			 * socket options set.  This heuristic avoids searching
419 			 * through all pcbs in the common case of a non-shared
420 			 * port.  It * assumes that an application will never
421 			 * clear these options after setting them.
422 			 */
423 			if (!(last->inp_socket->so_options &
424 			    (SO_REUSEPORT | SO_REUSEADDR)))
425 				break;
426 		}
427 
428 		if (last == NULL) {
429 			/*
430 			 * No matching pcb found; discard datagram.
431 			 * (No need to send an ICMP Port Unreachable
432 			 * for a broadcast or multicast datgram.)
433 			 */
434 			udpstat.udps_noportbcast++;
435 			goto bad;
436 		}
437 #ifdef IPSEC
438 		/* check AH/ESP integrity. */
439 		if (ipsec4_in_reject_so(m, last->inp_socket)) {
440 			ipsecstat.in_polvio++;
441 			goto bad;
442 		}
443 #endif /*IPSEC*/
444 #ifdef FAST_IPSEC
445 		/* check AH/ESP integrity. */
446 		if (ipsec4_in_reject(m, last))
447 			goto bad;
448 #endif /*FAST_IPSEC*/
449 		udp_append(last, ip, m, iphlen + sizeof(struct udphdr));
450 		return;
451 	}
452 	/*
453 	 * Locate pcb for datagram.
454 	 */
455 	inp = in_pcblookup_hash(&udbinfo, ip->ip_src, uh->uh_sport,
456 	    ip->ip_dst, uh->uh_dport, 1, m->m_pkthdr.rcvif);
457 	if (inp == NULL) {
458 		if (log_in_vain) {
459 			char buf[sizeof "aaa.bbb.ccc.ddd"];
460 
461 			strcpy(buf, inet_ntoa(ip->ip_dst));
462 			log(LOG_INFO,
463 			    "Connection attempt to UDP %s:%d from %s:%d\n",
464 			    buf, ntohs(uh->uh_dport), inet_ntoa(ip->ip_src),
465 			    ntohs(uh->uh_sport));
466 		}
467 		udpstat.udps_noport++;
468 		if (m->m_flags & (M_BCAST | M_MCAST)) {
469 			udpstat.udps_noportbcast++;
470 			goto bad;
471 		}
472 		if (blackhole)
473 			goto bad;
474 #ifdef ICMP_BANDLIM
475 		if (badport_bandlim(BANDLIM_ICMP_UNREACH) < 0)
476 			goto bad;
477 #endif
478 		*ip = save_ip;
479 		ip->ip_len += iphlen;
480 		icmp_error(m, ICMP_UNREACH, ICMP_UNREACH_PORT, 0, 0);
481 		return;
482 	}
483 #ifdef IPSEC
484 	if (ipsec4_in_reject_so(m, inp->inp_socket)) {
485 		ipsecstat.in_polvio++;
486 		goto bad;
487 	}
488 #endif /*IPSEC*/
489 #ifdef FAST_IPSEC
490 	if (ipsec4_in_reject(m, inp))
491 		goto bad;
492 #endif /*FAST_IPSEC*/
493 
494 	/*
495 	 * Construct sockaddr format source address.
496 	 * Stuff source address and datagram in user buffer.
497 	 */
498 	udp_in.sin_port = uh->uh_sport;
499 	udp_in.sin_addr = ip->ip_src;
500 	if ((inp->inp_flags & INP_CONTROLOPTS) ||
501 	    (inp->inp_socket->so_options & SO_TIMESTAMP)) {
502 #ifdef INET6
503 		if (inp->inp_vflag & INP_IPV6) {
504 			int savedflags;
505 
506 			ip_2_ip6_hdr(&udp_ip6.uip6_ip6, ip);
507 			savedflags = inp->inp_flags;
508 			inp->inp_flags &= ~INP_UNMAPPABLEOPTS;
509 			ip6_savecontrol(inp, &opts, &udp_ip6.uip6_ip6, m);
510 			inp->inp_flags = savedflags;
511 		} else
512 #endif
513 		ip_savecontrol(inp, &opts, ip, m);
514 	}
515 	m_adj(m, iphlen + sizeof(struct udphdr));
516 #ifdef INET6
517 	if (inp->inp_vflag & INP_IPV6) {
518 		in6_sin_2_v4mapsin6(&udp_in, &udp_in6.uin6_sin);
519 		append_sa = (struct sockaddr *)&udp_in6;
520 	} else
521 #endif
522 		append_sa = (struct sockaddr *)&udp_in;
523 	if (sbappendaddr(&inp->inp_socket->so_rcv, append_sa, m, opts) == 0) {
524 		udpstat.udps_fullsock++;
525 		goto bad;
526 	}
527 	sorwakeup(inp->inp_socket);
528 	return;
529 bad:
530 	m_freem(m);
531 	if (opts)
532 		m_freem(opts);
533 	return;
534 }
535 
536 #ifdef INET6
537 static void
538 ip_2_ip6_hdr(ip6, ip)
539 	struct ip6_hdr *ip6;
540 	struct ip *ip;
541 {
542 	bzero(ip6, sizeof *ip6);
543 
544 	ip6->ip6_vfc = IPV6_VERSION;
545 	ip6->ip6_plen = ip->ip_len;
546 	ip6->ip6_nxt = ip->ip_p;
547 	ip6->ip6_hlim = ip->ip_ttl;
548 	ip6->ip6_src.s6_addr32[2] = ip6->ip6_dst.s6_addr32[2] =
549 		IPV6_ADDR_INT32_SMP;
550 	ip6->ip6_src.s6_addr32[3] = ip->ip_src.s_addr;
551 	ip6->ip6_dst.s6_addr32[3] = ip->ip_dst.s_addr;
552 }
553 #endif
554 
555 /*
556  * subroutine of udp_input(), mainly for source code readability.
557  * caller must properly init udp_ip6 and udp_in6 beforehand.
558  */
559 static void
560 udp_append(last, ip, n, off)
561 	struct inpcb *last;
562 	struct ip *ip;
563 	struct mbuf *n;
564 	int off;
565 {
566 	struct sockaddr *append_sa;
567 	struct mbuf *opts = NULL;
568 
569 	if (last->inp_flags & INP_CONTROLOPTS ||
570 	    last->inp_socket->so_options & SO_TIMESTAMP) {
571 #ifdef INET6
572 		if (last->inp_vflag & INP_IPV6) {
573 			int savedflags;
574 
575 			if (udp_ip6.uip6_init_done == 0) {
576 				ip_2_ip6_hdr(&udp_ip6.uip6_ip6, ip);
577 				udp_ip6.uip6_init_done = 1;
578 			}
579 			savedflags = last->inp_flags;
580 			last->inp_flags &= ~INP_UNMAPPABLEOPTS;
581 			ip6_savecontrol(last, &opts, &udp_ip6.uip6_ip6, n);
582 			last->inp_flags = savedflags;
583 		} else
584 #endif
585 		ip_savecontrol(last, &opts, ip, n);
586 	}
587 #ifdef INET6
588 	if (last->inp_vflag & INP_IPV6) {
589 		if (udp_in6.uin6_init_done == 0) {
590 			in6_sin_2_v4mapsin6(&udp_in, &udp_in6.uin6_sin);
591 			udp_in6.uin6_init_done = 1;
592 		}
593 		append_sa = (struct sockaddr *)&udp_in6.uin6_sin;
594 	} else
595 #endif
596 		append_sa = (struct sockaddr *)&udp_in;
597 	m_adj(n, off);
598 	if (sbappendaddr(&last->inp_socket->so_rcv, append_sa, n, opts) == 0) {
599 		m_freem(n);
600 		if (opts)
601 			m_freem(opts);
602 		udpstat.udps_fullsock++;
603 	} else
604 		sorwakeup(last->inp_socket);
605 }
606 
607 /*
608  * Notify a udp user of an asynchronous error;
609  * just wake up so that he can collect error status.
610  */
611 void
612 udp_notify(inp, errno)
613 	struct inpcb *inp;
614 	int errno;
615 {
616 	inp->inp_socket->so_error = errno;
617 	sorwakeup(inp->inp_socket);
618 	sowwakeup(inp->inp_socket);
619 }
620 
621 void
622 udp_ctlinput(cmd, sa, vip)
623 	int cmd;
624 	struct sockaddr *sa;
625 	void *vip;
626 {
627 	struct ip *ip = vip;
628 	struct udphdr *uh;
629 	void (*notify) (struct inpcb *, int) = udp_notify;
630 	struct in_addr faddr;
631 	struct inpcb *inp;
632 	int s;
633 
634 	faddr = ((struct sockaddr_in *)sa)->sin_addr;
635 	if (sa->sa_family != AF_INET || faddr.s_addr == INADDR_ANY)
636 		return;
637 
638 	if (PRC_IS_REDIRECT(cmd)) {
639 		ip = NULL;
640 		notify = in_rtchange;
641 	} else if (cmd == PRC_HOSTDEAD)
642 		ip = NULL;
643 	else if ((unsigned)cmd >= PRC_NCMDS || inetctlerrmap[cmd] == 0)
644 		return;
645 	if (ip) {
646 		s = splnet();
647 		uh = (struct udphdr *)((caddr_t)ip + (ip->ip_hl << 2));
648 		inp = in_pcblookup_hash(&udbinfo, faddr, uh->uh_dport,
649 					ip->ip_src, uh->uh_sport, 0, NULL);
650 		if (inp != NULL && inp->inp_socket != NULL)
651 			(*notify)(inp, inetctlerrmap[cmd]);
652 		splx(s);
653 	} else
654 		in_pcbnotifyall(&udbinfo.pcblisthead, faddr, inetctlerrmap[cmd],
655 				notify);
656 }
657 
658 SYSCTL_PROC(_net_inet_udp, UDPCTL_PCBLIST, pcblist, CTLFLAG_RD, &udbinfo, 0,
659 	    in_pcblist_global, "S,xinpcb", "List of active UDP sockets");
660 
661 static int
662 udp_getcred(SYSCTL_HANDLER_ARGS)
663 {
664 	struct sockaddr_in addrs[2];
665 	struct inpcb *inp;
666 	int error, s;
667 
668 	error = suser(req->td);
669 	if (error)
670 		return (error);
671 	error = SYSCTL_IN(req, addrs, sizeof addrs);
672 	if (error)
673 		return (error);
674 	s = splnet();
675 	inp = in_pcblookup_hash(&udbinfo, addrs[1].sin_addr, addrs[1].sin_port,
676 				addrs[0].sin_addr, addrs[0].sin_port, 1, NULL);
677 	if (inp == NULL || inp->inp_socket == NULL) {
678 		error = ENOENT;
679 		goto out;
680 	}
681 	error = SYSCTL_OUT(req, inp->inp_socket->so_cred, sizeof(struct ucred));
682 out:
683 	splx(s);
684 	return (error);
685 }
686 
687 SYSCTL_PROC(_net_inet_udp, OID_AUTO, getcred, CTLTYPE_OPAQUE|CTLFLAG_RW,
688     0, 0, udp_getcred, "S,ucred", "Get the ucred of a UDP connection");
689 
690 static int
691 udp_output(inp, m, dstaddr, control, td)
692 	struct inpcb *inp;
693 	struct mbuf *m;
694 	struct sockaddr *dstaddr;
695 	struct mbuf *control;
696 	struct thread *td;
697 {
698 	struct udpiphdr *ui;
699 	int len = m->m_pkthdr.len;
700 	struct sockaddr_in *sin;	/* really is initialized before use */
701 	int error = 0;
702 
703 	if (len + sizeof(struct udpiphdr) > IP_MAXPACKET) {
704 		error = EMSGSIZE;
705 		goto release;
706 	}
707 
708 	if (inp->inp_lport == 0) {	/* unbound socket */
709 		error = in_pcbbind(inp, (struct sockaddr *)NULL, td);
710 		if (error)
711 			goto release;
712 		in_pcbinswildcardhash(inp);
713 	}
714 
715 	if (dstaddr != NULL) {		/* destination address specified */
716 		if (inp->inp_faddr.s_addr != INADDR_ANY) {
717 			/* already connected */
718 			error = EISCONN;
719 			goto release;
720 		}
721 		sin = (struct sockaddr_in *)dstaddr;
722 		prison_remote_ip(td, 0, &sin->sin_addr.s_addr);
723 	} else {
724 		if (inp->inp_faddr.s_addr == INADDR_ANY) {
725 			/* no destination specified and not already connected */
726 			error = ENOTCONN;
727 			goto release;
728 		}
729 		sin = NULL;
730 	}
731 
732 	/*
733 	 * Calculate data length and get a mbuf
734 	 * for UDP and IP headers.
735 	 */
736 	M_PREPEND(m, sizeof(struct udpiphdr), MB_DONTWAIT);
737 	if (m == NULL) {
738 		error = ENOBUFS;
739 		goto release;
740 	}
741 
742 	/*
743 	 * Fill in mbuf with extended UDP header
744 	 * and addresses and length put into network format.
745 	 */
746 	ui = mtod(m, struct udpiphdr *);
747 	bzero(ui->ui_x1, sizeof ui->ui_x1);	/* XXX still needed? */
748 	ui->ui_pr = IPPROTO_UDP;
749 
750 	/*
751 	 * Set destination address.
752 	 */
753 	if (dstaddr != NULL) {			/* use specified destination */
754 		ui->ui_dst = sin->sin_addr;
755 		ui->ui_dport = sin->sin_port;
756 	} else {				/* use connected destination */
757 		ui->ui_dst = inp->inp_faddr;
758 		ui->ui_dport = inp->inp_fport;
759 	}
760 
761 	/*
762 	 * Set source address.
763 	 */
764 	if (inp->inp_laddr.s_addr == INADDR_ANY) {
765 		struct sockaddr_in *if_sin;
766 
767 		KASSERT(dstaddr != NULL,
768 		    ("connected UDP socket without local addr: "
769 		     "lport %d, faddr %x, fport %d",
770 		     inp->inp_lport, inp->inp_faddr.s_addr, inp->inp_fport));
771 
772 		/* Look up outgoing interface. */
773 		if ((error = in_pcbladdr(inp, dstaddr, &if_sin)))
774 			goto release;
775 		ui->ui_src = if_sin->sin_addr;	/* use address of interface */
776 	} else {
777 		ui->ui_src = inp->inp_laddr;	/* use non-null bound address */
778 	}
779 	ui->ui_sport = inp->inp_lport;
780 	KASSERT(inp->inp_lport != 0, ("inp lport should have been bound"));
781 
782 	ui->ui_ulen = htons((u_short)len + sizeof(struct udphdr));
783 
784 	/*
785 	 * Set up checksum and output datagram.
786 	 */
787 	if (udpcksum) {
788 		ui->ui_sum = in_pseudo(ui->ui_src.s_addr, ui->ui_dst.s_addr,
789 		    htons((u_short)len + sizeof(struct udphdr) + IPPROTO_UDP));
790 		m->m_pkthdr.csum_flags = CSUM_UDP;
791 		m->m_pkthdr.csum_data = offsetof(struct udphdr, uh_sum);
792 	} else {
793 		ui->ui_sum = 0;
794 	}
795 	((struct ip *)ui)->ip_len = sizeof(struct udpiphdr) + len;
796 	((struct ip *)ui)->ip_ttl = inp->inp_ip_ttl;	/* XXX */
797 	((struct ip *)ui)->ip_tos = inp->inp_ip_tos;	/* XXX */
798 	udpstat.udps_opackets++;
799 
800 	error = ip_output(m, inp->inp_options, &inp->inp_route,
801 	    (inp->inp_socket->so_options & (SO_DONTROUTE | SO_BROADCAST)),
802 	    inp->inp_moptions, inp);
803 
804 	return (error);
805 
806 release:
807 	m_freem(m);
808 	return (error);
809 }
810 
811 u_long	udp_sendspace = 9216;		/* really max datagram size */
812 					/* 40 1K datagrams */
813 SYSCTL_INT(_net_inet_udp, UDPCTL_MAXDGRAM, maxdgram, CTLFLAG_RW,
814     &udp_sendspace, 0, "Maximum outgoing UDP datagram size");
815 
816 u_long	udp_recvspace = 40 * (1024 +
817 #ifdef INET6
818 				      sizeof(struct sockaddr_in6)
819 #else
820 				      sizeof(struct sockaddr_in)
821 #endif
822 				      );
823 SYSCTL_INT(_net_inet_udp, UDPCTL_RECVSPACE, recvspace, CTLFLAG_RW,
824     &udp_recvspace, 0, "Maximum incoming UDP datagram size");
825 
826 static int
827 udp_abort(struct socket *so)
828 {
829 	struct inpcb *inp;
830 	int s;
831 
832 	inp = sotoinpcb(so);
833 	if (inp == NULL)
834 		return EINVAL;	/* ??? possible? panic instead? */
835 	soisdisconnected(so);
836 	s = splnet();
837 	in_pcbdetach(inp);
838 	splx(s);
839 	return 0;
840 }
841 
842 static int
843 udp_attach(struct socket *so, int proto, struct pru_attach_info *ai)
844 {
845 	struct inpcb *inp;
846 	int s, error;
847 
848 	inp = sotoinpcb(so);
849 	if (inp != NULL)
850 		return EINVAL;
851 
852 	error = soreserve(so, udp_sendspace, udp_recvspace, ai->sb_rlimit);
853 	if (error)
854 		return error;
855 	s = splnet();
856 	error = in_pcballoc(so, &udbinfo);
857 	splx(s);
858 	if (error)
859 		return error;
860 
861 	inp = (struct inpcb *)so->so_pcb;
862 	inp->inp_vflag |= INP_IPV4;
863 	inp->inp_ip_ttl = ip_defttl;
864 	return 0;
865 }
866 
867 static int
868 udp_bind(struct socket *so, struct sockaddr *nam, struct thread *td)
869 {
870 	struct sockaddr_in *sin = (struct sockaddr_in *)nam;
871 	struct inpcb *inp;
872 	int s, error;
873 
874 	inp = sotoinpcb(so);
875 	if (inp == NULL)
876 		return EINVAL;
877 	s = splnet();
878 	error = in_pcbbind(inp, nam, td);
879 	splx(s);
880 	if (error == 0) {
881 		if (sin->sin_addr.s_addr != INADDR_ANY)
882 			inp->inp_flags |= INP_WASBOUND_NOTANY;
883 		in_pcbinswildcardhash(inp);
884 	}
885 	return error;
886 }
887 
888 static int
889 udp_connect(struct socket *so, struct sockaddr *nam, struct thread *td)
890 {
891 	struct inpcb *inp;
892 	int s, error;
893 	struct sockaddr_in *sin;
894 
895 	inp = sotoinpcb(so);
896 	if (inp == NULL)
897 		return EINVAL;
898 	if (inp->inp_faddr.s_addr != INADDR_ANY)
899 		return EISCONN;
900 	error = 0;
901 	s = splnet();
902 	if (td->td_proc && td->td_proc->p_ucred->cr_prison != NULL &&
903 	    inp->inp_laddr.s_addr == INADDR_ANY) {
904 		error = in_pcbbind(inp, NULL, td);
905 	}
906 	if (error == 0) {
907 		sin = (struct sockaddr_in *)nam;
908 		prison_remote_ip(td, 0, &sin->sin_addr.s_addr);
909 		if (inp->inp_flags & INP_WILDCARD)
910 			in_pcbremwildcardhash(inp);
911 		error = in_pcbconnect(inp, nam, td);
912 	}
913 	splx(s);
914 	if (error == 0)
915 		soisconnected(so);
916 	else if (error == EAFNOSUPPORT) {	/* connection dissolved */
917 		/*
918 		 * Follow traditional BSD behavior and retain
919 		 * the local port binding.  But, fix the old misbehavior
920 		 * of overwriting any previously bound local address.
921 		 */
922 		if (!(inp->inp_flags & INP_WASBOUND_NOTANY))
923 			inp->inp_laddr.s_addr = INADDR_ANY;
924 		in_pcbinswildcardhash(inp);
925 	}
926 	return error;
927 }
928 
929 static int
930 udp_detach(struct socket *so)
931 {
932 	struct inpcb *inp;
933 	int s;
934 
935 	inp = sotoinpcb(so);
936 	if (inp == NULL)
937 		return EINVAL;
938 	s = splnet();
939 	in_pcbdetach(inp);
940 	splx(s);
941 	return 0;
942 }
943 
944 static int
945 udp_disconnect(struct socket *so)
946 {
947 	struct inpcb *inp;
948 	int s;
949 
950 	inp = sotoinpcb(so);
951 	if (inp == NULL)
952 		return EINVAL;
953 	if (inp->inp_faddr.s_addr == INADDR_ANY)
954 		return ENOTCONN;
955 
956 	s = splnet();
957 	in_pcbdisconnect(inp);
958 	splx(s);
959 	so->so_state &= ~SS_ISCONNECTED;		/* XXX */
960 	return 0;
961 }
962 
963 static int
964 udp_send(struct socket *so, int flags, struct mbuf *m, struct sockaddr *addr,
965 	    struct mbuf *control, struct thread *td)
966 {
967 	struct inpcb *inp;
968 
969 	inp = sotoinpcb(so);
970 	if (inp == NULL) {
971 		m_freem(m);
972 		return EINVAL;
973 	}
974 	return udp_output(inp, m, addr, control, td);
975 }
976 
977 int
978 udp_shutdown(struct socket *so)
979 {
980 	struct inpcb *inp;
981 
982 	inp = sotoinpcb(so);
983 	if (inp == NULL)
984 		return EINVAL;
985 	socantsendmore(so);
986 	return 0;
987 }
988 
989 struct pr_usrreqs udp_usrreqs = {
990 	udp_abort, pru_accept_notsupp, udp_attach, udp_bind, udp_connect,
991 	pru_connect2_notsupp, in_control, udp_detach, udp_disconnect,
992 	pru_listen_notsupp, in_setpeeraddr, pru_rcvd_notsupp,
993 	pru_rcvoob_notsupp, udp_send, pru_sense_null, udp_shutdown,
994 	in_setsockaddr, sosendudp, soreceive, sopoll
995 };
996 
997