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