xref: /openbsd-src/sys/netinet/udp_usrreq.c (revision a28daedfc357b214be5c701aa8ba8adb29a7f1c2)
1 /*	$OpenBSD: udp_usrreq.c,v 1.126 2008/10/13 14:02:20 henning Exp $	*/
2 /*	$NetBSD: udp_usrreq.c,v 1.28 1996/03/16 23:54:03 christos Exp $	*/
3 
4 /*
5  * Copyright (c) 1982, 1986, 1988, 1990, 1993
6  *	The Regents of the University of California.  All rights reserved.
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 University nor the names of its contributors
17  *    may be used to endorse or promote products derived from this software
18  *    without specific prior written permission.
19  *
20  * THIS SOFTWARE IS PROVIDED BY THE REGENTS AND CONTRIBUTORS ``AS IS'' AND
21  * ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
22  * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE
23  * ARE DISCLAIMED.  IN NO EVENT SHALL THE REGENTS OR CONTRIBUTORS BE LIABLE
24  * FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL
25  * DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS
26  * OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION)
27  * HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT
28  * LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY
29  * OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF
30  * SUCH DAMAGE.
31  *
32  *	@(#)COPYRIGHT	1.1 (NRL) 17 January 1995
33  *
34  * NRL grants permission for redistribution and use in source and binary
35  * forms, with or without modification, of the software and documentation
36  * created at NRL provided that the following conditions are met:
37  *
38  * 1. Redistributions of source code must retain the above copyright
39  *    notice, this list of conditions and the following disclaimer.
40  * 2. Redistributions in binary form must reproduce the above copyright
41  *    notice, this list of conditions and the following disclaimer in the
42  *    documentation and/or other materials provided with the distribution.
43  * 3. All advertising materials mentioning features or use of this software
44  *    must display the following acknowledgements:
45  * 	This product includes software developed by the University of
46  * 	California, Berkeley and its contributors.
47  * 	This product includes software developed at the Information
48  * 	Technology Division, US Naval Research Laboratory.
49  * 4. Neither the name of the NRL nor the names of its contributors
50  *    may be used to endorse or promote products derived from this software
51  *    without specific prior written permission.
52  *
53  * THE SOFTWARE PROVIDED BY NRL IS PROVIDED BY NRL AND CONTRIBUTORS ``AS
54  * IS'' AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED
55  * TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A
56  * PARTICULAR PURPOSE ARE DISCLAIMED.  IN NO EVENT SHALL NRL OR
57  * CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL,
58  * EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO,
59  * PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR
60  * PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF
61  * LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING
62  * NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS
63  * SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
64  *
65  * The views and conclusions contained in the software and documentation
66  * are those of the authors and should not be interpreted as representing
67  * official policies, either expressed or implied, of the US Naval
68  * Research Laboratory (NRL).
69  */
70 
71 #include <sys/param.h>
72 #include <sys/systm.h>
73 #include <sys/mbuf.h>
74 #include <sys/protosw.h>
75 #include <sys/socket.h>
76 #include <sys/socketvar.h>
77 #include <sys/sysctl.h>
78 
79 #include <net/if.h>
80 #include <net/route.h>
81 
82 #include <netinet/in.h>
83 #include <netinet/in_systm.h>
84 #include <netinet/in_var.h>
85 #include <netinet/ip.h>
86 #include <netinet/in_pcb.h>
87 #include <netinet/ip_var.h>
88 #include <netinet/ip_icmp.h>
89 #include <netinet/udp.h>
90 #include <netinet/udp_var.h>
91 
92 #ifdef IPSEC
93 #include <netinet/ip_ipsp.h>
94 #include <netinet/ip_esp.h>
95 #endif
96 
97 #ifdef INET6
98 #ifndef INET
99 #include <netinet/in.h>
100 #endif
101 #include <netinet6/ip6protosw.h>
102 
103 extern int ip6_defhlim;
104 #endif /* INET6 */
105 
106 #include "faith.h"
107 
108 #include "pf.h"
109 #if NPF > 0
110 #include <net/pfvar.h>
111 #endif
112 
113 /*
114  * UDP protocol implementation.
115  * Per RFC 768, August, 1980.
116  */
117 int	udpcksum = 1;
118 
119 u_int	udp_sendspace = 9216;		/* really max datagram size */
120 u_int	udp_recvspace = 40 * (1024 + sizeof(struct sockaddr_in));
121 					/* 40 1K datagrams */
122 
123 int *udpctl_vars[UDPCTL_MAXID] = UDPCTL_VARS;
124 
125 struct	inpcbtable udbtable;
126 struct	udpstat udpstat;
127 
128 void udp_detach(struct inpcb *);
129 void udp_notify(struct inpcb *, int);
130 
131 #ifndef UDBHASHSIZE
132 #define	UDBHASHSIZE	128
133 #endif
134 int	udbhashsize = UDBHASHSIZE;
135 
136 /* from in_pcb.c */
137 extern	struct baddynamicports baddynamicports;
138 
139 void
140 udp_init()
141 {
142 	in_pcbinit(&udbtable, udbhashsize);
143 }
144 
145 #ifdef INET6
146 int
147 udp6_input(struct mbuf **mp, int *offp, int proto)
148 {
149 	struct mbuf *m = *mp;
150 
151 #if NFAITH > 0
152 	if (m->m_pkthdr.rcvif) {
153 		if (m->m_pkthdr.rcvif->if_type == IFT_FAITH) {
154 			/* XXX send icmp6 host/port unreach? */
155 			m_freem(m);
156 			return IPPROTO_DONE;
157 		}
158 	}
159 #endif
160 
161 	udp_input(m, *offp, proto);
162 	return IPPROTO_DONE;
163 }
164 #endif
165 
166 void
167 udp_input(struct mbuf *m, ...)
168 {
169 	struct ip *ip;
170 	struct udphdr *uh;
171 	struct inpcb *inp = NULL;
172 	struct mbuf *opts = NULL;
173 	struct ip save_ip;
174 	int iphlen, len;
175 	va_list ap;
176 	u_int16_t savesum;
177 	union {
178 		struct sockaddr sa;
179 		struct sockaddr_in sin;
180 #ifdef INET6
181 		struct sockaddr_in6 sin6;
182 #endif /* INET6 */
183 	} srcsa, dstsa;
184 #ifdef INET6
185 	struct ip6_hdr *ip6;
186 #endif /* INET6 */
187 #ifdef IPSEC
188 	struct m_tag *mtag;
189 	struct tdb_ident *tdbi;
190 	struct tdb *tdb;
191 	int error, s;
192 #endif /* IPSEC */
193 
194 	va_start(ap, m);
195 	iphlen = va_arg(ap, int);
196 	va_end(ap);
197 
198 	udpstat.udps_ipackets++;
199 
200 	switch (mtod(m, struct ip *)->ip_v) {
201 	case 4:
202 		ip = mtod(m, struct ip *);
203 #ifdef INET6
204 		ip6 = NULL;
205 #endif /* INET6 */
206 		srcsa.sa.sa_family = AF_INET;
207 		break;
208 #ifdef INET6
209 	case 6:
210 		ip = NULL;
211 		ip6 = mtod(m, struct ip6_hdr *);
212 		srcsa.sa.sa_family = AF_INET6;
213 		break;
214 #endif /* INET6 */
215 	default:
216 		goto bad;
217 	}
218 
219 	IP6_EXTHDR_GET(uh, struct udphdr *, m, iphlen, sizeof(struct udphdr));
220 	if (!uh) {
221 		udpstat.udps_hdrops++;
222 		return;
223 	}
224 
225 	/* Check for illegal destination port 0 */
226 	if (uh->uh_dport == 0) {
227 		udpstat.udps_noport++;
228 		goto bad;
229 	}
230 
231 	/*
232 	 * Make mbuf data length reflect UDP length.
233 	 * If not enough data to reflect UDP length, drop.
234 	 */
235 	len = ntohs((u_int16_t)uh->uh_ulen);
236 	if (ip) {
237 		if (m->m_pkthdr.len - iphlen != len) {
238 			if (len > (m->m_pkthdr.len - iphlen) ||
239 			    len < sizeof(struct udphdr)) {
240 				udpstat.udps_badlen++;
241 				goto bad;
242 			}
243 			m_adj(m, len - (m->m_pkthdr.len - iphlen));
244 		}
245 	}
246 #ifdef INET6
247 	else if (ip6) {
248 		/* jumbograms */
249 		if (len == 0 && m->m_pkthdr.len - iphlen > 0xffff)
250 			len = m->m_pkthdr.len - iphlen;
251 		if (len != m->m_pkthdr.len - iphlen) {
252 			udpstat.udps_badlen++;
253 			goto bad;
254 		}
255 	}
256 #endif
257 	else /* shouldn't happen */
258 		goto bad;
259 
260 	/*
261 	 * Save a copy of the IP header in case we want restore it
262 	 * for sending an ICMP error message in response.
263 	 */
264 	if (ip)
265 		save_ip = *ip;
266 
267 	/*
268 	 * Checksum extended UDP header and data.
269 	 * from W.R.Stevens: check incoming udp cksums even if
270 	 *	udpcksum is not set.
271 	 */
272 	savesum = uh->uh_sum;
273 #ifdef INET6
274 	if (ip6) {
275 		/* Be proactive about malicious use of IPv4 mapped address */
276 		if (IN6_IS_ADDR_V4MAPPED(&ip6->ip6_src) ||
277 		    IN6_IS_ADDR_V4MAPPED(&ip6->ip6_dst)) {
278 			/* XXX stat */
279 			goto bad;
280 		}
281 
282 		/*
283 		 * In IPv6, the UDP checksum is ALWAYS used.
284 		 */
285 		if (uh->uh_sum == 0) {
286 			udpstat.udps_nosum++;
287 			goto bad;
288 		}
289 		if ((uh->uh_sum = in6_cksum(m, IPPROTO_UDP, iphlen, len))) {
290 			udpstat.udps_badsum++;
291 			goto bad;
292 		}
293 	} else
294 #endif /* INET6 */
295 	if (uh->uh_sum) {
296 		if ((m->m_pkthdr.csum_flags & M_UDP_CSUM_IN_OK) == 0) {
297 			if (m->m_pkthdr.csum_flags & M_UDP_CSUM_IN_BAD) {
298 				udpstat.udps_badsum++;
299 				udpstat.udps_inhwcsum++;
300 				m_freem(m);
301 				return;
302 			}
303 
304 			if ((uh->uh_sum = in4_cksum(m, IPPROTO_UDP,
305 			    iphlen, len))) {
306 				udpstat.udps_badsum++;
307 				m_freem(m);
308 				return;
309 			}
310 		} else {
311 			m->m_pkthdr.csum_flags &= ~M_UDP_CSUM_IN_OK;
312 			udpstat.udps_inhwcsum++;
313 		}
314 	} else
315 		udpstat.udps_nosum++;
316 
317 #ifdef IPSEC
318 	if (udpencap_enable && udpencap_port &&
319 	    uh->uh_dport == htons(udpencap_port)) {
320 		u_int32_t spi;
321 		int skip = iphlen + sizeof(struct udphdr);
322 
323 		if (m->m_pkthdr.len - skip < sizeof(u_int32_t)) {
324 			/* packet too short */
325 			m_freem(m);
326 			return;
327 		}
328 		m_copydata(m, skip, sizeof(u_int32_t), (caddr_t) &spi);
329 		/*
330 		 * decapsulate if the SPI is not zero, otherwise pass
331 		 * to userland
332 		 */
333 		if (spi != 0) {
334 			if ((m = m_pullup2(m, skip)) == NULL) {
335 				udpstat.udps_hdrops++;
336 				return;
337 			}
338 
339 			/* remove the UDP header */
340 			bcopy(mtod(m, u_char *),
341 			    mtod(m, u_char *) + sizeof(struct udphdr), iphlen);
342 			m_adj(m, sizeof(struct udphdr));
343 			skip -= sizeof(struct udphdr);
344 
345 			espstat.esps_udpencin++;
346 			ipsec_common_input(m, skip, offsetof(struct ip, ip_p),
347 			    srcsa.sa.sa_family, IPPROTO_ESP, 1);
348 			return;
349 		}
350 	}
351 #endif
352 
353 	switch (srcsa.sa.sa_family) {
354 	case AF_INET:
355 		bzero(&srcsa, sizeof(struct sockaddr_in));
356 		srcsa.sin.sin_len = sizeof(struct sockaddr_in);
357 		srcsa.sin.sin_family = AF_INET;
358 		srcsa.sin.sin_port = uh->uh_sport;
359 		srcsa.sin.sin_addr = ip->ip_src;
360 
361 		bzero(&dstsa, sizeof(struct sockaddr_in));
362 		dstsa.sin.sin_len = sizeof(struct sockaddr_in);
363 		dstsa.sin.sin_family = AF_INET;
364 		dstsa.sin.sin_port = uh->uh_dport;
365 		dstsa.sin.sin_addr = ip->ip_dst;
366 		break;
367 #ifdef INET6
368 	case AF_INET6:
369 		bzero(&srcsa, sizeof(struct sockaddr_in6));
370 		srcsa.sin6.sin6_len = sizeof(struct sockaddr_in6);
371 		srcsa.sin6.sin6_family = AF_INET6;
372 		srcsa.sin6.sin6_port = uh->uh_sport;
373 #if 0 /*XXX inbound flowinfo */
374 		srcsa.sin6.sin6_flowinfo = htonl(0x0fffffff) & ip6->ip6_flow;
375 #endif
376 		/* KAME hack: recover scopeid */
377 		(void)in6_recoverscope(&srcsa.sin6, &ip6->ip6_src,
378 		    m->m_pkthdr.rcvif);
379 
380 		bzero(&dstsa, sizeof(struct sockaddr_in6));
381 		dstsa.sin6.sin6_len = sizeof(struct sockaddr_in6);
382 		dstsa.sin6.sin6_family = AF_INET6;
383 		dstsa.sin6.sin6_port = uh->uh_dport;
384 		/* KAME hack: recover scopeid */
385 		(void)in6_recoverscope(&dstsa.sin6, &ip6->ip6_dst,
386 		    m->m_pkthdr.rcvif);
387 		break;
388 #endif /* INET6 */
389 	}
390 
391 #ifdef INET6
392 	if ((ip6 && IN6_IS_ADDR_MULTICAST(&ip6->ip6_dst)) ||
393 	    (ip && IN_MULTICAST(ip->ip_dst.s_addr)) ||
394 	    (ip && in_broadcast(ip->ip_dst, m->m_pkthdr.rcvif))) {
395 #else /* INET6 */
396 	if (IN_MULTICAST(ip->ip_dst.s_addr) ||
397 	    in_broadcast(ip->ip_dst, m->m_pkthdr.rcvif)) {
398 #endif /* INET6 */
399 		struct inpcb *last;
400 		/*
401 		 * Deliver a multicast or broadcast datagram to *all* sockets
402 		 * for which the local and remote addresses and ports match
403 		 * those of the incoming datagram.  This allows more than
404 		 * one process to receive multi/broadcasts on the same port.
405 		 * (This really ought to be done for unicast datagrams as
406 		 * well, but that would cause problems with existing
407 		 * applications that open both address-specific sockets and
408 		 * a wildcard socket listening to the same port -- they would
409 		 * end up receiving duplicates of every unicast datagram.
410 		 * Those applications open the multiple sockets to overcome an
411 		 * inadequacy of the UDP socket interface, but for backwards
412 		 * compatibility we avoid the problem here rather than
413 		 * fixing the interface.  Maybe 4.5BSD will remedy this?)
414 		 */
415 
416 		iphlen += sizeof(struct udphdr);
417 
418 		/*
419 		 * Locate pcb(s) for datagram.
420 		 * (Algorithm copied from raw_intr().)
421 		 */
422 		last = NULL;
423 		CIRCLEQ_FOREACH(inp, &udbtable.inpt_queue, inp_queue) {
424 #ifdef INET6
425 			/* don't accept it if AF does not match */
426 			if (ip6 && !(inp->inp_flags & INP_IPV6))
427 				continue;
428 			if (!ip6 && (inp->inp_flags & INP_IPV6))
429 				continue;
430 #endif
431 			if (inp->inp_lport != uh->uh_dport)
432 				continue;
433 #ifdef INET6
434 			if (ip6) {
435 				if (!IN6_IS_ADDR_UNSPECIFIED(&inp->inp_laddr6))
436 					if (!IN6_ARE_ADDR_EQUAL(&inp->inp_laddr6,
437 					    &ip6->ip6_dst))
438 						continue;
439 			} else
440 #endif /* INET6 */
441 			if (inp->inp_laddr.s_addr != INADDR_ANY) {
442 				if (inp->inp_laddr.s_addr != ip->ip_dst.s_addr)
443 					continue;
444 			}
445 #ifdef INET6
446 			if (ip6) {
447 				if (!IN6_IS_ADDR_UNSPECIFIED(&inp->inp_faddr6))
448 					if (!IN6_ARE_ADDR_EQUAL(&inp->inp_faddr6,
449 					    &ip6->ip6_src) ||
450 					    inp->inp_fport != uh->uh_sport)
451 						continue;
452 			} else
453 #endif /* INET6 */
454 			if (inp->inp_faddr.s_addr != INADDR_ANY) {
455 				if (inp->inp_faddr.s_addr !=
456 				    ip->ip_src.s_addr ||
457 				    inp->inp_fport != uh->uh_sport)
458 					continue;
459 			}
460 
461 			if (last != NULL) {
462 				struct mbuf *n;
463 
464 				if ((n = m_copy(m, 0, M_COPYALL)) != NULL) {
465 #ifdef INET6
466 					if (ip6 && (last->inp_flags &
467 					    IN6P_CONTROLOPTS ||
468 					    last->inp_socket->so_options &
469 					    SO_TIMESTAMP))
470 						ip6_savecontrol(last, n, &opts);
471 #endif /* INET6 */
472 					if (ip && (last->inp_flags &
473 					    INP_CONTROLOPTS ||
474 					    last->inp_socket->so_options &
475 					    SO_TIMESTAMP))
476 						ip_savecontrol(last, &opts,
477 						    ip, n);
478 
479 					m_adj(n, iphlen);
480 					if (sbappendaddr(
481 					    &last->inp_socket->so_rcv,
482 					    &srcsa.sa, n, opts) == 0) {
483 						m_freem(n);
484 						if (opts)
485 							m_freem(opts);
486 						udpstat.udps_fullsock++;
487 					} else
488 						sorwakeup(last->inp_socket);
489 					opts = NULL;
490 				}
491 			}
492 			last = inp;
493 			/*
494 			 * Don't look for additional matches if this one does
495 			 * not have either the SO_REUSEPORT or SO_REUSEADDR
496 			 * socket options set.  This heuristic avoids searching
497 			 * through all pcbs in the common case of a non-shared
498 			 * port.  It * assumes that an application will never
499 			 * clear these options after setting them.
500 			 */
501 			if ((last->inp_socket->so_options & (SO_REUSEPORT |
502 			    SO_REUSEADDR)) == 0)
503 				break;
504 		}
505 
506 		if (last == NULL) {
507 			/*
508 			 * No matching pcb found; discard datagram.
509 			 * (No need to send an ICMP Port Unreachable
510 			 * for a broadcast or multicast datgram.)
511 			 */
512 			udpstat.udps_noportbcast++;
513 			goto bad;
514 		}
515 
516 #ifdef INET6
517 		if (ip6 && (last->inp_flags & IN6P_CONTROLOPTS ||
518 		    last->inp_socket->so_options & SO_TIMESTAMP))
519 			ip6_savecontrol(last, m, &opts);
520 #endif /* INET6 */
521 		if (ip && (last->inp_flags & INP_CONTROLOPTS ||
522 		    last->inp_socket->so_options & SO_TIMESTAMP))
523 			ip_savecontrol(last, &opts, ip, m);
524 
525 		m_adj(m, iphlen);
526 		if (sbappendaddr(&last->inp_socket->so_rcv,
527 		    &srcsa.sa, m, opts) == 0) {
528 			udpstat.udps_fullsock++;
529 			goto bad;
530 		}
531 		sorwakeup(last->inp_socket);
532 		return;
533 	}
534 	/*
535 	 * Locate pcb for datagram.
536 	 */
537 #if 0
538 	if (m->m_pkthdr.pf.statekey)
539 		inp = ((struct pf_state_key *)m->m_pkthdr.pf.statekey)->inp;
540 #endif
541 	if (inp == NULL) {
542 #ifdef INET6
543 		if (ip6)
544 			inp = in6_pcbhashlookup(&udbtable, &ip6->ip6_src,
545 			    uh->uh_sport, &ip6->ip6_dst, uh->uh_dport);
546 		else
547 #endif /* INET6 */
548 		inp = in_pcbhashlookup(&udbtable, ip->ip_src, uh->uh_sport,
549 		    ip->ip_dst, uh->uh_dport);
550 #if NPF > 0
551 		if (m->m_pkthdr.pf.statekey && inp) {
552 			((struct pf_state_key *)m->m_pkthdr.pf.statekey)->inp =
553 			    inp;
554 			inp->inp_pf_sk = m->m_pkthdr.pf.statekey;
555 		}
556 #endif
557 	}
558 	if (inp == 0) {
559 		int	inpl_reverse = 0;
560 		if (m->m_pkthdr.pf.flags & PF_TAG_TRANSLATE_LOCALHOST)
561 			inpl_reverse = 1;
562 		++udpstat.udps_pcbhashmiss;
563 #ifdef INET6
564 		if (ip6) {
565 			inp = in6_pcblookup_listen(&udbtable,
566 			    &ip6->ip6_dst, uh->uh_dport, inpl_reverse, m);
567 		} else
568 #endif /* INET6 */
569 		inp = in_pcblookup_listen(&udbtable,
570 		    ip->ip_dst, uh->uh_dport, inpl_reverse, m);
571 		if (inp == 0) {
572 			udpstat.udps_noport++;
573 			if (m->m_flags & (M_BCAST | M_MCAST)) {
574 				udpstat.udps_noportbcast++;
575 				goto bad;
576 			}
577 #ifdef INET6
578 			if (ip6) {
579 				uh->uh_sum = savesum;
580 				icmp6_error(m, ICMP6_DST_UNREACH,
581 				    ICMP6_DST_UNREACH_NOPORT,0);
582 			} else
583 #endif /* INET6 */
584 			{
585 				*ip = save_ip;
586 				uh->uh_sum = savesum;
587 				icmp_error(m, ICMP_UNREACH, ICMP_UNREACH_PORT,
588 				    0, 0);
589 			}
590 			return;
591 		}
592 	}
593 
594 #ifdef IPSEC
595 	mtag = m_tag_find(m, PACKET_TAG_IPSEC_IN_DONE, NULL);
596 	s = splnet();
597 	if (mtag != NULL) {
598 		tdbi = (struct tdb_ident *)(mtag + 1);
599 		tdb = gettdb(tdbi->spi, &tdbi->dst, tdbi->proto);
600 	} else
601 		tdb = NULL;
602 	ipsp_spd_lookup(m, srcsa.sa.sa_family, iphlen, &error,
603 	    IPSP_DIRECTION_IN, tdb, inp);
604 	if (error) {
605 		splx(s);
606 		goto bad;
607 	}
608 
609 	/* Latch SA only if the socket is connected */
610 	if (inp->inp_tdb_in != tdb &&
611 	    (inp->inp_socket->so_state & SS_ISCONNECTED)) {
612 		if (tdb) {
613 			tdb_add_inp(tdb, inp, 1);
614 			if (inp->inp_ipo == NULL) {
615 				inp->inp_ipo = ipsec_add_policy(inp,
616 				    srcsa.sa.sa_family, IPSP_DIRECTION_OUT);
617 				if (inp->inp_ipo == NULL) {
618 					splx(s);
619 					goto bad;
620 				}
621 			}
622 			if (inp->inp_ipo->ipo_dstid == NULL &&
623 			    tdb->tdb_srcid != NULL) {
624 				inp->inp_ipo->ipo_dstid = tdb->tdb_srcid;
625 				tdb->tdb_srcid->ref_count++;
626 			}
627 			if (inp->inp_ipsec_remotecred == NULL &&
628 			    tdb->tdb_remote_cred != NULL) {
629 				inp->inp_ipsec_remotecred =
630 				    tdb->tdb_remote_cred;
631 				tdb->tdb_remote_cred->ref_count++;
632 			}
633 			if (inp->inp_ipsec_remoteauth == NULL &&
634 			    tdb->tdb_remote_auth != NULL) {
635 				inp->inp_ipsec_remoteauth =
636 				    tdb->tdb_remote_auth;
637 				tdb->tdb_remote_auth->ref_count++;
638 			}
639 		} else { /* Just reset */
640 			TAILQ_REMOVE(&inp->inp_tdb_in->tdb_inp_in, inp,
641 			    inp_tdb_in_next);
642 			inp->inp_tdb_in = NULL;
643 		}
644 	}
645 	splx(s);
646 #endif /*IPSEC */
647 
648 	opts = NULL;
649 #ifdef INET6
650 	if (ip6 && (inp->inp_flags & IN6P_CONTROLOPTS ||
651 	    inp->inp_socket->so_options & SO_TIMESTAMP))
652 		ip6_savecontrol(inp, m, &opts);
653 #endif /* INET6 */
654 	if (ip && (inp->inp_flags & INP_CONTROLOPTS ||
655 	    inp->inp_socket->so_options & SO_TIMESTAMP))
656 		ip_savecontrol(inp, &opts, ip, m);
657 	if (ip && (inp->inp_flags & INP_RECVDSTPORT)) {
658 		struct mbuf **mp = &opts;
659 
660 		while (*mp)
661 			mp = &(*mp)->m_next;
662 		*mp = sbcreatecontrol((caddr_t)&uh->uh_dport, sizeof(u_int16_t),
663 		    IP_RECVDSTPORT, IPPROTO_IP);
664 	}
665 
666 	iphlen += sizeof(struct udphdr);
667 	m_adj(m, iphlen);
668 	if (sbappendaddr(&inp->inp_socket->so_rcv, &srcsa.sa, m, opts) == 0) {
669 		udpstat.udps_fullsock++;
670 		goto bad;
671 	}
672 	sorwakeup(inp->inp_socket);
673 	return;
674 bad:
675 	m_freem(m);
676 	if (opts)
677 		m_freem(opts);
678 }
679 
680 /*
681  * Notify a udp user of an asynchronous error;
682  * just wake up so that he can collect error status.
683  */
684 void
685 udp_notify(struct inpcb *inp, int errno)
686 {
687 	inp->inp_socket->so_error = errno;
688 	sorwakeup(inp->inp_socket);
689 	sowwakeup(inp->inp_socket);
690 }
691 
692 #ifdef INET6
693 void
694 udp6_ctlinput(int cmd, struct sockaddr *sa, void *d)
695 {
696 	struct udphdr uh;
697 	struct sockaddr_in6 sa6;
698 	struct ip6_hdr *ip6;
699 	struct mbuf *m;
700 	int off;
701 	void *cmdarg;
702 	struct ip6ctlparam *ip6cp = NULL;
703 	struct udp_portonly {
704 		u_int16_t uh_sport;
705 		u_int16_t uh_dport;
706 	} *uhp;
707 	void (*notify)(struct inpcb *, int) = udp_notify;
708 
709 	if (sa == NULL)
710 		return;
711 	if (sa->sa_family != AF_INET6 ||
712 	    sa->sa_len != sizeof(struct sockaddr_in6))
713 		return;
714 
715 	if ((unsigned)cmd >= PRC_NCMDS)
716 		return;
717 	if (PRC_IS_REDIRECT(cmd))
718 		notify = in_rtchange, d = NULL;
719 	else if (cmd == PRC_HOSTDEAD)
720 		d = NULL;
721 	else if (cmd == PRC_MSGSIZE)
722 		; /* special code is present, see below */
723 	else if (inet6ctlerrmap[cmd] == 0)
724 		return;
725 
726 	/* if the parameter is from icmp6, decode it. */
727 	if (d != NULL) {
728 		ip6cp = (struct ip6ctlparam *)d;
729 		m = ip6cp->ip6c_m;
730 		ip6 = ip6cp->ip6c_ip6;
731 		off = ip6cp->ip6c_off;
732 		cmdarg = ip6cp->ip6c_cmdarg;
733 	} else {
734 		m = NULL;
735 		ip6 = NULL;
736 		cmdarg = NULL;
737 		/* XXX: translate addresses into internal form */
738 		sa6 = *(struct sockaddr_in6 *)sa;
739 #ifndef SCOPEDROUTING
740 		if (in6_embedscope(&sa6.sin6_addr, &sa6, NULL, NULL)) {
741 			/* should be impossible */
742 			return;
743 		}
744 #endif
745 	}
746 
747 	if (ip6cp && ip6cp->ip6c_finaldst) {
748 		bzero(&sa6, sizeof(sa6));
749 		sa6.sin6_family = AF_INET6;
750 		sa6.sin6_len = sizeof(sa6);
751 		sa6.sin6_addr = *ip6cp->ip6c_finaldst;
752 		/* XXX: assuming M is valid in this case */
753 		sa6.sin6_scope_id = in6_addr2scopeid(m->m_pkthdr.rcvif,
754 		    ip6cp->ip6c_finaldst);
755 #ifndef SCOPEDROUTING
756 		if (in6_embedscope(ip6cp->ip6c_finaldst, &sa6, NULL, NULL)) {
757 			/* should be impossible */
758 			return;
759 		}
760 #endif
761 	} else {
762 		/* XXX: translate addresses into internal form */
763 		sa6 = *(struct sockaddr_in6 *)sa;
764 #ifndef SCOPEDROUTING
765 		if (in6_embedscope(&sa6.sin6_addr, &sa6, NULL, NULL)) {
766 			/* should be impossible */
767 			return;
768 		}
769 #endif
770 	}
771 
772 	if (ip6) {
773 		/*
774 		 * XXX: We assume that when IPV6 is non NULL,
775 		 * M and OFF are valid.
776 		 */
777 		struct sockaddr_in6 sa6_src;
778 
779 		/* check if we can safely examine src and dst ports */
780 		if (m->m_pkthdr.len < off + sizeof(*uhp))
781 			return;
782 
783 		bzero(&uh, sizeof(uh));
784 		m_copydata(m, off, sizeof(*uhp), (caddr_t)&uh);
785 
786 		bzero(&sa6_src, sizeof(sa6_src));
787 		sa6_src.sin6_family = AF_INET6;
788 		sa6_src.sin6_len = sizeof(sa6_src);
789 		sa6_src.sin6_addr = ip6->ip6_src;
790 		sa6_src.sin6_scope_id = in6_addr2scopeid(m->m_pkthdr.rcvif,
791 		    &ip6->ip6_src);
792 #ifndef SCOPEDROUTING
793 		if (in6_embedscope(&sa6_src.sin6_addr, &sa6_src, NULL, NULL)) {
794 			/* should be impossible */
795 			return;
796 		}
797 #endif
798 
799 		if (cmd == PRC_MSGSIZE) {
800 			int valid = 0;
801 
802 			/*
803 			 * Check to see if we have a valid UDP socket
804 			 * corresponding to the address in the ICMPv6 message
805 			 * payload.
806 			 */
807 			if (in6_pcbhashlookup(&udbtable, &sa6.sin6_addr,
808 			    uh.uh_dport, &sa6_src.sin6_addr, uh.uh_sport))
809 				valid = 1;
810 #if 0
811 			/*
812 			 * As the use of sendto(2) is fairly popular,
813 			 * we may want to allow non-connected pcb too.
814 			 * But it could be too weak against attacks...
815 			 * We should at least check if the local address (= s)
816 			 * is really ours.
817 			 */
818 			else if (in6_pcblookup_listen(&udbtable,
819 			    &sa6_src.sin6_addr, uh.uh_sport, 0);
820 				valid = 1;
821 #endif
822 
823 			/*
824 			 * Depending on the value of "valid" and routing table
825 			 * size (mtudisc_{hi,lo}wat), we will:
826 			 * - recalculate the new MTU and create the
827 			 *   corresponding routing entry, or
828 			 * - ignore the MTU change notification.
829 			 */
830 			icmp6_mtudisc_update((struct ip6ctlparam *)d, valid);
831 
832 			/*
833 			 * regardless of if we called icmp6_mtudisc_update(),
834 			 * we need to call in6_pcbnotify(), to notify path
835 			 * MTU change to the userland (2292bis-02), because
836 			 * some unconnected sockets may share the same
837 			 * destination and want to know the path MTU.
838 			 */
839 		}
840 
841 		(void) in6_pcbnotify(&udbtable, (struct sockaddr *)&sa6,
842 		    uh.uh_dport, (struct sockaddr *)&sa6_src,
843 		    uh.uh_sport, cmd, cmdarg, notify);
844 	} else {
845 		(void) in6_pcbnotify(&udbtable, (struct sockaddr *)&sa6, 0,
846 		    (struct sockaddr *)&sa6_any, 0, cmd, cmdarg, notify);
847 	}
848 }
849 #endif
850 
851 void *
852 udp_ctlinput(int cmd, struct sockaddr *sa, void *v)
853 {
854 	struct ip *ip = v;
855 	struct udphdr *uhp;
856 	struct in_addr faddr;
857 	struct inpcb *inp;
858 	extern int inetctlerrmap[];
859 	void (*notify)(struct inpcb *, int) = udp_notify;
860 	int errno;
861 
862 	if (sa == NULL)
863 		return NULL;
864 	if (sa->sa_family != AF_INET ||
865 	    sa->sa_len != sizeof(struct sockaddr_in))
866 		return NULL;
867 	faddr = satosin(sa)->sin_addr;
868 	if (faddr.s_addr == INADDR_ANY)
869 		return NULL;
870 
871 	if ((unsigned)cmd >= PRC_NCMDS)
872 		return NULL;
873 	errno = inetctlerrmap[cmd];
874 	if (PRC_IS_REDIRECT(cmd))
875 		notify = in_rtchange, ip = 0;
876 	else if (cmd == PRC_HOSTDEAD)
877 		ip = 0;
878 	else if (errno == 0)
879 		return NULL;
880 	if (ip) {
881 		uhp = (struct udphdr *)((caddr_t)ip + (ip->ip_hl << 2));
882 
883 #ifdef IPSEC
884 		/* PMTU discovery for udpencap */
885 		if (cmd == PRC_MSGSIZE && ip_mtudisc && udpencap_enable &&
886 		    udpencap_port && uhp->uh_sport == htons(udpencap_port)) {
887 			udpencap_ctlinput(cmd, sa, v);
888 			return (NULL);
889 		}
890 #endif
891 		inp = in_pcbhashlookup(&udbtable,
892 		    ip->ip_dst, uhp->uh_dport, ip->ip_src, uhp->uh_sport);
893 		if (inp && inp->inp_socket != NULL)
894 			notify(inp, errno);
895 	} else
896 		in_pcbnotifyall(&udbtable, sa, errno, notify);
897 	return (NULL);
898 }
899 
900 int
901 udp_output(struct mbuf *m, ...)
902 {
903 	struct inpcb *inp;
904 	struct mbuf *addr, *control;
905 	struct udpiphdr *ui;
906 	int len = m->m_pkthdr.len;
907 	struct in_addr laddr;
908 	int s = 0, error = 0;
909 	va_list ap;
910 
911 	va_start(ap, m);
912 	inp = va_arg(ap, struct inpcb *);
913 	addr = va_arg(ap, struct mbuf *);
914 	control = va_arg(ap, struct mbuf *);
915 	va_end(ap);
916 
917 #ifdef DIAGNOSTIC
918 	if ((inp->inp_flags & INP_IPV6) != 0)
919 		panic("IPv6 inpcb to udp_output");
920 #endif
921 
922 	/*
923 	 * Compute the packet length of the IP header, and
924 	 * punt if the length looks bogus.
925 	 */
926 	if ((len + sizeof(struct udpiphdr)) > IP_MAXPACKET) {
927 		error = EMSGSIZE;
928 		goto release;
929 	}
930 
931 	if (addr) {
932 		laddr = inp->inp_laddr;
933 		if (inp->inp_faddr.s_addr != INADDR_ANY) {
934 			error = EISCONN;
935 			goto release;
936 		}
937 		/*
938 		 * Must block input while temporarily connected.
939 		 */
940 		s = splsoftnet();
941 		error = in_pcbconnect(inp, addr);
942 		if (error) {
943 			splx(s);
944 			goto release;
945 		}
946 	} else {
947 		if (inp->inp_faddr.s_addr == INADDR_ANY) {
948 			error = ENOTCONN;
949 			goto release;
950 		}
951 	}
952 	/*
953 	 * Calculate data length and get a mbuf
954 	 * for UDP and IP headers.
955 	 */
956 	M_PREPEND(m, sizeof(struct udpiphdr), M_DONTWAIT);
957 	if (m == 0) {
958 		error = ENOBUFS;
959 		goto bail;
960 	}
961 
962 	/*
963 	 * Fill in mbuf with extended UDP header
964 	 * and addresses and length put into network format.
965 	 */
966 	ui = mtod(m, struct udpiphdr *);
967 	bzero(ui->ui_x1, sizeof ui->ui_x1);
968 	ui->ui_pr = IPPROTO_UDP;
969 	ui->ui_len = htons((u_int16_t)len + sizeof (struct udphdr));
970 	ui->ui_src = inp->inp_laddr;
971 	ui->ui_dst = inp->inp_faddr;
972 	ui->ui_sport = inp->inp_lport;
973 	ui->ui_dport = inp->inp_fport;
974 	ui->ui_ulen = ui->ui_len;
975 
976 	/*
977 	 * Compute the pseudo-header checksum; defer further checksumming
978 	 * until ip_output() or hardware (if it exists).
979 	 */
980 	if (udpcksum) {
981 		m->m_pkthdr.csum_flags |= M_UDPV4_CSUM_OUT;
982 		ui->ui_sum = in_cksum_phdr(ui->ui_src.s_addr,
983 		    ui->ui_dst.s_addr, htons((u_int16_t)len +
984 		    sizeof (struct udphdr) + IPPROTO_UDP));
985 	} else
986 		ui->ui_sum = 0;
987 	((struct ip *)ui)->ip_len = htons(sizeof (struct udpiphdr) + len);
988 	((struct ip *)ui)->ip_ttl = inp->inp_ip.ip_ttl;
989 	((struct ip *)ui)->ip_tos = inp->inp_ip.ip_tos;
990 
991 	udpstat.udps_opackets++;
992 	error = ip_output(m, inp->inp_options, &inp->inp_route,
993 	    inp->inp_socket->so_options &
994 	    (SO_DONTROUTE | SO_BROADCAST | SO_JUMBO),
995 	    inp->inp_moptions, inp);
996 
997 bail:
998 	if (addr) {
999 		inp->inp_laddr = laddr;
1000 		in_pcbdisconnect(inp);
1001 		splx(s);
1002 	}
1003 	if (control)
1004 		m_freem(control);
1005 	return (error);
1006 
1007 release:
1008 	m_freem(m);
1009 	if (control)
1010 		m_freem(control);
1011 	return (error);
1012 }
1013 
1014 /*ARGSUSED*/
1015 int
1016 udp_usrreq(struct socket *so, int req, struct mbuf *m, struct mbuf *addr,
1017     struct mbuf *control, struct proc *p)
1018 {
1019 	struct inpcb *inp = sotoinpcb(so);
1020 	int error = 0;
1021 	int s;
1022 
1023 	if (req == PRU_CONTROL) {
1024 #ifdef INET6
1025 		if (inp->inp_flags & INP_IPV6)
1026 			return (in6_control(so, (u_long)m, (caddr_t)addr,
1027 			    (struct ifnet *)control, 0));
1028 		else
1029 #endif /* INET6 */
1030 			return (in_control(so, (u_long)m, (caddr_t)addr,
1031 			    (struct ifnet *)control));
1032 	}
1033 	if (inp == NULL && req != PRU_ATTACH) {
1034 		error = EINVAL;
1035 		goto release;
1036 	}
1037 	/*
1038 	 * Note: need to block udp_input while changing
1039 	 * the udp pcb queue and/or pcb addresses.
1040 	 */
1041 	switch (req) {
1042 
1043 	case PRU_ATTACH:
1044 		if (inp != NULL) {
1045 			error = EINVAL;
1046 			break;
1047 		}
1048 		s = splsoftnet();
1049 		error = in_pcballoc(so, &udbtable);
1050 		splx(s);
1051 		if (error)
1052 			break;
1053 		error = soreserve(so, udp_sendspace, udp_recvspace);
1054 		if (error)
1055 			break;
1056 #ifdef INET6
1057 		if (((struct inpcb *)so->so_pcb)->inp_flags & INP_IPV6)
1058 			((struct inpcb *) so->so_pcb)->inp_ipv6.ip6_hlim =
1059 			    ip6_defhlim;
1060 		else
1061 #endif /* INET6 */
1062 			((struct inpcb *) so->so_pcb)->inp_ip.ip_ttl = ip_defttl;
1063 		break;
1064 
1065 	case PRU_DETACH:
1066 		udp_detach(inp);
1067 		break;
1068 
1069 	case PRU_BIND:
1070 		s = splsoftnet();
1071 #ifdef INET6
1072 		if (inp->inp_flags & INP_IPV6)
1073 			error = in6_pcbbind(inp, addr, p);
1074 		else
1075 #endif
1076 			error = in_pcbbind(inp, addr, p);
1077 		splx(s);
1078 		break;
1079 
1080 	case PRU_LISTEN:
1081 		error = EOPNOTSUPP;
1082 		break;
1083 
1084 	case PRU_CONNECT:
1085 #ifdef INET6
1086 		if (inp->inp_flags & INP_IPV6) {
1087 			if (!IN6_IS_ADDR_UNSPECIFIED(&inp->inp_faddr6)) {
1088 				error = EISCONN;
1089 				break;
1090 			}
1091 			s = splsoftnet();
1092 			error = in6_pcbconnect(inp, addr);
1093 			splx(s);
1094 		} else
1095 #endif /* INET6 */
1096 		{
1097 			if (inp->inp_faddr.s_addr != INADDR_ANY) {
1098 				error = EISCONN;
1099 				break;
1100 			}
1101 			s = splsoftnet();
1102 			error = in_pcbconnect(inp, addr);
1103 			splx(s);
1104 		}
1105 
1106 		if (error == 0)
1107 			soisconnected(so);
1108 		break;
1109 
1110 	case PRU_CONNECT2:
1111 		error = EOPNOTSUPP;
1112 		break;
1113 
1114 	case PRU_ACCEPT:
1115 		error = EOPNOTSUPP;
1116 		break;
1117 
1118 	case PRU_DISCONNECT:
1119 #ifdef INET6
1120 		if (inp->inp_flags & INP_IPV6) {
1121 			if (IN6_IS_ADDR_UNSPECIFIED(&inp->inp_faddr6)) {
1122 				error = ENOTCONN;
1123 				break;
1124 			}
1125 		} else
1126 #endif /* INET6 */
1127 		{
1128 			if (inp->inp_faddr.s_addr == INADDR_ANY) {
1129 				error = ENOTCONN;
1130 				break;
1131 			}
1132 		}
1133 
1134 		s = splsoftnet();
1135 #ifdef INET6
1136 		if (inp->inp_flags & INP_IPV6)
1137 			inp->inp_laddr6 = in6addr_any;
1138 		else
1139 #endif /* INET6 */
1140 			inp->inp_laddr.s_addr = INADDR_ANY;
1141 		in_pcbdisconnect(inp);
1142 
1143 		splx(s);
1144 		so->so_state &= ~SS_ISCONNECTED;		/* XXX */
1145 		break;
1146 
1147 	case PRU_SHUTDOWN:
1148 		socantsendmore(so);
1149 		break;
1150 
1151 	case PRU_SEND:
1152 #ifdef INET6
1153 		if (inp->inp_flags & INP_IPV6)
1154 			return (udp6_output(inp, m, addr, control));
1155 		else
1156 			return (udp_output(m, inp, addr, control));
1157 #else
1158 		return (udp_output(m, inp, addr, control));
1159 #endif
1160 
1161 	case PRU_ABORT:
1162 		soisdisconnected(so);
1163 		udp_detach(inp);
1164 		break;
1165 
1166 	case PRU_SOCKADDR:
1167 #ifdef INET6
1168 		if (inp->inp_flags & INP_IPV6)
1169 			in6_setsockaddr(inp, addr);
1170 		else
1171 #endif /* INET6 */
1172 			in_setsockaddr(inp, addr);
1173 		break;
1174 
1175 	case PRU_PEERADDR:
1176 #ifdef INET6
1177 		if (inp->inp_flags & INP_IPV6)
1178 			in6_setpeeraddr(inp, addr);
1179 		else
1180 #endif /* INET6 */
1181 			in_setpeeraddr(inp, addr);
1182 		break;
1183 
1184 	case PRU_SENSE:
1185 		/*
1186 		 * stat: don't bother with a blocksize.
1187 		 */
1188 		/*
1189 		 * Perhaps Path MTU might be returned for a connected
1190 		 * UDP socket in this case.
1191 		 */
1192 		return (0);
1193 
1194 	case PRU_SENDOOB:
1195 	case PRU_FASTTIMO:
1196 	case PRU_SLOWTIMO:
1197 	case PRU_PROTORCV:
1198 	case PRU_PROTOSEND:
1199 		error =  EOPNOTSUPP;
1200 		break;
1201 
1202 	case PRU_RCVD:
1203 	case PRU_RCVOOB:
1204 		return (EOPNOTSUPP);	/* do not free mbuf's */
1205 
1206 	default:
1207 		panic("udp_usrreq");
1208 	}
1209 
1210 release:
1211 	if (control) {
1212 		m_freem(control);
1213 	}
1214 	if (m)
1215 		m_freem(m);
1216 	return (error);
1217 }
1218 
1219 void
1220 udp_detach(struct inpcb *inp)
1221 {
1222 	int s = splsoftnet();
1223 
1224 	in_pcbdetach(inp);
1225 	splx(s);
1226 }
1227 
1228 /*
1229  * Sysctl for udp variables.
1230  */
1231 int
1232 udp_sysctl(int *name, u_int namelen, void *oldp, size_t *oldlenp, void *newp,
1233     size_t newlen)
1234 {
1235 	/* All sysctl names at this level are terminal. */
1236 	if (namelen != 1)
1237 		return (ENOTDIR);
1238 
1239 	switch (name[0]) {
1240 	case UDPCTL_BADDYNAMIC:
1241 		return (sysctl_struct(oldp, oldlenp, newp, newlen,
1242 		    baddynamicports.udp, sizeof(baddynamicports.udp)));
1243 
1244 	case UDPCTL_STATS:
1245 		if (newp != NULL)
1246 			return (EPERM);
1247 		return (sysctl_struct(oldp, oldlenp, newp, newlen,
1248 		    &udpstat, sizeof(udpstat)));
1249 
1250 	default:
1251 		if (name[0] < UDPCTL_MAXID)
1252 			return (sysctl_int_arr(udpctl_vars, name, namelen,
1253 			    oldp, oldlenp, newp, newlen));
1254 		return (ENOPROTOOPT);
1255 	}
1256 	/* NOTREACHED */
1257 }
1258