udp6_usrreq.c revision 220463
113250Sgraichen/*-
250472Speter * Copyright (C) 1995, 1996, 1997, and 1998 WIDE Project.
313250Sgraichen * All rights reserved.
448295Sobrien *
522295Smpp * Redistribution and use in source and binary forms, with or without
622295Smpp * modification, are permitted provided that the following conditions
722295Smpp * are met:
822295Smpp * 1. Redistributions of source code must retain the above copyright
922295Smpp *    notice, this list of conditions and the following disclaimer.
1048294Sobrien * 2. Redistributions in binary form must reproduce the above copyright
1122295Smpp *    notice, this list of conditions and the following disclaimer in the
1222295Smpp *    documentation and/or other materials provided with the distribution.
1326548Sache * 3. Neither the name of the project nor the names of its contributors
1450126Sgreen *    may be used to endorse or promote products derived from this software
1543358Swollman *    without specific prior written permission.
16 *
17 * THIS SOFTWARE IS PROVIDED BY THE PROJECT AND CONTRIBUTORS ``AS IS'' AND
18 * ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
19 * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE
20 * ARE DISCLAIMED.  IN NO EVENT SHALL THE PROJECT OR CONTRIBUTORS BE LIABLE
21 * FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL
22 * DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS
23 * OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION)
24 * HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT
25 * LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY
26 * OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF
27 * SUCH DAMAGE.
28 *
29 *	$KAME: udp6_usrreq.c,v 1.27 2001/05/21 05:45:10 jinmei Exp $
30 *	$KAME: udp6_output.c,v 1.31 2001/05/21 16:39:15 jinmei Exp $
31 */
32
33/*-
34 * Copyright (c) 1982, 1986, 1988, 1990, 1993, 1995
35 *	The Regents of the University of California.
36 * All rights reserved.
37 *
38 * Redistribution and use in source and binary forms, with or without
39 * modification, are permitted provided that the following conditions
40 * are met:
41 * 1. Redistributions of source code must retain the above copyright
42 *    notice, this list of conditions and the following disclaimer.
43 * 2. Redistributions in binary form must reproduce the above copyright
44 *    notice, this list of conditions and the following disclaimer in the
45 *    documentation and/or other materials provided with the distribution.
46 * 4. Neither the name of the University nor the names of its contributors
47 *    may be used to endorse or promote products derived from this software
48 *    without specific prior written permission.
49 *
50 * THIS SOFTWARE IS PROVIDED BY THE REGENTS AND CONTRIBUTORS ``AS IS'' AND
51 * ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
52 * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE
53 * ARE DISCLAIMED.  IN NO EVENT SHALL THE REGENTS OR CONTRIBUTORS BE LIABLE
54 * FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL
55 * DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS
56 * OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION)
57 * HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT
58 * LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY
59 * OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF
60 * SUCH DAMAGE.
61 *
62 *	@(#)udp_usrreq.c	8.6 (Berkeley) 5/23/95
63 */
64
65#include <sys/cdefs.h>
66__FBSDID("$FreeBSD: head/sys/netinet6/udp6_usrreq.c 220463 2011-04-09 02:22:49Z bz $");
67
68#include "opt_inet.h"
69#include "opt_inet6.h"
70#include "opt_ipsec.h"
71
72#include <sys/param.h>
73#include <sys/jail.h>
74#include <sys/kernel.h>
75#include <sys/lock.h>
76#include <sys/mbuf.h>
77#include <sys/priv.h>
78#include <sys/proc.h>
79#include <sys/protosw.h>
80#include <sys/signalvar.h>
81#include <sys/socket.h>
82#include <sys/socketvar.h>
83#include <sys/sx.h>
84#include <sys/sysctl.h>
85#include <sys/syslog.h>
86#include <sys/systm.h>
87
88#include <net/if.h>
89#include <net/if_types.h>
90#include <net/route.h>
91
92#include <netinet/in.h>
93#include <netinet/in_pcb.h>
94#include <netinet/in_systm.h>
95#include <netinet/in_var.h>
96#include <netinet/ip.h>
97#include <netinet/ip_icmp.h>
98#include <netinet/ip6.h>
99#include <netinet/icmp_var.h>
100#include <netinet/icmp6.h>
101#include <netinet/ip_var.h>
102#include <netinet/udp.h>
103#include <netinet/udp_var.h>
104
105#include <netinet6/ip6protosw.h>
106#include <netinet6/ip6_var.h>
107#include <netinet6/in6_pcb.h>
108#include <netinet6/udp6_var.h>
109#include <netinet6/scope6_var.h>
110
111#ifdef IPSEC
112#include <netipsec/ipsec.h>
113#include <netipsec/ipsec6.h>
114#endif /* IPSEC */
115
116#include <security/mac/mac_framework.h>
117
118/*
119 * UDP protocol implementation.
120 * Per RFC 768, August, 1980.
121 */
122
123extern struct protosw	inetsw[];
124static void		udp6_detach(struct socket *so);
125
126static void
127udp6_append(struct inpcb *inp, struct mbuf *n, int off,
128    struct sockaddr_in6 *fromsa)
129{
130	struct socket *so;
131	struct mbuf *opts;
132
133	INP_LOCK_ASSERT(inp);
134
135#ifdef IPSEC
136	/* Check AH/ESP integrity. */
137	if (ipsec6_in_reject(n, inp)) {
138		m_freem(n);
139		V_ipsec6stat.in_polvio++;
140		return;
141	}
142#endif /* IPSEC */
143#ifdef MAC
144	if (mac_inpcb_check_deliver(inp, n) != 0) {
145		m_freem(n);
146		return;
147	}
148#endif
149	opts = NULL;
150	if (inp->inp_flags & INP_CONTROLOPTS ||
151	    inp->inp_socket->so_options & SO_TIMESTAMP)
152		ip6_savecontrol(inp, n, &opts);
153	m_adj(n, off + sizeof(struct udphdr));
154
155	so = inp->inp_socket;
156	SOCKBUF_LOCK(&so->so_rcv);
157	if (sbappendaddr_locked(&so->so_rcv, (struct sockaddr *)fromsa, n,
158	    opts) == 0) {
159		SOCKBUF_UNLOCK(&so->so_rcv);
160		m_freem(n);
161		if (opts)
162			m_freem(opts);
163		UDPSTAT_INC(udps_fullsock);
164	} else
165		sorwakeup_locked(so);
166}
167
168int
169udp6_input(struct mbuf **mp, int *offp, int proto)
170{
171	struct mbuf *m = *mp;
172	struct ifnet *ifp;
173	struct ip6_hdr *ip6;
174	struct udphdr *uh;
175	struct inpcb *inp;
176	struct udpcb *up;
177	int off = *offp;
178	int plen, ulen;
179	struct sockaddr_in6 fromsa;
180
181	ifp = m->m_pkthdr.rcvif;
182	ip6 = mtod(m, struct ip6_hdr *);
183
184	if (faithprefix_p != NULL && (*faithprefix_p)(&ip6->ip6_dst)) {
185		/* XXX send icmp6 host/port unreach? */
186		m_freem(m);
187		return (IPPROTO_DONE);
188	}
189
190#ifndef PULLDOWN_TEST
191	IP6_EXTHDR_CHECK(m, off, sizeof(struct udphdr), IPPROTO_DONE);
192	ip6 = mtod(m, struct ip6_hdr *);
193	uh = (struct udphdr *)((caddr_t)ip6 + off);
194#else
195	IP6_EXTHDR_GET(uh, struct udphdr *, m, off, sizeof(*uh));
196	if (!uh)
197		return (IPPROTO_DONE);
198#endif
199
200	UDPSTAT_INC(udps_ipackets);
201
202	/*
203	 * Destination port of 0 is illegal, based on RFC768.
204	 */
205	if (uh->uh_dport == 0)
206		goto badunlocked;
207
208	plen = ntohs(ip6->ip6_plen) - off + sizeof(*ip6);
209	ulen = ntohs((u_short)uh->uh_ulen);
210
211	if (plen != ulen) {
212		UDPSTAT_INC(udps_badlen);
213		goto badunlocked;
214	}
215
216	/*
217	 * Checksum extended UDP header and data.
218	 */
219	if (uh->uh_sum == 0) {
220		UDPSTAT_INC(udps_nosum);
221		goto badunlocked;
222	}
223	if (in6_cksum(m, IPPROTO_UDP, off, ulen) != 0) {
224		UDPSTAT_INC(udps_badsum);
225		goto badunlocked;
226	}
227
228	/*
229	 * Construct sockaddr format source address.
230	 */
231	init_sin6(&fromsa, m);
232	fromsa.sin6_port = uh->uh_sport;
233
234	INP_INFO_RLOCK(&V_udbinfo);
235	if (IN6_IS_ADDR_MULTICAST(&ip6->ip6_dst)) {
236		struct inpcb *last;
237		struct ip6_moptions *imo;
238
239		/*
240		 * In the event that laddr should be set to the link-local
241		 * address (this happens in RIPng), the multicast address
242		 * specified in the received packet will not match laddr.  To
243		 * handle this situation, matching is relaxed if the
244		 * receiving interface is the same as one specified in the
245		 * socket and if the destination multicast address matches
246		 * one of the multicast groups specified in the socket.
247		 */
248
249		/*
250		 * KAME note: traditionally we dropped udpiphdr from mbuf
251		 * here.  We need udphdr for IPsec processing so we do that
252		 * later.
253		 */
254		last = NULL;
255		LIST_FOREACH(inp, &V_udb, inp_list) {
256			if ((inp->inp_vflag & INP_IPV6) == 0)
257				continue;
258			if (inp->inp_lport != uh->uh_dport)
259				continue;
260			if (inp->inp_fport != 0 &&
261			    inp->inp_fport != uh->uh_sport)
262				continue;
263			if (!IN6_IS_ADDR_UNSPECIFIED(&inp->in6p_laddr)) {
264				if (!IN6_ARE_ADDR_EQUAL(&inp->in6p_laddr,
265							&ip6->ip6_dst))
266					continue;
267			}
268			if (!IN6_IS_ADDR_UNSPECIFIED(&inp->in6p_faddr)) {
269				if (!IN6_ARE_ADDR_EQUAL(&inp->in6p_faddr,
270							&ip6->ip6_src) ||
271				    inp->inp_fport != uh->uh_sport)
272					continue;
273			}
274
275			/*
276			 * Handle socket delivery policy for any-source
277			 * and source-specific multicast. [RFC3678]
278			 */
279			imo = inp->in6p_moptions;
280			if (imo && IN6_IS_ADDR_MULTICAST(&ip6->ip6_dst)) {
281				struct sockaddr_in6	 mcaddr;
282				int			 blocked;
283
284				INP_RLOCK(inp);
285
286				bzero(&mcaddr, sizeof(struct sockaddr_in6));
287				mcaddr.sin6_len = sizeof(struct sockaddr_in6);
288				mcaddr.sin6_family = AF_INET6;
289				mcaddr.sin6_addr = ip6->ip6_dst;
290
291				blocked = im6o_mc_filter(imo, ifp,
292					(struct sockaddr *)&mcaddr,
293					(struct sockaddr *)&fromsa);
294				if (blocked != MCAST_PASS) {
295					if (blocked == MCAST_NOTGMEMBER)
296						IP6STAT_INC(ip6s_notmember);
297					if (blocked == MCAST_NOTSMEMBER ||
298					    blocked == MCAST_MUTED)
299						UDPSTAT_INC(udps_filtermcast);
300					INP_RUNLOCK(inp); /* XXX */
301					continue;
302				}
303
304				INP_RUNLOCK(inp);
305			}
306			if (last != NULL) {
307				struct mbuf *n;
308
309				if ((n = m_copy(m, 0, M_COPYALL)) != NULL) {
310					INP_RLOCK(last);
311					up = intoudpcb(last);
312					if (up->u_tun_func == NULL) {
313						udp6_append(last, n, off, &fromsa);
314					} else {
315						/*
316						 * Engage the tunneling
317						 * protocol we will have to
318						 * leave the info_lock up,
319						 * since we are hunting
320						 * through multiple UDP's.
321						 *
322						 */
323						(*up->u_tun_func)(n, off, last);
324					}
325					INP_RUNLOCK(last);
326				}
327			}
328			last = inp;
329			/*
330			 * Don't look for additional matches if this one does
331			 * not have either the SO_REUSEPORT or SO_REUSEADDR
332			 * socket options set.  This heuristic avoids
333			 * searching through all pcbs in the common case of a
334			 * non-shared port.  It assumes that an application
335			 * will never clear these options after setting them.
336			 */
337			if ((last->inp_socket->so_options &
338			     (SO_REUSEPORT|SO_REUSEADDR)) == 0)
339				break;
340		}
341
342		if (last == NULL) {
343			/*
344			 * No matching pcb found; discard datagram.  (No need
345			 * to send an ICMP Port Unreachable for a broadcast
346			 * or multicast datgram.)
347			 */
348			UDPSTAT_INC(udps_noport);
349			UDPSTAT_INC(udps_noportmcast);
350			goto badheadlocked;
351		}
352		INP_RLOCK(last);
353		INP_INFO_RUNLOCK(&V_udbinfo);
354		up = intoudpcb(last);
355		if (up->u_tun_func == NULL) {
356			udp6_append(last, m, off, &fromsa);
357		} else {
358			/*
359			 * Engage the tunneling protocol.
360			 */
361			(*up->u_tun_func)(m, off, last);
362		}
363		INP_RUNLOCK(last);
364		return (IPPROTO_DONE);
365	}
366	/*
367	 * Locate pcb for datagram.
368	 */
369	inp = in6_pcblookup_hash(&V_udbinfo, &ip6->ip6_src, uh->uh_sport,
370	    &ip6->ip6_dst, uh->uh_dport, 1, m->m_pkthdr.rcvif);
371	if (inp == NULL) {
372		if (udp_log_in_vain) {
373			char ip6bufs[INET6_ADDRSTRLEN];
374			char ip6bufd[INET6_ADDRSTRLEN];
375
376			log(LOG_INFO,
377			    "Connection attempt to UDP [%s]:%d from [%s]:%d\n",
378			    ip6_sprintf(ip6bufd, &ip6->ip6_dst),
379			    ntohs(uh->uh_dport),
380			    ip6_sprintf(ip6bufs, &ip6->ip6_src),
381			    ntohs(uh->uh_sport));
382		}
383		UDPSTAT_INC(udps_noport);
384		if (m->m_flags & M_MCAST) {
385			printf("UDP6: M_MCAST is set in a unicast packet.\n");
386			UDPSTAT_INC(udps_noportmcast);
387			goto badheadlocked;
388		}
389		INP_INFO_RUNLOCK(&V_udbinfo);
390		if (V_udp_blackhole)
391			goto badunlocked;
392		if (badport_bandlim(BANDLIM_ICMP6_UNREACH) < 0)
393			goto badunlocked;
394		icmp6_error(m, ICMP6_DST_UNREACH, ICMP6_DST_UNREACH_NOPORT, 0);
395		return (IPPROTO_DONE);
396	}
397	INP_RLOCK(inp);
398	INP_INFO_RUNLOCK(&V_udbinfo);
399	up = intoudpcb(inp);
400	if (up->u_tun_func == NULL) {
401		udp6_append(inp, m, off, &fromsa);
402	} else {
403		/*
404		 * Engage the tunneling protocol.
405		 */
406
407		(*up->u_tun_func)(m, off, inp);
408	}
409	INP_RUNLOCK(inp);
410	return (IPPROTO_DONE);
411
412badheadlocked:
413	INP_INFO_RUNLOCK(&V_udbinfo);
414badunlocked:
415	if (m)
416		m_freem(m);
417	return (IPPROTO_DONE);
418}
419
420void
421udp6_ctlinput(int cmd, struct sockaddr *sa, void *d)
422{
423	struct udphdr uh;
424	struct ip6_hdr *ip6;
425	struct mbuf *m;
426	int off = 0;
427	struct ip6ctlparam *ip6cp = NULL;
428	const struct sockaddr_in6 *sa6_src = NULL;
429	void *cmdarg;
430	struct inpcb *(*notify)(struct inpcb *, int) = udp_notify;
431	struct udp_portonly {
432		u_int16_t uh_sport;
433		u_int16_t uh_dport;
434	} *uhp;
435
436	if (sa->sa_family != AF_INET6 ||
437	    sa->sa_len != sizeof(struct sockaddr_in6))
438		return;
439
440	if ((unsigned)cmd >= PRC_NCMDS)
441		return;
442	if (PRC_IS_REDIRECT(cmd))
443		notify = in6_rtchange, d = NULL;
444	else if (cmd == PRC_HOSTDEAD)
445		d = NULL;
446	else if (inet6ctlerrmap[cmd] == 0)
447		return;
448
449	/* if the parameter is from icmp6, decode it. */
450	if (d != NULL) {
451		ip6cp = (struct ip6ctlparam *)d;
452		m = ip6cp->ip6c_m;
453		ip6 = ip6cp->ip6c_ip6;
454		off = ip6cp->ip6c_off;
455		cmdarg = ip6cp->ip6c_cmdarg;
456		sa6_src = ip6cp->ip6c_src;
457	} else {
458		m = NULL;
459		ip6 = NULL;
460		cmdarg = NULL;
461		sa6_src = &sa6_any;
462	}
463
464	if (ip6) {
465		/*
466		 * XXX: We assume that when IPV6 is non NULL,
467		 * M and OFF are valid.
468		 */
469
470		/* Check if we can safely examine src and dst ports. */
471		if (m->m_pkthdr.len < off + sizeof(*uhp))
472			return;
473
474		bzero(&uh, sizeof(uh));
475		m_copydata(m, off, sizeof(*uhp), (caddr_t)&uh);
476
477		(void) in6_pcbnotify(&V_udbinfo, sa, uh.uh_dport,
478		    (struct sockaddr *)ip6cp->ip6c_src, uh.uh_sport, cmd,
479		    cmdarg, notify);
480	} else
481		(void) in6_pcbnotify(&V_udbinfo, sa, 0,
482		    (const struct sockaddr *)sa6_src, 0, cmd, cmdarg, notify);
483}
484
485static int
486udp6_getcred(SYSCTL_HANDLER_ARGS)
487{
488	struct xucred xuc;
489	struct sockaddr_in6 addrs[2];
490	struct inpcb *inp;
491	int error;
492
493	error = priv_check(req->td, PRIV_NETINET_GETCRED);
494	if (error)
495		return (error);
496
497	if (req->newlen != sizeof(addrs))
498		return (EINVAL);
499	if (req->oldlen != sizeof(struct xucred))
500		return (EINVAL);
501	error = SYSCTL_IN(req, addrs, sizeof(addrs));
502	if (error)
503		return (error);
504	if ((error = sa6_embedscope(&addrs[0], V_ip6_use_defzone)) != 0 ||
505	    (error = sa6_embedscope(&addrs[1], V_ip6_use_defzone)) != 0) {
506		return (error);
507	}
508	INP_INFO_RLOCK(&V_udbinfo);
509	inp = in6_pcblookup_hash(&V_udbinfo, &addrs[1].sin6_addr,
510	    addrs[1].sin6_port, &addrs[0].sin6_addr, addrs[0].sin6_port, 1,
511	    NULL);
512	if (inp != NULL) {
513		INP_RLOCK(inp);
514		INP_INFO_RUNLOCK(&V_udbinfo);
515		if (inp->inp_socket == NULL)
516			error = ENOENT;
517		if (error == 0)
518			error = cr_canseesocket(req->td->td_ucred,
519			    inp->inp_socket);
520		if (error == 0)
521			cru2x(inp->inp_cred, &xuc);
522		INP_RUNLOCK(inp);
523	} else {
524		INP_INFO_RUNLOCK(&V_udbinfo);
525		error = ENOENT;
526	}
527	if (error == 0)
528		error = SYSCTL_OUT(req, &xuc, sizeof(struct xucred));
529	return (error);
530}
531
532SYSCTL_PROC(_net_inet6_udp6, OID_AUTO, getcred, CTLTYPE_OPAQUE|CTLFLAG_RW, 0,
533    0, udp6_getcred, "S,xucred", "Get the xucred of a UDP6 connection");
534
535static int
536udp6_output(struct inpcb *inp, struct mbuf *m, struct sockaddr *addr6,
537    struct mbuf *control, struct thread *td)
538{
539	u_int32_t ulen = m->m_pkthdr.len;
540	u_int32_t plen = sizeof(struct udphdr) + ulen;
541	struct ip6_hdr *ip6;
542	struct udphdr *udp6;
543	struct in6_addr *laddr, *faddr, in6a;
544	struct sockaddr_in6 *sin6 = NULL;
545	struct ifnet *oifp = NULL;
546	int scope_ambiguous = 0;
547	u_short fport;
548	int error = 0;
549	struct ip6_pktopts *optp, opt;
550	int af = AF_INET6, hlen = sizeof(struct ip6_hdr);
551	int flags;
552	struct sockaddr_in6 tmp;
553
554	INP_WLOCK_ASSERT(inp);
555
556	if (addr6) {
557		/* addr6 has been validated in udp6_send(). */
558		sin6 = (struct sockaddr_in6 *)addr6;
559
560		/* protect *sin6 from overwrites */
561		tmp = *sin6;
562		sin6 = &tmp;
563
564		/*
565		 * Application should provide a proper zone ID or the use of
566		 * default zone IDs should be enabled.  Unfortunately, some
567		 * applications do not behave as it should, so we need a
568		 * workaround.  Even if an appropriate ID is not determined,
569		 * we'll see if we can determine the outgoing interface.  If we
570		 * can, determine the zone ID based on the interface below.
571		 */
572		if (sin6->sin6_scope_id == 0 && !V_ip6_use_defzone)
573			scope_ambiguous = 1;
574		if ((error = sa6_embedscope(sin6, V_ip6_use_defzone)) != 0)
575			return (error);
576	}
577
578	if (control) {
579		if ((error = ip6_setpktopts(control, &opt,
580		    inp->in6p_outputopts, td->td_ucred, IPPROTO_UDP)) != 0)
581			goto release;
582		optp = &opt;
583	} else
584		optp = inp->in6p_outputopts;
585
586	if (sin6) {
587		faddr = &sin6->sin6_addr;
588
589		/*
590		 * IPv4 version of udp_output calls in_pcbconnect in this case,
591		 * which needs splnet and affects performance.
592		 * Since we saw no essential reason for calling in_pcbconnect,
593		 * we get rid of such kind of logic, and call in6_selectsrc
594		 * and in6_pcbsetport in order to fill in the local address
595		 * and the local port.
596		 */
597		if (sin6->sin6_port == 0) {
598			error = EADDRNOTAVAIL;
599			goto release;
600		}
601
602		if (!IN6_IS_ADDR_UNSPECIFIED(&inp->in6p_faddr)) {
603			/* how about ::ffff:0.0.0.0 case? */
604			error = EISCONN;
605			goto release;
606		}
607
608		fport = sin6->sin6_port; /* allow 0 port */
609
610		if (IN6_IS_ADDR_V4MAPPED(faddr)) {
611			if ((inp->inp_flags & IN6P_IPV6_V6ONLY)) {
612				/*
613				 * I believe we should explicitly discard the
614				 * packet when mapped addresses are disabled,
615				 * rather than send the packet as an IPv6 one.
616				 * If we chose the latter approach, the packet
617				 * might be sent out on the wire based on the
618				 * default route, the situation which we'd
619				 * probably want to avoid.
620				 * (20010421 jinmei@kame.net)
621				 */
622				error = EINVAL;
623				goto release;
624			}
625			if (!IN6_IS_ADDR_UNSPECIFIED(&inp->in6p_laddr) &&
626			    !IN6_IS_ADDR_V4MAPPED(&inp->in6p_laddr)) {
627				/*
628				 * when remote addr is an IPv4-mapped address,
629				 * local addr should not be an IPv6 address,
630				 * since you cannot determine how to map IPv6
631				 * source address to IPv4.
632				 */
633				error = EINVAL;
634				goto release;
635			}
636
637			af = AF_INET;
638		}
639
640		if (!IN6_IS_ADDR_V4MAPPED(faddr)) {
641			error = in6_selectsrc(sin6, optp, inp, NULL,
642			    td->td_ucred, &oifp, &in6a);
643			if (error)
644				goto release;
645			if (oifp && scope_ambiguous &&
646			    (error = in6_setscope(&sin6->sin6_addr,
647			    oifp, NULL))) {
648				goto release;
649			}
650			laddr = &in6a;
651		} else
652			laddr = &inp->in6p_laddr;	/* XXX */
653		if (laddr == NULL) {
654			if (error == 0)
655				error = EADDRNOTAVAIL;
656			goto release;
657		}
658		if (inp->inp_lport == 0 &&
659		    (error = in6_pcbsetport(laddr, inp, td->td_ucred)) != 0) {
660			/* Undo an address bind that may have occurred. */
661			inp->in6p_laddr = in6addr_any;
662			goto release;
663		}
664	} else {
665		if (IN6_IS_ADDR_UNSPECIFIED(&inp->in6p_faddr)) {
666			error = ENOTCONN;
667			goto release;
668		}
669		if (IN6_IS_ADDR_V4MAPPED(&inp->in6p_faddr)) {
670			if ((inp->inp_flags & IN6P_IPV6_V6ONLY)) {
671				/*
672				 * XXX: this case would happen when the
673				 * application sets the V6ONLY flag after
674				 * connecting the foreign address.
675				 * Such applications should be fixed,
676				 * so we bark here.
677				 */
678				log(LOG_INFO, "udp6_output: IPV6_V6ONLY "
679				    "option was set for a connected socket\n");
680				error = EINVAL;
681				goto release;
682			} else
683				af = AF_INET;
684		}
685		laddr = &inp->in6p_laddr;
686		faddr = &inp->in6p_faddr;
687		fport = inp->inp_fport;
688	}
689
690	if (af == AF_INET)
691		hlen = sizeof(struct ip);
692
693	/*
694	 * Calculate data length and get a mbuf
695	 * for UDP and IP6 headers.
696	 */
697	M_PREPEND(m, hlen + sizeof(struct udphdr), M_DONTWAIT);
698	if (m == 0) {
699		error = ENOBUFS;
700		goto release;
701	}
702
703	/*
704	 * Stuff checksum and output datagram.
705	 */
706	udp6 = (struct udphdr *)(mtod(m, caddr_t) + hlen);
707	udp6->uh_sport = inp->inp_lport; /* lport is always set in the PCB */
708	udp6->uh_dport = fport;
709	if (plen <= 0xffff)
710		udp6->uh_ulen = htons((u_short)plen);
711	else
712		udp6->uh_ulen = 0;
713	udp6->uh_sum = 0;
714
715	switch (af) {
716	case AF_INET6:
717		ip6 = mtod(m, struct ip6_hdr *);
718		ip6->ip6_flow	= inp->inp_flow & IPV6_FLOWINFO_MASK;
719		ip6->ip6_vfc	&= ~IPV6_VERSION_MASK;
720		ip6->ip6_vfc	|= IPV6_VERSION;
721#if 0				/* ip6_plen will be filled in ip6_output. */
722		ip6->ip6_plen	= htons((u_short)plen);
723#endif
724		ip6->ip6_nxt	= IPPROTO_UDP;
725		ip6->ip6_hlim	= in6_selecthlim(inp, NULL);
726		ip6->ip6_src	= *laddr;
727		ip6->ip6_dst	= *faddr;
728
729		if ((udp6->uh_sum = in6_cksum(m, IPPROTO_UDP,
730				sizeof(struct ip6_hdr), plen)) == 0) {
731			udp6->uh_sum = 0xffff;
732		}
733
734		flags = 0;
735
736		UDPSTAT_INC(udps_opackets);
737		error = ip6_output(m, optp, NULL, flags, inp->in6p_moptions,
738		    NULL, inp);
739		break;
740	case AF_INET:
741		error = EAFNOSUPPORT;
742		goto release;
743	}
744	goto releaseopt;
745
746release:
747	m_freem(m);
748
749releaseopt:
750	if (control) {
751		ip6_clearpktopts(&opt, -1);
752		m_freem(control);
753	}
754	return (error);
755}
756
757static void
758udp6_abort(struct socket *so)
759{
760	struct inpcb *inp;
761
762	inp = sotoinpcb(so);
763	KASSERT(inp != NULL, ("udp6_abort: inp == NULL"));
764
765#ifdef INET
766	if (inp->inp_vflag & INP_IPV4) {
767		struct pr_usrreqs *pru;
768
769		pru = inetsw[ip_protox[IPPROTO_UDP]].pr_usrreqs;
770		(*pru->pru_abort)(so);
771		return;
772	}
773#endif
774
775	INP_INFO_WLOCK(&V_udbinfo);
776	INP_WLOCK(inp);
777	if (!IN6_IS_ADDR_UNSPECIFIED(&inp->in6p_faddr)) {
778		in6_pcbdisconnect(inp);
779		inp->in6p_laddr = in6addr_any;
780		soisdisconnected(so);
781	}
782	INP_WUNLOCK(inp);
783	INP_INFO_WUNLOCK(&V_udbinfo);
784}
785
786static int
787udp6_attach(struct socket *so, int proto, struct thread *td)
788{
789	struct inpcb *inp;
790	int error;
791
792	inp = sotoinpcb(so);
793	KASSERT(inp == NULL, ("udp6_attach: inp != NULL"));
794
795	if (so->so_snd.sb_hiwat == 0 || so->so_rcv.sb_hiwat == 0) {
796		error = soreserve(so, udp_sendspace, udp_recvspace);
797		if (error)
798			return (error);
799	}
800	INP_INFO_WLOCK(&V_udbinfo);
801	error = in_pcballoc(so, &V_udbinfo);
802	if (error) {
803		INP_INFO_WUNLOCK(&V_udbinfo);
804		return (error);
805	}
806	inp = (struct inpcb *)so->so_pcb;
807	inp->inp_vflag |= INP_IPV6;
808	if ((inp->inp_flags & IN6P_IPV6_V6ONLY) == 0)
809		inp->inp_vflag |= INP_IPV4;
810	inp->in6p_hops = -1;	/* use kernel default */
811	inp->in6p_cksum = -1;	/* just to be sure */
812	/*
813	 * XXX: ugly!!
814	 * IPv4 TTL initialization is necessary for an IPv6 socket as well,
815	 * because the socket may be bound to an IPv6 wildcard address,
816	 * which may match an IPv4-mapped IPv6 address.
817	 */
818	inp->inp_ip_ttl = V_ip_defttl;
819
820	error = udp_newudpcb(inp);
821	if (error) {
822		in_pcbdetach(inp);
823		in_pcbfree(inp);
824		INP_INFO_WUNLOCK(&V_udbinfo);
825		return (error);
826	}
827	INP_WUNLOCK(inp);
828	INP_INFO_WUNLOCK(&V_udbinfo);
829	return (0);
830}
831
832static int
833udp6_bind(struct socket *so, struct sockaddr *nam, struct thread *td)
834{
835	struct inpcb *inp;
836	int error;
837
838	inp = sotoinpcb(so);
839	KASSERT(inp != NULL, ("udp6_bind: inp == NULL"));
840
841	INP_INFO_WLOCK(&V_udbinfo);
842	INP_WLOCK(inp);
843	inp->inp_vflag &= ~INP_IPV4;
844	inp->inp_vflag |= INP_IPV6;
845	if ((inp->inp_flags & IN6P_IPV6_V6ONLY) == 0) {
846		struct sockaddr_in6 *sin6_p;
847
848		sin6_p = (struct sockaddr_in6 *)nam;
849
850		if (IN6_IS_ADDR_UNSPECIFIED(&sin6_p->sin6_addr))
851			inp->inp_vflag |= INP_IPV4;
852		else if (IN6_IS_ADDR_V4MAPPED(&sin6_p->sin6_addr)) {
853			struct sockaddr_in sin;
854
855			in6_sin6_2_sin(&sin, sin6_p);
856			inp->inp_vflag |= INP_IPV4;
857			inp->inp_vflag &= ~INP_IPV6;
858			error = in_pcbbind(inp, (struct sockaddr *)&sin,
859			    td->td_ucred);
860			goto out;
861		}
862	}
863
864	error = in6_pcbbind(inp, nam, td->td_ucred);
865out:
866	INP_WUNLOCK(inp);
867	INP_INFO_WUNLOCK(&V_udbinfo);
868	return (error);
869}
870
871static void
872udp6_close(struct socket *so)
873{
874	struct inpcb *inp;
875
876	inp = sotoinpcb(so);
877	KASSERT(inp != NULL, ("udp6_close: inp == NULL"));
878
879#ifdef INET
880	if (inp->inp_vflag & INP_IPV4) {
881		struct pr_usrreqs *pru;
882
883		pru = inetsw[ip_protox[IPPROTO_UDP]].pr_usrreqs;
884		(*pru->pru_disconnect)(so);
885		return;
886	}
887#endif
888	INP_INFO_WLOCK(&V_udbinfo);
889	INP_WLOCK(inp);
890	if (!IN6_IS_ADDR_UNSPECIFIED(&inp->in6p_faddr)) {
891		in6_pcbdisconnect(inp);
892		inp->in6p_laddr = in6addr_any;
893		soisdisconnected(so);
894	}
895	INP_WUNLOCK(inp);
896	INP_INFO_WUNLOCK(&V_udbinfo);
897}
898
899static int
900udp6_connect(struct socket *so, struct sockaddr *nam, struct thread *td)
901{
902	struct inpcb *inp;
903	struct sockaddr_in6 *sin6;
904	int error;
905
906	inp = sotoinpcb(so);
907	sin6 = (struct sockaddr_in6 *)nam;
908	KASSERT(inp != NULL, ("udp6_connect: inp == NULL"));
909
910	INP_INFO_WLOCK(&V_udbinfo);
911	INP_WLOCK(inp);
912	if (IN6_IS_ADDR_V4MAPPED(&sin6->sin6_addr)) {
913		struct sockaddr_in sin;
914
915		if ((inp->inp_flags & IN6P_IPV6_V6ONLY) != 0) {
916			error = EINVAL;
917			goto out;
918		}
919		if (inp->inp_faddr.s_addr != INADDR_ANY) {
920			error = EISCONN;
921			goto out;
922		}
923		in6_sin6_2_sin(&sin, sin6);
924		inp->inp_vflag |= INP_IPV4;
925		inp->inp_vflag &= ~INP_IPV6;
926		error = prison_remote_ip4(td->td_ucred, &sin.sin_addr);
927		if (error != 0)
928			goto out;
929		error = in_pcbconnect(inp, (struct sockaddr *)&sin,
930		    td->td_ucred);
931		if (error == 0)
932			soisconnected(so);
933		goto out;
934	}
935	if (!IN6_IS_ADDR_UNSPECIFIED(&inp->in6p_faddr)) {
936		error = EISCONN;
937		goto out;
938	}
939	inp->inp_vflag &= ~INP_IPV4;
940	inp->inp_vflag |= INP_IPV6;
941	error = prison_remote_ip6(td->td_ucred, &sin6->sin6_addr);
942	if (error != 0)
943		goto out;
944	error = in6_pcbconnect(inp, nam, td->td_ucred);
945	if (error == 0)
946		soisconnected(so);
947out:
948	INP_WUNLOCK(inp);
949	INP_INFO_WUNLOCK(&V_udbinfo);
950	return (error);
951}
952
953static void
954udp6_detach(struct socket *so)
955{
956	struct inpcb *inp;
957	struct udpcb *up;
958
959	inp = sotoinpcb(so);
960	KASSERT(inp != NULL, ("udp6_detach: inp == NULL"));
961
962	INP_INFO_WLOCK(&V_udbinfo);
963	INP_WLOCK(inp);
964	up = intoudpcb(inp);
965	KASSERT(up != NULL, ("%s: up == NULL", __func__));
966	in_pcbdetach(inp);
967	in_pcbfree(inp);
968	INP_INFO_WUNLOCK(&V_udbinfo);
969	udp_discardcb(up);
970}
971
972static int
973udp6_disconnect(struct socket *so)
974{
975	struct inpcb *inp;
976	int error;
977
978	inp = sotoinpcb(so);
979	KASSERT(inp != NULL, ("udp6_disconnect: inp == NULL"));
980
981	INP_INFO_WLOCK(&V_udbinfo);
982	INP_WLOCK(inp);
983
984#ifdef INET
985	if (inp->inp_vflag & INP_IPV4) {
986		struct pr_usrreqs *pru;
987
988		pru = inetsw[ip_protox[IPPROTO_UDP]].pr_usrreqs;
989		error = (*pru->pru_disconnect)(so);
990		goto out;
991	}
992#endif
993
994	if (IN6_IS_ADDR_UNSPECIFIED(&inp->in6p_faddr)) {
995		error = ENOTCONN;
996		goto out;
997	}
998
999	in6_pcbdisconnect(inp);
1000	inp->in6p_laddr = in6addr_any;
1001	SOCK_LOCK(so);
1002	so->so_state &= ~SS_ISCONNECTED;		/* XXX */
1003	SOCK_UNLOCK(so);
1004out:
1005	INP_WUNLOCK(inp);
1006	INP_INFO_WUNLOCK(&V_udbinfo);
1007	return (0);
1008}
1009
1010static int
1011udp6_send(struct socket *so, int flags, struct mbuf *m,
1012    struct sockaddr *addr, struct mbuf *control, struct thread *td)
1013{
1014	struct inpcb *inp;
1015	int error = 0;
1016
1017	inp = sotoinpcb(so);
1018	KASSERT(inp != NULL, ("udp6_send: inp == NULL"));
1019
1020	INP_INFO_WLOCK(&V_udbinfo);
1021	INP_WLOCK(inp);
1022	if (addr) {
1023		if (addr->sa_len != sizeof(struct sockaddr_in6)) {
1024			error = EINVAL;
1025			goto bad;
1026		}
1027		if (addr->sa_family != AF_INET6) {
1028			error = EAFNOSUPPORT;
1029			goto bad;
1030		}
1031	}
1032
1033#ifdef INET
1034	if ((inp->inp_flags & IN6P_IPV6_V6ONLY) == 0) {
1035		int hasv4addr;
1036		struct sockaddr_in6 *sin6 = 0;
1037
1038		if (addr == 0)
1039			hasv4addr = (inp->inp_vflag & INP_IPV4);
1040		else {
1041			sin6 = (struct sockaddr_in6 *)addr;
1042			hasv4addr = IN6_IS_ADDR_V4MAPPED(&sin6->sin6_addr)
1043			    ? 1 : 0;
1044		}
1045		if (hasv4addr) {
1046			struct pr_usrreqs *pru;
1047
1048			/*
1049			 * XXXRW: We release UDP-layer locks before calling
1050			 * udp_send() in order to avoid recursion.  However,
1051			 * this does mean there is a short window where inp's
1052			 * fields are unstable.  Could this lead to a
1053			 * potential race in which the factors causing us to
1054			 * select the UDPv4 output routine are invalidated?
1055			 */
1056			INP_WUNLOCK(inp);
1057			INP_INFO_WUNLOCK(&V_udbinfo);
1058			if (sin6)
1059				in6_sin6_2_sin_in_sock(addr);
1060			pru = inetsw[ip_protox[IPPROTO_UDP]].pr_usrreqs;
1061			/* addr will just be freed in sendit(). */
1062			return ((*pru->pru_send)(so, flags, m, addr, control,
1063			    td));
1064		}
1065	}
1066#endif
1067#ifdef MAC
1068	mac_inpcb_create_mbuf(inp, m);
1069#endif
1070	error = udp6_output(inp, m, addr, control, td);
1071#ifdef INET
1072#endif
1073	INP_WUNLOCK(inp);
1074	INP_INFO_WUNLOCK(&V_udbinfo);
1075	return (error);
1076
1077bad:
1078	INP_WUNLOCK(inp);
1079	INP_INFO_WUNLOCK(&V_udbinfo);
1080	m_freem(m);
1081	return (error);
1082}
1083
1084struct pr_usrreqs udp6_usrreqs = {
1085	.pru_abort =		udp6_abort,
1086	.pru_attach =		udp6_attach,
1087	.pru_bind =		udp6_bind,
1088	.pru_connect =		udp6_connect,
1089	.pru_control =		in6_control,
1090	.pru_detach =		udp6_detach,
1091	.pru_disconnect =	udp6_disconnect,
1092	.pru_peeraddr =		in6_mapped_peeraddr,
1093	.pru_send =		udp6_send,
1094	.pru_shutdown =		udp_shutdown,
1095	.pru_sockaddr =		in6_mapped_sockaddr,
1096	.pru_soreceive =	soreceive_dgram,
1097	.pru_sosend =		sosend_dgram,
1098	.pru_sosetlabel =	in_pcbsosetlabel,
1099	.pru_close =		udp6_close
1100};
1101