xref: /freebsd/sys/netinet/udp_usrreq.c (revision 48991a368427cadb9cdac39581d1676c29619c52)
1 /*
2  * Copyright (c) 1982, 1986, 1988, 1990, 1993, 1995
3  *	The Regents of the University of California.  All rights reserved.
4  *
5  * Redistribution and use in source and binary forms, with or without
6  * modification, are permitted provided that the following conditions
7  * are met:
8  * 1. Redistributions of source code must retain the above copyright
9  *    notice, this list of conditions and the following disclaimer.
10  * 2. Redistributions in binary form must reproduce the above copyright
11  *    notice, this list of conditions and the following disclaimer in the
12  *    documentation and/or other materials provided with the distribution.
13  * 3. All advertising materials mentioning features or use of this software
14  *    must display the following acknowledgement:
15  *	This product includes software developed by the University of
16  *	California, Berkeley and its contributors.
17  * 4. Neither the name of the University nor the names of its contributors
18  *    may be used to endorse or promote products derived from this software
19  *    without specific prior written permission.
20  *
21  * THIS SOFTWARE IS PROVIDED BY THE REGENTS AND CONTRIBUTORS ``AS IS'' AND
22  * ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
23  * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE
24  * ARE DISCLAIMED.  IN NO EVENT SHALL THE REGENTS OR CONTRIBUTORS BE LIABLE
25  * FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL
26  * DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS
27  * OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION)
28  * HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT
29  * LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY
30  * OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF
31  * SUCH DAMAGE.
32  *
33  *	@(#)udp_usrreq.c	8.6 (Berkeley) 5/23/95
34  *	$Id: udp_usrreq.c,v 1.15 1995/11/14 20:34:51 phk Exp $
35  */
36 
37 #include <sys/param.h>
38 #include <sys/systm.h>
39 #include <sys/malloc.h>
40 #include <sys/mbuf.h>
41 #include <sys/protosw.h>
42 #include <sys/socket.h>
43 #include <sys/socketvar.h>
44 #include <sys/errno.h>
45 #include <sys/stat.h>
46 #include <sys/queue.h>
47 #include <vm/vm.h>
48 #include <sys/kernel.h>
49 #include <sys/sysctl.h>
50 
51 #include <net/if.h>
52 #include <net/route.h>
53 
54 #include <netinet/in.h>
55 #include <netinet/in_systm.h>
56 #include <netinet/ip.h>
57 #include <netinet/in_pcb.h>
58 #include <netinet/in_var.h>
59 #include <netinet/ip_var.h>
60 #include <netinet/ip_icmp.h>
61 #include <netinet/udp.h>
62 #include <netinet/udp_var.h>
63 
64 /*
65  * UDP protocol implementation.
66  * Per RFC 768, August, 1980.
67  */
68 #ifndef	COMPAT_42
69 static int	udpcksum = 1;
70 #else
71 static int	udpcksum = 0;		/* XXX */
72 #endif
73 SYSCTL_INT(_net_inet_udp, UDPCTL_CHECKSUM, checksum, CTLFLAG_RW,
74 		&udpcksum, 0, "");
75 
76 struct	inpcbhead udb;		/* from udp_var.h */
77 struct	inpcbinfo udbinfo;
78 
79 #ifndef UDBHASHSIZE
80 #define UDBHASHSIZE 64
81 #endif
82 
83 struct	udpstat udpstat;	/* from udp_var.h */
84 SYSCTL_STRUCT(_net_inet_udp, UDPCTL_STATS, stats, CTLFLAG_RD,
85 	&udpstat, udpstat, "");
86 
87 static struct	sockaddr_in udp_in = { sizeof(udp_in), AF_INET };
88 
89 static	void udp_detach __P((struct inpcb *));
90 static	int udp_output __P((struct inpcb *, struct mbuf *, struct mbuf *,
91 			    struct mbuf *));
92 static	void udp_notify __P((struct inpcb *, int));
93 static	struct mbuf *udp_saveopt __P((caddr_t, int, int));
94 
95 void
96 udp_init()
97 {
98 	LIST_INIT(&udb);
99 	udbinfo.listhead = &udb;
100 	udbinfo.hashbase = phashinit(UDBHASHSIZE, M_PCB, &udbinfo.hashsize);
101 }
102 
103 void
104 udp_input(m, iphlen)
105 	register struct mbuf *m;
106 	int iphlen;
107 {
108 	register struct ip *ip;
109 	register struct udphdr *uh;
110 	register struct inpcb *inp;
111 	struct mbuf *opts = 0;
112 	int len;
113 	struct ip save_ip;
114 
115 	udpstat.udps_ipackets++;
116 
117 	/*
118 	 * Strip IP options, if any; should skip this,
119 	 * make available to user, and use on returned packets,
120 	 * but we don't yet have a way to check the checksum
121 	 * with options still present.
122 	 */
123 	if (iphlen > sizeof (struct ip)) {
124 		ip_stripoptions(m, (struct mbuf *)0);
125 		iphlen = sizeof(struct ip);
126 	}
127 
128 	/*
129 	 * Get IP and UDP header together in first mbuf.
130 	 */
131 	ip = mtod(m, struct ip *);
132 	if (m->m_len < iphlen + sizeof(struct udphdr)) {
133 		if ((m = m_pullup(m, iphlen + sizeof(struct udphdr))) == 0) {
134 			udpstat.udps_hdrops++;
135 			return;
136 		}
137 		ip = mtod(m, struct ip *);
138 	}
139 	uh = (struct udphdr *)((caddr_t)ip + iphlen);
140 
141 	/*
142 	 * Make mbuf data length reflect UDP length.
143 	 * If not enough data to reflect UDP length, drop.
144 	 */
145 	len = ntohs((u_short)uh->uh_ulen);
146 	if (ip->ip_len != len) {
147 		if (len > ip->ip_len || len < sizeof(struct udphdr)) {
148 			udpstat.udps_badlen++;
149 			goto bad;
150 		}
151 		m_adj(m, len - ip->ip_len);
152 		/* ip->ip_len = len; */
153 	}
154 	/*
155 	 * Save a copy of the IP header in case we want restore it
156 	 * for sending an ICMP error message in response.
157 	 */
158 	save_ip = *ip;
159 
160 	/*
161 	 * Checksum extended UDP header and data.
162 	 */
163 	if (uh->uh_sum) {
164 		((struct ipovly *)ip)->ih_next = 0;
165 		((struct ipovly *)ip)->ih_prev = 0;
166 		((struct ipovly *)ip)->ih_x1 = 0;
167 		((struct ipovly *)ip)->ih_len = uh->uh_ulen;
168 		uh->uh_sum = in_cksum(m, len + sizeof (struct ip));
169 		if (uh->uh_sum) {
170 			udpstat.udps_badsum++;
171 			m_freem(m);
172 			return;
173 		}
174 	}
175 
176 	if (IN_MULTICAST(ntohl(ip->ip_dst.s_addr)) ||
177 	    in_broadcast(ip->ip_dst, m->m_pkthdr.rcvif)) {
178 		struct socket *last;
179 		/*
180 		 * Deliver a multicast or broadcast datagram to *all* sockets
181 		 * for which the local and remote addresses and ports match
182 		 * those of the incoming datagram.  This allows more than
183 		 * one process to receive multi/broadcasts on the same port.
184 		 * (This really ought to be done for unicast datagrams as
185 		 * well, but that would cause problems with existing
186 		 * applications that open both address-specific sockets and
187 		 * a wildcard socket listening to the same port -- they would
188 		 * end up receiving duplicates of every unicast datagram.
189 		 * Those applications open the multiple sockets to overcome an
190 		 * inadequacy of the UDP socket interface, but for backwards
191 		 * compatibility we avoid the problem here rather than
192 		 * fixing the interface.  Maybe 4.5BSD will remedy this?)
193 		 */
194 
195 		/*
196 		 * Construct sockaddr format source address.
197 		 */
198 		udp_in.sin_port = uh->uh_sport;
199 		udp_in.sin_addr = ip->ip_src;
200 		m->m_len -= sizeof (struct udpiphdr);
201 		m->m_data += sizeof (struct udpiphdr);
202 		/*
203 		 * Locate pcb(s) for datagram.
204 		 * (Algorithm copied from raw_intr().)
205 		 */
206 		last = NULL;
207 		for (inp = udb.lh_first; inp != NULL; inp = inp->inp_list.le_next) {
208 			if (inp->inp_lport != uh->uh_dport)
209 				continue;
210 			if (inp->inp_laddr.s_addr != INADDR_ANY) {
211 				if (inp->inp_laddr.s_addr !=
212 				    ip->ip_dst.s_addr)
213 					continue;
214 			}
215 			if (inp->inp_faddr.s_addr != INADDR_ANY) {
216 				if (inp->inp_faddr.s_addr !=
217 				    ip->ip_src.s_addr ||
218 				    inp->inp_fport != uh->uh_sport)
219 					continue;
220 			}
221 
222 			if (last != NULL) {
223 				struct mbuf *n;
224 
225 				if ((n = m_copy(m, 0, M_COPYALL)) != NULL) {
226 					if (sbappendaddr(&last->so_rcv,
227 						(struct sockaddr *)&udp_in,
228 						n, (struct mbuf *)0) == 0) {
229 						m_freem(n);
230 						udpstat.udps_fullsock++;
231 					} else
232 						sorwakeup(last);
233 				}
234 			}
235 			last = inp->inp_socket;
236 			/*
237 			 * Don't look for additional matches if this one does
238 			 * not have either the SO_REUSEPORT or SO_REUSEADDR
239 			 * socket options set.  This heuristic avoids searching
240 			 * through all pcbs in the common case of a non-shared
241 			 * port.  It * assumes that an application will never
242 			 * clear these options after setting them.
243 			 */
244 			if ((last->so_options&(SO_REUSEPORT|SO_REUSEADDR) == 0))
245 				break;
246 		}
247 
248 		if (last == NULL) {
249 			/*
250 			 * No matching pcb found; discard datagram.
251 			 * (No need to send an ICMP Port Unreachable
252 			 * for a broadcast or multicast datgram.)
253 			 */
254 			udpstat.udps_noportbcast++;
255 			goto bad;
256 		}
257 		if (sbappendaddr(&last->so_rcv, (struct sockaddr *)&udp_in,
258 		     m, (struct mbuf *)0) == 0) {
259 			udpstat.udps_fullsock++;
260 			goto bad;
261 		}
262 		sorwakeup(last);
263 		return;
264 	}
265 	/*
266 	 * Locate pcb for datagram. First look for an exact match.
267 	 */
268 	inp = in_pcblookuphash(&udbinfo, ip->ip_src, uh->uh_sport,
269 	    ip->ip_dst, uh->uh_dport);
270 	/*
271 	 * ...and if that fails, do a wildcard search.
272 	 */
273 	if (inp == NULL) {
274 		inp = in_pcblookup(&udb, ip->ip_src, uh->uh_sport, ip->ip_dst,
275 		    uh->uh_dport, INPLOOKUP_WILDCARD);
276 	}
277 	if (inp == NULL) {
278 		udpstat.udps_noport++;
279 		if (m->m_flags & (M_BCAST | M_MCAST)) {
280 			udpstat.udps_noportbcast++;
281 			goto bad;
282 		}
283 		*ip = save_ip;
284 		icmp_error(m, ICMP_UNREACH, ICMP_UNREACH_PORT, 0, 0);
285 		return;
286 	}
287 
288 	/*
289 	 * Construct sockaddr format source address.
290 	 * Stuff source address and datagram in user buffer.
291 	 */
292 	udp_in.sin_port = uh->uh_sport;
293 	udp_in.sin_addr = ip->ip_src;
294 	if (inp->inp_flags & INP_CONTROLOPTS) {
295 		struct mbuf **mp = &opts;
296 
297 		if (inp->inp_flags & INP_RECVDSTADDR) {
298 			*mp = udp_saveopt((caddr_t) &ip->ip_dst,
299 			    sizeof(struct in_addr), IP_RECVDSTADDR);
300 			if (*mp)
301 				mp = &(*mp)->m_next;
302 		}
303 #ifdef notyet
304 		/* options were tossed above */
305 		if (inp->inp_flags & INP_RECVOPTS) {
306 			*mp = udp_saveopt((caddr_t) opts_deleted_above,
307 			    sizeof(struct in_addr), IP_RECVOPTS);
308 			if (*mp)
309 				mp = &(*mp)->m_next;
310 		}
311 		/* ip_srcroute doesn't do what we want here, need to fix */
312 		if (inp->inp_flags & INP_RECVRETOPTS) {
313 			*mp = udp_saveopt((caddr_t) ip_srcroute(),
314 			    sizeof(struct in_addr), IP_RECVRETOPTS);
315 			if (*mp)
316 				mp = &(*mp)->m_next;
317 		}
318 #endif
319 	}
320 	iphlen += sizeof(struct udphdr);
321 	m->m_len -= iphlen;
322 	m->m_pkthdr.len -= iphlen;
323 	m->m_data += iphlen;
324 	if (sbappendaddr(&inp->inp_socket->so_rcv, (struct sockaddr *)&udp_in,
325 	    m, opts) == 0) {
326 		udpstat.udps_fullsock++;
327 		goto bad;
328 	}
329 	sorwakeup(inp->inp_socket);
330 	return;
331 bad:
332 	m_freem(m);
333 	if (opts)
334 		m_freem(opts);
335 }
336 
337 /*
338  * Create a "control" mbuf containing the specified data
339  * with the specified type for presentation with a datagram.
340  */
341 struct mbuf *
342 udp_saveopt(p, size, type)
343 	caddr_t p;
344 	register int size;
345 	int type;
346 {
347 	register struct cmsghdr *cp;
348 	struct mbuf *m;
349 
350 	if ((m = m_get(M_DONTWAIT, MT_CONTROL)) == NULL)
351 		return ((struct mbuf *) NULL);
352 	cp = (struct cmsghdr *) mtod(m, struct cmsghdr *);
353 	(void)memcpy(CMSG_DATA(cp), p, size);
354 	size += sizeof(*cp);
355 	m->m_len = size;
356 	cp->cmsg_len = size;
357 	cp->cmsg_level = IPPROTO_IP;
358 	cp->cmsg_type = type;
359 	return (m);
360 }
361 
362 /*
363  * Notify a udp user of an asynchronous error;
364  * just wake up so that he can collect error status.
365  */
366 static void
367 udp_notify(inp, errno)
368 	register struct inpcb *inp;
369 	int errno;
370 {
371 	inp->inp_socket->so_error = errno;
372 	sorwakeup(inp->inp_socket);
373 	sowwakeup(inp->inp_socket);
374 }
375 
376 void
377 udp_ctlinput(cmd, sa, ip)
378 	int cmd;
379 	struct sockaddr *sa;
380 	register struct ip *ip;
381 {
382 	register struct udphdr *uh;
383 
384 	if (!PRC_IS_REDIRECT(cmd) &&
385 	    ((unsigned)cmd >= PRC_NCMDS || inetctlerrmap[cmd] == 0))
386 		return;
387 	if (ip) {
388 		uh = (struct udphdr *)((caddr_t)ip + (ip->ip_hl << 2));
389 		in_pcbnotify(&udb, sa, uh->uh_dport, ip->ip_src, uh->uh_sport,
390 			cmd, udp_notify);
391 	} else
392 		in_pcbnotify(&udb, sa, 0, zeroin_addr, 0, cmd, udp_notify);
393 }
394 
395 static int
396 udp_output(inp, m, addr, control)
397 	register struct inpcb *inp;
398 	register struct mbuf *m;
399 	struct mbuf *addr, *control;
400 {
401 	register struct udpiphdr *ui;
402 	register int len = m->m_pkthdr.len;
403 	struct in_addr laddr;
404 	int s = 0, error = 0;
405 
406 	if (control)
407 		m_freem(control);		/* XXX */
408 
409 	if (addr) {
410 		laddr = inp->inp_laddr;
411 		if (inp->inp_faddr.s_addr != INADDR_ANY) {
412 			error = EISCONN;
413 			goto release;
414 		}
415 		/*
416 		 * Must block input while temporarily connected.
417 		 */
418 		s = splnet();
419 		error = in_pcbconnect(inp, addr);
420 		if (error) {
421 			splx(s);
422 			goto release;
423 		}
424 	} else {
425 		if (inp->inp_faddr.s_addr == INADDR_ANY) {
426 			error = ENOTCONN;
427 			goto release;
428 		}
429 	}
430 	/*
431 	 * Calculate data length and get a mbuf
432 	 * for UDP and IP headers.
433 	 */
434 	M_PREPEND(m, sizeof(struct udpiphdr), M_DONTWAIT);
435 	if (m == 0) {
436 		error = ENOBUFS;
437 		if (addr)
438 			splx(s);
439 		goto release;
440 	}
441 
442 	/*
443 	 * Fill in mbuf with extended UDP header
444 	 * and addresses and length put into network format.
445 	 */
446 	ui = mtod(m, struct udpiphdr *);
447 	ui->ui_next = ui->ui_prev = 0;
448 	ui->ui_x1 = 0;
449 	ui->ui_pr = IPPROTO_UDP;
450 	ui->ui_len = htons((u_short)len + sizeof (struct udphdr));
451 	ui->ui_src = inp->inp_laddr;
452 	ui->ui_dst = inp->inp_faddr;
453 	ui->ui_sport = inp->inp_lport;
454 	ui->ui_dport = inp->inp_fport;
455 	ui->ui_ulen = ui->ui_len;
456 
457 	/*
458 	 * Stuff checksum and output datagram.
459 	 */
460 	ui->ui_sum = 0;
461 	if (udpcksum) {
462 	    if ((ui->ui_sum = in_cksum(m, sizeof (struct udpiphdr) + len)) == 0)
463 		ui->ui_sum = 0xffff;
464 	}
465 	((struct ip *)ui)->ip_len = sizeof (struct udpiphdr) + len;
466 	((struct ip *)ui)->ip_ttl = inp->inp_ip.ip_ttl;	/* XXX */
467 	((struct ip *)ui)->ip_tos = inp->inp_ip.ip_tos;	/* XXX */
468 	udpstat.udps_opackets++;
469 	error = ip_output(m, inp->inp_options, &inp->inp_route,
470 	    inp->inp_socket->so_options & (SO_DONTROUTE | SO_BROADCAST),
471 	    inp->inp_moptions);
472 
473 	if (addr) {
474 		in_pcbdisconnect(inp);
475 		inp->inp_laddr = laddr;
476 		splx(s);
477 	}
478 	return (error);
479 
480 release:
481 	m_freem(m);
482 	return (error);
483 }
484 
485 static u_long	udp_sendspace = 9216;		/* really max datagram size */
486 					/* 40 1K datagrams */
487 SYSCTL_INT(_net_inet_udp, UDPCTL_MAXDGRAM, maxdgram, CTLFLAG_RW,
488 	&udp_sendspace, 0, "");
489 
490 static u_long	udp_recvspace = 40 * (1024 + sizeof(struct sockaddr_in));
491 SYSCTL_INT(_net_inet_udp, UDPCTL_RECVSPACE, recvspace, CTLFLAG_RW,
492 	&udp_recvspace, 0, "");
493 
494 /*ARGSUSED*/
495 int
496 udp_usrreq(so, req, m, addr, control)
497 	struct socket *so;
498 	int req;
499 	struct mbuf *m, *addr, *control;
500 {
501 	struct inpcb *inp = sotoinpcb(so);
502 	int error = 0;
503 	int s;
504 
505 	if (req == PRU_CONTROL)
506 		return (in_control(so, (u_long)m, (caddr_t)addr,
507 			(struct ifnet *)control));
508 	if (inp == NULL && req != PRU_ATTACH) {
509 		error = EINVAL;
510 		goto release;
511 	}
512 	/*
513 	 * Note: need to block udp_input while changing
514 	 * the udp pcb queue and/or pcb addresses.
515 	 */
516 	switch (req) {
517 
518 	case PRU_ATTACH:
519 		if (inp != NULL) {
520 			error = EINVAL;
521 			break;
522 		}
523 		s = splnet();
524 		error = in_pcballoc(so, &udbinfo);
525 		splx(s);
526 		if (error)
527 			break;
528 		error = soreserve(so, udp_sendspace, udp_recvspace);
529 		if (error)
530 			break;
531 		((struct inpcb *) so->so_pcb)->inp_ip.ip_ttl = ip_defttl;
532 		break;
533 
534 	case PRU_DETACH:
535 		udp_detach(inp);
536 		break;
537 
538 	case PRU_BIND:
539 		s = splnet();
540 		error = in_pcbbind(inp, addr);
541 		splx(s);
542 		break;
543 
544 	case PRU_LISTEN:
545 		error = EOPNOTSUPP;
546 		break;
547 
548 	case PRU_CONNECT:
549 		if (inp->inp_faddr.s_addr != INADDR_ANY) {
550 			error = EISCONN;
551 			break;
552 		}
553 		s = splnet();
554 		error = in_pcbconnect(inp, addr);
555 		splx(s);
556 		if (error == 0)
557 			soisconnected(so);
558 		break;
559 
560 	case PRU_CONNECT2:
561 		error = EOPNOTSUPP;
562 		break;
563 
564 	case PRU_ACCEPT:
565 		error = EOPNOTSUPP;
566 		break;
567 
568 	case PRU_DISCONNECT:
569 		if (inp->inp_faddr.s_addr == INADDR_ANY) {
570 			error = ENOTCONN;
571 			break;
572 		}
573 		s = splnet();
574 		in_pcbdisconnect(inp);
575 		inp->inp_laddr.s_addr = INADDR_ANY;
576 		splx(s);
577 		so->so_state &= ~SS_ISCONNECTED;		/* XXX */
578 		break;
579 
580 	case PRU_SHUTDOWN:
581 		socantsendmore(so);
582 		break;
583 
584 	case PRU_SEND:
585 		return (udp_output(inp, m, addr, control));
586 
587 	case PRU_ABORT:
588 		soisdisconnected(so);
589 		udp_detach(inp);
590 		break;
591 
592 	case PRU_SOCKADDR:
593 		in_setsockaddr(inp, addr);
594 		break;
595 
596 	case PRU_PEERADDR:
597 		in_setpeeraddr(inp, addr);
598 		break;
599 
600 	case PRU_SENSE:
601 		/*
602 		 * stat: don't bother with a blocksize.
603 		 */
604 		return (0);
605 
606 	case PRU_SENDOOB:
607 	case PRU_FASTTIMO:
608 	case PRU_SLOWTIMO:
609 	case PRU_PROTORCV:
610 	case PRU_PROTOSEND:
611 		error =  EOPNOTSUPP;
612 		break;
613 
614 	case PRU_RCVD:
615 	case PRU_RCVOOB:
616 		return (EOPNOTSUPP);	/* do not free mbuf's */
617 
618 	default:
619 		panic("udp_usrreq");
620 	}
621 
622 release:
623 	if (control) {
624 		printf("udp control data unexpectedly retained\n");
625 		m_freem(control);
626 	}
627 	if (m)
628 		m_freem(m);
629 	return (error);
630 }
631 
632 static void
633 udp_detach(inp)
634 	struct inpcb *inp;
635 {
636 	int s = splnet();
637 
638 	in_pcbdetach(inp);
639 	splx(s);
640 }
641