ip_output.c revision 165082
1/*-
2 * Copyright (c) 1982, 1986, 1988, 1990, 1993
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 * 4. Neither the name of the University nor the names of its contributors
14 *    may be used to endorse or promote products derived from this software
15 *    without specific prior written permission.
16 *
17 * THIS SOFTWARE IS PROVIDED BY THE REGENTS 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 REGENTS 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 *	@(#)ip_output.c	8.3 (Berkeley) 1/21/94
30 * $FreeBSD: head/sys/netinet/ip_output.c 165082 2006-12-10 13:44:00Z bms $
31 */
32
33#include "opt_ipfw.h"
34#include "opt_ipsec.h"
35#include "opt_mac.h"
36#include "opt_mbuf_stress_test.h"
37
38#include <sys/param.h>
39#include <sys/systm.h>
40#include <sys/kernel.h>
41#include <sys/malloc.h>
42#include <sys/mbuf.h>
43#include <sys/priv.h>
44#include <sys/protosw.h>
45#include <sys/socket.h>
46#include <sys/socketvar.h>
47#include <sys/sysctl.h>
48
49#include <net/if.h>
50#include <net/netisr.h>
51#include <net/pfil.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_options.h>
61
62#if defined(IPSEC) || defined(FAST_IPSEC)
63#include <netinet/ip_ipsec.h>
64#ifdef IPSEC
65#include <netinet6/ipsec.h>
66#endif
67#ifdef FAST_IPSEC
68#include <netipsec/ipsec.h>
69#endif
70#endif /*IPSEC*/
71
72#include <machine/in_cksum.h>
73
74#include <security/mac/mac_framework.h>
75
76static MALLOC_DEFINE(M_IPMOPTS, "ip_moptions", "internet multicast options");
77
78#define print_ip(x, a, y)	 printf("%s %d.%d.%d.%d%s",\
79				x, (ntohl(a.s_addr)>>24)&0xFF,\
80				  (ntohl(a.s_addr)>>16)&0xFF,\
81				  (ntohl(a.s_addr)>>8)&0xFF,\
82				  (ntohl(a.s_addr))&0xFF, y);
83
84u_short ip_id;
85
86#ifdef MBUF_STRESS_TEST
87int mbuf_frag_size = 0;
88SYSCTL_INT(_net_inet_ip, OID_AUTO, mbuf_frag_size, CTLFLAG_RW,
89	&mbuf_frag_size, 0, "Fragment outgoing mbufs to this size");
90#endif
91
92static struct ifnet *ip_multicast_if(struct in_addr *, int *);
93static void	ip_mloopback
94	(struct ifnet *, struct mbuf *, struct sockaddr_in *, int);
95static int	ip_getmoptions(struct inpcb *, struct sockopt *);
96static int	ip_setmoptions(struct inpcb *, struct sockopt *);
97
98
99extern	struct protosw inetsw[];
100
101/*
102 * IP output.  The packet in mbuf chain m contains a skeletal IP
103 * header (with len, off, ttl, proto, tos, src, dst).
104 * The mbuf chain containing the packet will be freed.
105 * The mbuf opt, if present, will not be freed.
106 * In the IP forwarding case, the packet will arrive with options already
107 * inserted, so must have a NULL opt pointer.
108 */
109int
110ip_output(struct mbuf *m, struct mbuf *opt, struct route *ro,
111	int flags, struct ip_moptions *imo, struct inpcb *inp)
112{
113	struct ip *ip;
114	struct ifnet *ifp = NULL;	/* keep compiler happy */
115	struct mbuf *m0;
116	int hlen = sizeof (struct ip);
117	int mtu;
118	int len, error = 0;
119	struct sockaddr_in *dst = NULL;	/* keep compiler happy */
120	struct in_ifaddr *ia = NULL;
121	int isbroadcast, sw_csum;
122	struct route iproute;
123	struct in_addr odst;
124#ifdef IPFIREWALL_FORWARD
125	struct m_tag *fwd_tag = NULL;
126#endif
127	M_ASSERTPKTHDR(m);
128
129	if (ro == NULL) {
130		ro = &iproute;
131		bzero(ro, sizeof (*ro));
132	}
133
134	if (inp != NULL)
135		INP_LOCK_ASSERT(inp);
136
137	if (opt) {
138		len = 0;
139		m = ip_insertoptions(m, opt, &len);
140		if (len != 0)
141			hlen = len;
142	}
143	ip = mtod(m, struct ip *);
144
145	/*
146	 * Fill in IP header.  If we are not allowing fragmentation,
147	 * then the ip_id field is meaningless, but we don't set it
148	 * to zero.  Doing so causes various problems when devices along
149	 * the path (routers, load balancers, firewalls, etc.) illegally
150	 * disable DF on our packet.  Note that a 16-bit counter
151	 * will wrap around in less than 10 seconds at 100 Mbit/s on a
152	 * medium with MTU 1500.  See Steven M. Bellovin, "A Technique
153	 * for Counting NATted Hosts", Proc. IMW'02, available at
154	 * <http://www.cs.columbia.edu/~smb/papers/fnat.pdf>.
155	 */
156	if ((flags & (IP_FORWARDING|IP_RAWOUTPUT)) == 0) {
157		ip->ip_v = IPVERSION;
158		ip->ip_hl = hlen >> 2;
159		ip->ip_id = ip_newid();
160		ipstat.ips_localout++;
161	} else {
162		hlen = ip->ip_hl << 2;
163	}
164
165	dst = (struct sockaddr_in *)&ro->ro_dst;
166again:
167	/*
168	 * If there is a cached route,
169	 * check that it is to the same destination
170	 * and is still up.  If not, free it and try again.
171	 * The address family should also be checked in case of sharing the
172	 * cache with IPv6.
173	 */
174	if (ro->ro_rt && ((ro->ro_rt->rt_flags & RTF_UP) == 0 ||
175			  dst->sin_family != AF_INET ||
176			  dst->sin_addr.s_addr != ip->ip_dst.s_addr)) {
177		RTFREE(ro->ro_rt);
178		ro->ro_rt = (struct rtentry *)NULL;
179	}
180#ifdef IPFIREWALL_FORWARD
181	if (ro->ro_rt == NULL && fwd_tag == NULL) {
182#else
183	if (ro->ro_rt == NULL) {
184#endif
185		bzero(dst, sizeof(*dst));
186		dst->sin_family = AF_INET;
187		dst->sin_len = sizeof(*dst);
188		dst->sin_addr = ip->ip_dst;
189	}
190	/*
191	 * If routing to interface only,
192	 * short circuit routing lookup.
193	 */
194	if (flags & IP_ROUTETOIF) {
195		if ((ia = ifatoia(ifa_ifwithdstaddr(sintosa(dst)))) == NULL &&
196		    (ia = ifatoia(ifa_ifwithnet(sintosa(dst)))) == NULL) {
197			ipstat.ips_noroute++;
198			error = ENETUNREACH;
199			goto bad;
200		}
201		ifp = ia->ia_ifp;
202		ip->ip_ttl = 1;
203		isbroadcast = in_broadcast(dst->sin_addr, ifp);
204	} else if (flags & IP_SENDONES) {
205		if ((ia = ifatoia(ifa_ifwithbroadaddr(sintosa(dst)))) == NULL) {
206			ipstat.ips_noroute++;
207			error = ENETUNREACH;
208			goto bad;
209		}
210		ifp = ia->ia_ifp;
211		ip->ip_dst.s_addr = INADDR_BROADCAST;
212		dst->sin_addr = ip->ip_dst;
213		ip->ip_ttl = 1;
214		isbroadcast = 1;
215	} else if (IN_MULTICAST(ntohl(ip->ip_dst.s_addr)) &&
216	    imo != NULL && imo->imo_multicast_ifp != NULL) {
217		/*
218		 * Bypass the normal routing lookup for multicast
219		 * packets if the interface is specified.
220		 */
221		ifp = imo->imo_multicast_ifp;
222		IFP_TO_IA(ifp, ia);
223		isbroadcast = 0;	/* fool gcc */
224	} else {
225		/*
226		 * We want to do any cloning requested by the link layer,
227		 * as this is probably required in all cases for correct
228		 * operation (as it is for ARP).
229		 */
230		if (ro->ro_rt == NULL)
231			rtalloc_ign(ro, 0);
232		if (ro->ro_rt == NULL) {
233			ipstat.ips_noroute++;
234			error = EHOSTUNREACH;
235			goto bad;
236		}
237		ia = ifatoia(ro->ro_rt->rt_ifa);
238		ifp = ro->ro_rt->rt_ifp;
239		ro->ro_rt->rt_rmx.rmx_pksent++;
240		if (ro->ro_rt->rt_flags & RTF_GATEWAY)
241			dst = (struct sockaddr_in *)ro->ro_rt->rt_gateway;
242		if (ro->ro_rt->rt_flags & RTF_HOST)
243			isbroadcast = (ro->ro_rt->rt_flags & RTF_BROADCAST);
244		else
245			isbroadcast = in_broadcast(dst->sin_addr, ifp);
246	}
247	/*
248	 * Calculate MTU.  If we have a route that is up, use that,
249	 * otherwise use the interface's MTU.
250	 */
251	if (ro->ro_rt != NULL && (ro->ro_rt->rt_flags & (RTF_UP|RTF_HOST))) {
252		/*
253		 * This case can happen if the user changed the MTU
254		 * of an interface after enabling IP on it.  Because
255		 * most netifs don't keep track of routes pointing to
256		 * them, there is no way for one to update all its
257		 * routes when the MTU is changed.
258		 */
259		if (ro->ro_rt->rt_rmx.rmx_mtu > ifp->if_mtu)
260			ro->ro_rt->rt_rmx.rmx_mtu = ifp->if_mtu;
261		mtu = ro->ro_rt->rt_rmx.rmx_mtu;
262	} else {
263		mtu = ifp->if_mtu;
264	}
265	if (IN_MULTICAST(ntohl(ip->ip_dst.s_addr))) {
266		struct in_multi *inm;
267
268		m->m_flags |= M_MCAST;
269		/*
270		 * IP destination address is multicast.  Make sure "dst"
271		 * still points to the address in "ro".  (It may have been
272		 * changed to point to a gateway address, above.)
273		 */
274		dst = (struct sockaddr_in *)&ro->ro_dst;
275		/*
276		 * See if the caller provided any multicast options
277		 */
278		if (imo != NULL) {
279			ip->ip_ttl = imo->imo_multicast_ttl;
280			if (imo->imo_multicast_vif != -1)
281				ip->ip_src.s_addr =
282				    ip_mcast_src ?
283				    ip_mcast_src(imo->imo_multicast_vif) :
284				    INADDR_ANY;
285		} else
286			ip->ip_ttl = IP_DEFAULT_MULTICAST_TTL;
287		/*
288		 * Confirm that the outgoing interface supports multicast.
289		 */
290		if ((imo == NULL) || (imo->imo_multicast_vif == -1)) {
291			if ((ifp->if_flags & IFF_MULTICAST) == 0) {
292				ipstat.ips_noroute++;
293				error = ENETUNREACH;
294				goto bad;
295			}
296		}
297		/*
298		 * If source address not specified yet, use address
299		 * of outgoing interface.
300		 */
301		if (ip->ip_src.s_addr == INADDR_ANY) {
302			/* Interface may have no addresses. */
303			if (ia != NULL)
304				ip->ip_src = IA_SIN(ia)->sin_addr;
305		}
306
307		IN_MULTI_LOCK();
308		IN_LOOKUP_MULTI(ip->ip_dst, ifp, inm);
309		if (inm != NULL &&
310		   (imo == NULL || imo->imo_multicast_loop)) {
311			IN_MULTI_UNLOCK();
312			/*
313			 * If we belong to the destination multicast group
314			 * on the outgoing interface, and the caller did not
315			 * forbid loopback, loop back a copy.
316			 */
317			ip_mloopback(ifp, m, dst, hlen);
318		}
319		else {
320			IN_MULTI_UNLOCK();
321			/*
322			 * If we are acting as a multicast router, perform
323			 * multicast forwarding as if the packet had just
324			 * arrived on the interface to which we are about
325			 * to send.  The multicast forwarding function
326			 * recursively calls this function, using the
327			 * IP_FORWARDING flag to prevent infinite recursion.
328			 *
329			 * Multicasts that are looped back by ip_mloopback(),
330			 * above, will be forwarded by the ip_input() routine,
331			 * if necessary.
332			 */
333			if (ip_mrouter && (flags & IP_FORWARDING) == 0) {
334				/*
335				 * If rsvp daemon is not running, do not
336				 * set ip_moptions. This ensures that the packet
337				 * is multicast and not just sent down one link
338				 * as prescribed by rsvpd.
339				 */
340				if (!rsvp_on)
341					imo = NULL;
342				if (ip_mforward &&
343				    ip_mforward(ip, ifp, m, imo) != 0) {
344					m_freem(m);
345					goto done;
346				}
347			}
348		}
349
350		/*
351		 * Multicasts with a time-to-live of zero may be looped-
352		 * back, above, but must not be transmitted on a network.
353		 * Also, multicasts addressed to the loopback interface
354		 * are not sent -- the above call to ip_mloopback() will
355		 * loop back a copy if this host actually belongs to the
356		 * destination group on the loopback interface.
357		 */
358		if (ip->ip_ttl == 0 || ifp->if_flags & IFF_LOOPBACK) {
359			m_freem(m);
360			goto done;
361		}
362
363		goto sendit;
364	}
365
366	/*
367	 * If the source address is not specified yet, use the address
368	 * of the outoing interface.
369	 */
370	if (ip->ip_src.s_addr == INADDR_ANY) {
371		/* Interface may have no addresses. */
372		if (ia != NULL) {
373			ip->ip_src = IA_SIN(ia)->sin_addr;
374		}
375	}
376
377	/*
378	 * Verify that we have any chance at all of being able to queue the
379	 * packet or packet fragments, unless ALTQ is enabled on the given
380	 * interface in which case packetdrop should be done by queueing.
381	 */
382#ifdef ALTQ
383	if ((!ALTQ_IS_ENABLED(&ifp->if_snd)) &&
384	    ((ifp->if_snd.ifq_len + ip->ip_len / mtu + 1) >=
385	    ifp->if_snd.ifq_maxlen))
386#else
387	if ((ifp->if_snd.ifq_len + ip->ip_len / mtu + 1) >=
388	    ifp->if_snd.ifq_maxlen)
389#endif /* ALTQ */
390	{
391		error = ENOBUFS;
392		ipstat.ips_odropped++;
393		ifp->if_snd.ifq_drops += (ip->ip_len / ifp->if_mtu + 1);
394		goto bad;
395	}
396
397	/*
398	 * Look for broadcast address and
399	 * verify user is allowed to send
400	 * such a packet.
401	 */
402	if (isbroadcast) {
403		if ((ifp->if_flags & IFF_BROADCAST) == 0) {
404			error = EADDRNOTAVAIL;
405			goto bad;
406		}
407		if ((flags & IP_ALLOWBROADCAST) == 0) {
408			error = EACCES;
409			goto bad;
410		}
411		/* don't allow broadcast messages to be fragmented */
412		if (ip->ip_len > mtu) {
413			error = EMSGSIZE;
414			goto bad;
415		}
416		m->m_flags |= M_BCAST;
417	} else {
418		m->m_flags &= ~M_BCAST;
419	}
420
421sendit:
422#if defined(IPSEC) || defined(FAST_IPSEC)
423	switch(ip_ipsec_output(&m, inp, &flags, &error, &ro, &iproute, &dst, &ia, &ifp)) {
424	case 1:
425		goto bad;
426	case -1:
427		goto done;
428	case 0:
429	default:
430		break;	/* Continue with packet processing. */
431	}
432	/* Update variables that are affected by ipsec4_output(). */
433	ip = mtod(m, struct ip *);
434	hlen = ip->ip_hl << 2;
435#endif /* IPSEC */
436
437	/* Jump over all PFIL processing if hooks are not active. */
438	if (!PFIL_HOOKED(&inet_pfil_hook))
439		goto passout;
440
441	/* Run through list of hooks for output packets. */
442	odst.s_addr = ip->ip_dst.s_addr;
443	error = pfil_run_hooks(&inet_pfil_hook, &m, ifp, PFIL_OUT, inp);
444	if (error != 0 || m == NULL)
445		goto done;
446
447	ip = mtod(m, struct ip *);
448
449	/* See if destination IP address was changed by packet filter. */
450	if (odst.s_addr != ip->ip_dst.s_addr) {
451		m->m_flags |= M_SKIP_FIREWALL;
452		/* If destination is now ourself drop to ip_input(). */
453		if (in_localip(ip->ip_dst)) {
454			m->m_flags |= M_FASTFWD_OURS;
455			if (m->m_pkthdr.rcvif == NULL)
456				m->m_pkthdr.rcvif = loif;
457			if (m->m_pkthdr.csum_flags & CSUM_DELAY_DATA) {
458				m->m_pkthdr.csum_flags |=
459				    CSUM_DATA_VALID | CSUM_PSEUDO_HDR;
460				m->m_pkthdr.csum_data = 0xffff;
461			}
462			m->m_pkthdr.csum_flags |=
463			    CSUM_IP_CHECKED | CSUM_IP_VALID;
464
465			error = netisr_queue(NETISR_IP, m);
466			goto done;
467		} else
468			goto again;	/* Redo the routing table lookup. */
469	}
470
471#ifdef IPFIREWALL_FORWARD
472	/* See if local, if yes, send it to netisr with IP_FASTFWD_OURS. */
473	if (m->m_flags & M_FASTFWD_OURS) {
474		if (m->m_pkthdr.rcvif == NULL)
475			m->m_pkthdr.rcvif = loif;
476		if (m->m_pkthdr.csum_flags & CSUM_DELAY_DATA) {
477			m->m_pkthdr.csum_flags |=
478			    CSUM_DATA_VALID | CSUM_PSEUDO_HDR;
479			m->m_pkthdr.csum_data = 0xffff;
480		}
481		m->m_pkthdr.csum_flags |=
482			    CSUM_IP_CHECKED | CSUM_IP_VALID;
483
484		error = netisr_queue(NETISR_IP, m);
485		goto done;
486	}
487	/* Or forward to some other address? */
488	fwd_tag = m_tag_find(m, PACKET_TAG_IPFORWARD, NULL);
489	if (fwd_tag) {
490		dst = (struct sockaddr_in *)&ro->ro_dst;
491		bcopy((fwd_tag+1), dst, sizeof(struct sockaddr_in));
492		m->m_flags |= M_SKIP_FIREWALL;
493		m_tag_delete(m, fwd_tag);
494		goto again;
495	}
496#endif /* IPFIREWALL_FORWARD */
497
498passout:
499	/* 127/8 must not appear on wire - RFC1122. */
500	if ((ntohl(ip->ip_dst.s_addr) >> IN_CLASSA_NSHIFT) == IN_LOOPBACKNET ||
501	    (ntohl(ip->ip_src.s_addr) >> IN_CLASSA_NSHIFT) == IN_LOOPBACKNET) {
502		if ((ifp->if_flags & IFF_LOOPBACK) == 0) {
503			ipstat.ips_badaddr++;
504			error = EADDRNOTAVAIL;
505			goto bad;
506		}
507	}
508
509	m->m_pkthdr.csum_flags |= CSUM_IP;
510	sw_csum = m->m_pkthdr.csum_flags & ~ifp->if_hwassist;
511	if (sw_csum & CSUM_DELAY_DATA) {
512		in_delayed_cksum(m);
513		sw_csum &= ~CSUM_DELAY_DATA;
514	}
515	m->m_pkthdr.csum_flags &= ifp->if_hwassist;
516
517	/*
518	 * If small enough for interface, or the interface will take
519	 * care of the fragmentation for us, we can just send directly.
520	 */
521	if (ip->ip_len <= mtu ||
522	    (m->m_pkthdr.csum_flags & ifp->if_hwassist & CSUM_TSO) != 0 ||
523	    ((ip->ip_off & IP_DF) == 0 && (ifp->if_hwassist & CSUM_FRAGMENT))) {
524		ip->ip_len = htons(ip->ip_len);
525		ip->ip_off = htons(ip->ip_off);
526		ip->ip_sum = 0;
527		if (sw_csum & CSUM_DELAY_IP)
528			ip->ip_sum = in_cksum(m, hlen);
529
530		/*
531		 * Record statistics for this interface address.
532		 * With CSUM_TSO the byte/packet count will be slightly
533		 * incorrect because we count the IP+TCP headers only
534		 * once instead of for every generated packet.
535		 */
536		if (!(flags & IP_FORWARDING) && ia) {
537			if (m->m_pkthdr.csum_flags & CSUM_TSO)
538				ia->ia_ifa.if_opackets +=
539				    m->m_pkthdr.len / m->m_pkthdr.tso_segsz;
540			else
541				ia->ia_ifa.if_opackets++;
542			ia->ia_ifa.if_obytes += m->m_pkthdr.len;
543		}
544#ifdef IPSEC
545		/* clean ipsec history once it goes out of the node */
546		ipsec_delaux(m);
547#endif
548#ifdef MBUF_STRESS_TEST
549		if (mbuf_frag_size && m->m_pkthdr.len > mbuf_frag_size)
550			m = m_fragment(m, M_DONTWAIT, mbuf_frag_size);
551#endif
552		/*
553		 * Reset layer specific mbuf flags
554		 * to avoid confusing lower layers.
555		 */
556		m->m_flags &= ~(M_PROTOFLAGS);
557
558		error = (*ifp->if_output)(ifp, m,
559				(struct sockaddr *)dst, ro->ro_rt);
560		goto done;
561	}
562
563	/* Balk when DF bit is set or the interface didn't support TSO. */
564	if ((ip->ip_off & IP_DF) || (m->m_pkthdr.csum_flags & CSUM_TSO)) {
565		error = EMSGSIZE;
566		ipstat.ips_cantfrag++;
567		goto bad;
568	}
569
570	/*
571	 * Too large for interface; fragment if possible. If successful,
572	 * on return, m will point to a list of packets to be sent.
573	 */
574	error = ip_fragment(ip, &m, mtu, ifp->if_hwassist, sw_csum);
575	if (error)
576		goto bad;
577	for (; m; m = m0) {
578		m0 = m->m_nextpkt;
579		m->m_nextpkt = 0;
580#ifdef IPSEC
581		/* clean ipsec history once it goes out of the node */
582		ipsec_delaux(m);
583#endif
584		if (error == 0) {
585			/* Record statistics for this interface address. */
586			if (ia != NULL) {
587				ia->ia_ifa.if_opackets++;
588				ia->ia_ifa.if_obytes += m->m_pkthdr.len;
589			}
590			/*
591			 * Reset layer specific mbuf flags
592			 * to avoid confusing upper layers.
593			 */
594			m->m_flags &= ~(M_PROTOFLAGS);
595
596			error = (*ifp->if_output)(ifp, m,
597			    (struct sockaddr *)dst, ro->ro_rt);
598		} else
599			m_freem(m);
600	}
601
602	if (error == 0)
603		ipstat.ips_fragmented++;
604
605done:
606	if (ro == &iproute && ro->ro_rt) {
607		RTFREE(ro->ro_rt);
608	}
609	return (error);
610bad:
611	m_freem(m);
612	goto done;
613}
614
615/*
616 * Create a chain of fragments which fit the given mtu. m_frag points to the
617 * mbuf to be fragmented; on return it points to the chain with the fragments.
618 * Return 0 if no error. If error, m_frag may contain a partially built
619 * chain of fragments that should be freed by the caller.
620 *
621 * if_hwassist_flags is the hw offload capabilities (see if_data.ifi_hwassist)
622 * sw_csum contains the delayed checksums flags (e.g., CSUM_DELAY_IP).
623 */
624int
625ip_fragment(struct ip *ip, struct mbuf **m_frag, int mtu,
626	    u_long if_hwassist_flags, int sw_csum)
627{
628	int error = 0;
629	int hlen = ip->ip_hl << 2;
630	int len = (mtu - hlen) & ~7;	/* size of payload in each fragment */
631	int off;
632	struct mbuf *m0 = *m_frag;	/* the original packet		*/
633	int firstlen;
634	struct mbuf **mnext;
635	int nfrags;
636
637	if (ip->ip_off & IP_DF) {	/* Fragmentation not allowed */
638		ipstat.ips_cantfrag++;
639		return EMSGSIZE;
640	}
641
642	/*
643	 * Must be able to put at least 8 bytes per fragment.
644	 */
645	if (len < 8)
646		return EMSGSIZE;
647
648	/*
649	 * If the interface will not calculate checksums on
650	 * fragmented packets, then do it here.
651	 */
652	if (m0->m_pkthdr.csum_flags & CSUM_DELAY_DATA &&
653	    (if_hwassist_flags & CSUM_IP_FRAGS) == 0) {
654		in_delayed_cksum(m0);
655		m0->m_pkthdr.csum_flags &= ~CSUM_DELAY_DATA;
656	}
657
658	if (len > PAGE_SIZE) {
659		/*
660		 * Fragment large datagrams such that each segment
661		 * contains a multiple of PAGE_SIZE amount of data,
662		 * plus headers. This enables a receiver to perform
663		 * page-flipping zero-copy optimizations.
664		 *
665		 * XXX When does this help given that sender and receiver
666		 * could have different page sizes, and also mtu could
667		 * be less than the receiver's page size ?
668		 */
669		int newlen;
670		struct mbuf *m;
671
672		for (m = m0, off = 0; m && (off+m->m_len) <= mtu; m = m->m_next)
673			off += m->m_len;
674
675		/*
676		 * firstlen (off - hlen) must be aligned on an
677		 * 8-byte boundary
678		 */
679		if (off < hlen)
680			goto smart_frag_failure;
681		off = ((off - hlen) & ~7) + hlen;
682		newlen = (~PAGE_MASK) & mtu;
683		if ((newlen + sizeof (struct ip)) > mtu) {
684			/* we failed, go back the default */
685smart_frag_failure:
686			newlen = len;
687			off = hlen + len;
688		}
689		len = newlen;
690
691	} else {
692		off = hlen + len;
693	}
694
695	firstlen = off - hlen;
696	mnext = &m0->m_nextpkt;		/* pointer to next packet */
697
698	/*
699	 * Loop through length of segment after first fragment,
700	 * make new header and copy data of each part and link onto chain.
701	 * Here, m0 is the original packet, m is the fragment being created.
702	 * The fragments are linked off the m_nextpkt of the original
703	 * packet, which after processing serves as the first fragment.
704	 */
705	for (nfrags = 1; off < ip->ip_len; off += len, nfrags++) {
706		struct ip *mhip;	/* ip header on the fragment */
707		struct mbuf *m;
708		int mhlen = sizeof (struct ip);
709
710		MGETHDR(m, M_DONTWAIT, MT_DATA);
711		if (m == NULL) {
712			error = ENOBUFS;
713			ipstat.ips_odropped++;
714			goto done;
715		}
716		m->m_flags |= (m0->m_flags & M_MCAST) | M_FRAG;
717		/*
718		 * In the first mbuf, leave room for the link header, then
719		 * copy the original IP header including options. The payload
720		 * goes into an additional mbuf chain returned by m_copy().
721		 */
722		m->m_data += max_linkhdr;
723		mhip = mtod(m, struct ip *);
724		*mhip = *ip;
725		if (hlen > sizeof (struct ip)) {
726			mhlen = ip_optcopy(ip, mhip) + sizeof (struct ip);
727			mhip->ip_v = IPVERSION;
728			mhip->ip_hl = mhlen >> 2;
729		}
730		m->m_len = mhlen;
731		/* XXX do we need to add ip->ip_off below ? */
732		mhip->ip_off = ((off - hlen) >> 3) + ip->ip_off;
733		if (off + len >= ip->ip_len) {	/* last fragment */
734			len = ip->ip_len - off;
735			m->m_flags |= M_LASTFRAG;
736		} else
737			mhip->ip_off |= IP_MF;
738		mhip->ip_len = htons((u_short)(len + mhlen));
739		m->m_next = m_copy(m0, off, len);
740		if (m->m_next == NULL) {	/* copy failed */
741			m_free(m);
742			error = ENOBUFS;	/* ??? */
743			ipstat.ips_odropped++;
744			goto done;
745		}
746		m->m_pkthdr.len = mhlen + len;
747		m->m_pkthdr.rcvif = NULL;
748#ifdef MAC
749		mac_create_fragment(m0, m);
750#endif
751		m->m_pkthdr.csum_flags = m0->m_pkthdr.csum_flags;
752		mhip->ip_off = htons(mhip->ip_off);
753		mhip->ip_sum = 0;
754		if (sw_csum & CSUM_DELAY_IP)
755			mhip->ip_sum = in_cksum(m, mhlen);
756		*mnext = m;
757		mnext = &m->m_nextpkt;
758	}
759	ipstat.ips_ofragments += nfrags;
760
761	/* set first marker for fragment chain */
762	m0->m_flags |= M_FIRSTFRAG | M_FRAG;
763	m0->m_pkthdr.csum_data = nfrags;
764
765	/*
766	 * Update first fragment by trimming what's been copied out
767	 * and updating header.
768	 */
769	m_adj(m0, hlen + firstlen - ip->ip_len);
770	m0->m_pkthdr.len = hlen + firstlen;
771	ip->ip_len = htons((u_short)m0->m_pkthdr.len);
772	ip->ip_off |= IP_MF;
773	ip->ip_off = htons(ip->ip_off);
774	ip->ip_sum = 0;
775	if (sw_csum & CSUM_DELAY_IP)
776		ip->ip_sum = in_cksum(m0, hlen);
777
778done:
779	*m_frag = m0;
780	return error;
781}
782
783void
784in_delayed_cksum(struct mbuf *m)
785{
786	struct ip *ip;
787	u_short csum, offset;
788
789	ip = mtod(m, struct ip *);
790	offset = ip->ip_hl << 2 ;
791	csum = in_cksum_skip(m, ip->ip_len, offset);
792	if (m->m_pkthdr.csum_flags & CSUM_UDP && csum == 0)
793		csum = 0xffff;
794	offset += m->m_pkthdr.csum_data;	/* checksum offset */
795
796	if (offset + sizeof(u_short) > m->m_len) {
797		printf("delayed m_pullup, m->len: %d  off: %d  p: %d\n",
798		    m->m_len, offset, ip->ip_p);
799		/*
800		 * XXX
801		 * this shouldn't happen, but if it does, the
802		 * correct behavior may be to insert the checksum
803		 * in the appropriate next mbuf in the chain.
804		 */
805		return;
806	}
807	*(u_short *)(m->m_data + offset) = csum;
808}
809
810/*
811 * IP socket option processing.
812 */
813int
814ip_ctloutput(so, sopt)
815	struct socket *so;
816	struct sockopt *sopt;
817{
818	struct	inpcb *inp = sotoinpcb(so);
819	int	error, optval;
820
821	error = optval = 0;
822	if (sopt->sopt_level != IPPROTO_IP) {
823		return (EINVAL);
824	}
825
826	switch (sopt->sopt_dir) {
827	case SOPT_SET:
828		switch (sopt->sopt_name) {
829		case IP_OPTIONS:
830#ifdef notyet
831		case IP_RETOPTS:
832#endif
833		{
834			struct mbuf *m;
835			if (sopt->sopt_valsize > MLEN) {
836				error = EMSGSIZE;
837				break;
838			}
839			MGET(m, sopt->sopt_td ? M_TRYWAIT : M_DONTWAIT, MT_DATA);
840			if (m == NULL) {
841				error = ENOBUFS;
842				break;
843			}
844			m->m_len = sopt->sopt_valsize;
845			error = sooptcopyin(sopt, mtod(m, char *), m->m_len,
846					    m->m_len);
847			if (error) {
848				m_free(m);
849				break;
850			}
851			INP_LOCK(inp);
852			error = ip_pcbopts(inp, sopt->sopt_name, m);
853			INP_UNLOCK(inp);
854			return (error);
855		}
856
857		case IP_TOS:
858		case IP_TTL:
859		case IP_MINTTL:
860		case IP_RECVOPTS:
861		case IP_RECVRETOPTS:
862		case IP_RECVDSTADDR:
863		case IP_RECVTTL:
864		case IP_RECVIF:
865		case IP_FAITH:
866		case IP_ONESBCAST:
867		case IP_DONTFRAG:
868			error = sooptcopyin(sopt, &optval, sizeof optval,
869					    sizeof optval);
870			if (error)
871				break;
872
873			switch (sopt->sopt_name) {
874			case IP_TOS:
875				inp->inp_ip_tos = optval;
876				break;
877
878			case IP_TTL:
879				inp->inp_ip_ttl = optval;
880				break;
881
882			case IP_MINTTL:
883				if (optval > 0 && optval <= MAXTTL)
884					inp->inp_ip_minttl = optval;
885				else
886					error = EINVAL;
887				break;
888
889#define	OPTSET(bit) do {						\
890	INP_LOCK(inp);							\
891	if (optval)							\
892		inp->inp_flags |= bit;					\
893	else								\
894		inp->inp_flags &= ~bit;					\
895	INP_UNLOCK(inp);						\
896} while (0)
897
898			case IP_RECVOPTS:
899				OPTSET(INP_RECVOPTS);
900				break;
901
902			case IP_RECVRETOPTS:
903				OPTSET(INP_RECVRETOPTS);
904				break;
905
906			case IP_RECVDSTADDR:
907				OPTSET(INP_RECVDSTADDR);
908				break;
909
910			case IP_RECVTTL:
911				OPTSET(INP_RECVTTL);
912				break;
913
914			case IP_RECVIF:
915				OPTSET(INP_RECVIF);
916				break;
917
918			case IP_FAITH:
919				OPTSET(INP_FAITH);
920				break;
921
922			case IP_ONESBCAST:
923				OPTSET(INP_ONESBCAST);
924				break;
925			case IP_DONTFRAG:
926				OPTSET(INP_DONTFRAG);
927				break;
928			}
929			break;
930#undef OPTSET
931
932		case IP_MULTICAST_IF:
933		case IP_MULTICAST_VIF:
934		case IP_MULTICAST_TTL:
935		case IP_MULTICAST_LOOP:
936		case IP_ADD_MEMBERSHIP:
937		case IP_DROP_MEMBERSHIP:
938			error = ip_setmoptions(inp, sopt);
939			break;
940
941		case IP_PORTRANGE:
942			error = sooptcopyin(sopt, &optval, sizeof optval,
943					    sizeof optval);
944			if (error)
945				break;
946
947			INP_LOCK(inp);
948			switch (optval) {
949			case IP_PORTRANGE_DEFAULT:
950				inp->inp_flags &= ~(INP_LOWPORT);
951				inp->inp_flags &= ~(INP_HIGHPORT);
952				break;
953
954			case IP_PORTRANGE_HIGH:
955				inp->inp_flags &= ~(INP_LOWPORT);
956				inp->inp_flags |= INP_HIGHPORT;
957				break;
958
959			case IP_PORTRANGE_LOW:
960				inp->inp_flags &= ~(INP_HIGHPORT);
961				inp->inp_flags |= INP_LOWPORT;
962				break;
963
964			default:
965				error = EINVAL;
966				break;
967			}
968			INP_UNLOCK(inp);
969			break;
970
971#if defined(IPSEC) || defined(FAST_IPSEC)
972		case IP_IPSEC_POLICY:
973		{
974			caddr_t req;
975			size_t len = 0;
976			int priv;
977			struct mbuf *m;
978			int optname;
979
980			if ((error = soopt_getm(sopt, &m)) != 0) /* XXX */
981				break;
982			if ((error = soopt_mcopyin(sopt, m)) != 0) /* XXX */
983				break;
984			if (sopt->sopt_td != NULL) {
985				/*
986				 * XXXRW: Would be more desirable to do this
987				 * one layer down so that we only exercise
988				 * privilege if it is needed.
989				 */
990				error = priv_check(sopt->sopt_td,
991				    PRIV_NETINET_IPSEC);
992				if (error)
993					priv = 0;
994				else
995					priv = 1;
996			} else
997				priv = 1;
998			req = mtod(m, caddr_t);
999			len = m->m_len;
1000			optname = sopt->sopt_name;
1001			error = ipsec4_set_policy(inp, optname, req, len, priv);
1002			m_freem(m);
1003			break;
1004		}
1005#endif /*IPSEC*/
1006
1007		default:
1008			error = ENOPROTOOPT;
1009			break;
1010		}
1011		break;
1012
1013	case SOPT_GET:
1014		switch (sopt->sopt_name) {
1015		case IP_OPTIONS:
1016		case IP_RETOPTS:
1017			if (inp->inp_options)
1018				error = sooptcopyout(sopt,
1019						     mtod(inp->inp_options,
1020							  char *),
1021						     inp->inp_options->m_len);
1022			else
1023				sopt->sopt_valsize = 0;
1024			break;
1025
1026		case IP_TOS:
1027		case IP_TTL:
1028		case IP_MINTTL:
1029		case IP_RECVOPTS:
1030		case IP_RECVRETOPTS:
1031		case IP_RECVDSTADDR:
1032		case IP_RECVTTL:
1033		case IP_RECVIF:
1034		case IP_PORTRANGE:
1035		case IP_FAITH:
1036		case IP_ONESBCAST:
1037		case IP_DONTFRAG:
1038			switch (sopt->sopt_name) {
1039
1040			case IP_TOS:
1041				optval = inp->inp_ip_tos;
1042				break;
1043
1044			case IP_TTL:
1045				optval = inp->inp_ip_ttl;
1046				break;
1047
1048			case IP_MINTTL:
1049				optval = inp->inp_ip_minttl;
1050				break;
1051
1052#define	OPTBIT(bit)	(inp->inp_flags & bit ? 1 : 0)
1053
1054			case IP_RECVOPTS:
1055				optval = OPTBIT(INP_RECVOPTS);
1056				break;
1057
1058			case IP_RECVRETOPTS:
1059				optval = OPTBIT(INP_RECVRETOPTS);
1060				break;
1061
1062			case IP_RECVDSTADDR:
1063				optval = OPTBIT(INP_RECVDSTADDR);
1064				break;
1065
1066			case IP_RECVTTL:
1067				optval = OPTBIT(INP_RECVTTL);
1068				break;
1069
1070			case IP_RECVIF:
1071				optval = OPTBIT(INP_RECVIF);
1072				break;
1073
1074			case IP_PORTRANGE:
1075				if (inp->inp_flags & INP_HIGHPORT)
1076					optval = IP_PORTRANGE_HIGH;
1077				else if (inp->inp_flags & INP_LOWPORT)
1078					optval = IP_PORTRANGE_LOW;
1079				else
1080					optval = 0;
1081				break;
1082
1083			case IP_FAITH:
1084				optval = OPTBIT(INP_FAITH);
1085				break;
1086
1087			case IP_ONESBCAST:
1088				optval = OPTBIT(INP_ONESBCAST);
1089				break;
1090			case IP_DONTFRAG:
1091				optval = OPTBIT(INP_DONTFRAG);
1092				break;
1093			}
1094			error = sooptcopyout(sopt, &optval, sizeof optval);
1095			break;
1096
1097		case IP_MULTICAST_IF:
1098		case IP_MULTICAST_VIF:
1099		case IP_MULTICAST_TTL:
1100		case IP_MULTICAST_LOOP:
1101		case IP_ADD_MEMBERSHIP:
1102		case IP_DROP_MEMBERSHIP:
1103			error = ip_getmoptions(inp, sopt);
1104			break;
1105
1106#if defined(IPSEC) || defined(FAST_IPSEC)
1107		case IP_IPSEC_POLICY:
1108		{
1109			struct mbuf *m = NULL;
1110			caddr_t req = NULL;
1111			size_t len = 0;
1112
1113			if (m != 0) {
1114				req = mtod(m, caddr_t);
1115				len = m->m_len;
1116			}
1117			error = ipsec4_get_policy(sotoinpcb(so), req, len, &m);
1118			if (error == 0)
1119				error = soopt_mcopyout(sopt, m); /* XXX */
1120			if (error == 0)
1121				m_freem(m);
1122			break;
1123		}
1124#endif /*IPSEC*/
1125
1126		default:
1127			error = ENOPROTOOPT;
1128			break;
1129		}
1130		break;
1131	}
1132	return (error);
1133}
1134
1135/*
1136 * XXX
1137 * The whole multicast option thing needs to be re-thought.
1138 * Several of these options are equally applicable to non-multicast
1139 * transmission, and one (IP_MULTICAST_TTL) totally duplicates a
1140 * standard option (IP_TTL).
1141 */
1142
1143/*
1144 * following RFC1724 section 3.3, 0.0.0.0/8 is interpreted as interface index.
1145 */
1146static struct ifnet *
1147ip_multicast_if(a, ifindexp)
1148	struct in_addr *a;
1149	int *ifindexp;
1150{
1151	int ifindex;
1152	struct ifnet *ifp;
1153
1154	if (ifindexp)
1155		*ifindexp = 0;
1156	if (ntohl(a->s_addr) >> 24 == 0) {
1157		ifindex = ntohl(a->s_addr) & 0xffffff;
1158		if (ifindex < 0 || if_index < ifindex)
1159			return NULL;
1160		ifp = ifnet_byindex(ifindex);
1161		if (ifindexp)
1162			*ifindexp = ifindex;
1163	} else {
1164		INADDR_TO_IFP(*a, ifp);
1165	}
1166	return ifp;
1167}
1168
1169/*
1170 * Given an inpcb, return its multicast options structure pointer.  Accepts
1171 * an unlocked inpcb pointer, but will return it locked.  May sleep.
1172 */
1173static struct ip_moptions *
1174ip_findmoptions(struct inpcb *inp)
1175{
1176	struct ip_moptions *imo;
1177	struct in_multi **immp;
1178
1179	INP_LOCK(inp);
1180	if (inp->inp_moptions != NULL)
1181		return (inp->inp_moptions);
1182
1183	INP_UNLOCK(inp);
1184
1185	imo = (struct ip_moptions*)malloc(sizeof(*imo), M_IPMOPTS, M_WAITOK);
1186	immp = (struct in_multi **)malloc((sizeof(*immp) * IP_MIN_MEMBERSHIPS),
1187					  M_IPMOPTS, M_WAITOK);
1188
1189	imo->imo_multicast_ifp = NULL;
1190	imo->imo_multicast_addr.s_addr = INADDR_ANY;
1191	imo->imo_multicast_vif = -1;
1192	imo->imo_multicast_ttl = IP_DEFAULT_MULTICAST_TTL;
1193	imo->imo_multicast_loop = IP_DEFAULT_MULTICAST_LOOP;
1194	imo->imo_num_memberships = 0;
1195	imo->imo_max_memberships = IP_MIN_MEMBERSHIPS;
1196	imo->imo_membership = immp;
1197
1198	INP_LOCK(inp);
1199	if (inp->inp_moptions != NULL) {
1200		free(immp, M_IPMOPTS);
1201		free(imo, M_IPMOPTS);
1202		return (inp->inp_moptions);
1203	}
1204	inp->inp_moptions = imo;
1205	return (imo);
1206}
1207
1208/*
1209 * Set the IP multicast options in response to user setsockopt().
1210 */
1211static int
1212ip_setmoptions(struct inpcb *inp, struct sockopt *sopt)
1213{
1214	int error = 0;
1215	int i;
1216	struct in_addr addr;
1217	struct ip_mreq mreq;
1218	struct ifnet *ifp;
1219	struct ip_moptions *imo;
1220	struct route ro;
1221	struct sockaddr_in *dst;
1222	int ifindex;
1223	int s;
1224
1225	switch (sopt->sopt_name) {
1226	/* store an index number for the vif you wanna use in the send */
1227	case IP_MULTICAST_VIF:
1228		if (legal_vif_num == 0) {
1229			error = EOPNOTSUPP;
1230			break;
1231		}
1232		error = sooptcopyin(sopt, &i, sizeof i, sizeof i);
1233		if (error)
1234			break;
1235		if (!legal_vif_num(i) && (i != -1)) {
1236			error = EINVAL;
1237			break;
1238		}
1239		imo = ip_findmoptions(inp);
1240		imo->imo_multicast_vif = i;
1241		INP_UNLOCK(inp);
1242		break;
1243
1244	case IP_MULTICAST_IF:
1245		/*
1246		 * Select the interface for outgoing multicast packets.
1247		 */
1248		error = sooptcopyin(sopt, &addr, sizeof addr, sizeof addr);
1249		if (error)
1250			break;
1251		/*
1252		 * INADDR_ANY is used to remove a previous selection.
1253		 * When no interface is selected, a default one is
1254		 * chosen every time a multicast packet is sent.
1255		 */
1256		imo = ip_findmoptions(inp);
1257		if (addr.s_addr == INADDR_ANY) {
1258			imo->imo_multicast_ifp = NULL;
1259			INP_UNLOCK(inp);
1260			break;
1261		}
1262		/*
1263		 * The selected interface is identified by its local
1264		 * IP address.  Find the interface and confirm that
1265		 * it supports multicasting.
1266		 */
1267		s = splimp();
1268		ifp = ip_multicast_if(&addr, &ifindex);
1269		if (ifp == NULL || (ifp->if_flags & IFF_MULTICAST) == 0) {
1270			INP_UNLOCK(inp);
1271			splx(s);
1272			error = EADDRNOTAVAIL;
1273			break;
1274		}
1275		imo->imo_multicast_ifp = ifp;
1276		if (ifindex)
1277			imo->imo_multicast_addr = addr;
1278		else
1279			imo->imo_multicast_addr.s_addr = INADDR_ANY;
1280		INP_UNLOCK(inp);
1281		splx(s);
1282		break;
1283
1284	case IP_MULTICAST_TTL:
1285		/*
1286		 * Set the IP time-to-live for outgoing multicast packets.
1287		 * The original multicast API required a char argument,
1288		 * which is inconsistent with the rest of the socket API.
1289		 * We allow either a char or an int.
1290		 */
1291		if (sopt->sopt_valsize == 1) {
1292			u_char ttl;
1293			error = sooptcopyin(sopt, &ttl, 1, 1);
1294			if (error)
1295				break;
1296			imo = ip_findmoptions(inp);
1297			imo->imo_multicast_ttl = ttl;
1298			INP_UNLOCK(inp);
1299		} else {
1300			u_int ttl;
1301			error = sooptcopyin(sopt, &ttl, sizeof ttl,
1302					    sizeof ttl);
1303			if (error)
1304				break;
1305			if (ttl > 255)
1306				error = EINVAL;
1307			else {
1308				imo = ip_findmoptions(inp);
1309				imo->imo_multicast_ttl = ttl;
1310				INP_UNLOCK(inp);
1311			}
1312		}
1313		break;
1314
1315	case IP_MULTICAST_LOOP:
1316		/*
1317		 * Set the loopback flag for outgoing multicast packets.
1318		 * Must be zero or one.  The original multicast API required a
1319		 * char argument, which is inconsistent with the rest
1320		 * of the socket API.  We allow either a char or an int.
1321		 */
1322		if (sopt->sopt_valsize == 1) {
1323			u_char loop;
1324			error = sooptcopyin(sopt, &loop, 1, 1);
1325			if (error)
1326				break;
1327			imo = ip_findmoptions(inp);
1328			imo->imo_multicast_loop = !!loop;
1329			INP_UNLOCK(inp);
1330		} else {
1331			u_int loop;
1332			error = sooptcopyin(sopt, &loop, sizeof loop,
1333					    sizeof loop);
1334			if (error)
1335				break;
1336			imo = ip_findmoptions(inp);
1337			imo->imo_multicast_loop = !!loop;
1338			INP_UNLOCK(inp);
1339		}
1340		break;
1341
1342	case IP_ADD_MEMBERSHIP:
1343		/*
1344		 * Add a multicast group membership.
1345		 * Group must be a valid IP multicast address.
1346		 */
1347		error = sooptcopyin(sopt, &mreq, sizeof mreq, sizeof mreq);
1348		if (error)
1349			break;
1350
1351		if (!IN_MULTICAST(ntohl(mreq.imr_multiaddr.s_addr))) {
1352			error = EINVAL;
1353			break;
1354		}
1355		s = splimp();
1356		/*
1357		 * If no interface address was provided, use the interface of
1358		 * the route to the given multicast address.
1359		 */
1360		if (mreq.imr_interface.s_addr == INADDR_ANY) {
1361			bzero((caddr_t)&ro, sizeof(ro));
1362			dst = (struct sockaddr_in *)&ro.ro_dst;
1363			dst->sin_len = sizeof(*dst);
1364			dst->sin_family = AF_INET;
1365			dst->sin_addr = mreq.imr_multiaddr;
1366			rtalloc_ign(&ro, RTF_CLONING);
1367			if (ro.ro_rt == NULL) {
1368				error = EADDRNOTAVAIL;
1369				splx(s);
1370				break;
1371			}
1372			ifp = ro.ro_rt->rt_ifp;
1373			RTFREE(ro.ro_rt);
1374		}
1375		else {
1376			ifp = ip_multicast_if(&mreq.imr_interface, NULL);
1377		}
1378
1379		/*
1380		 * See if we found an interface, and confirm that it
1381		 * supports multicast.
1382		 */
1383		if (ifp == NULL || (ifp->if_flags & IFF_MULTICAST) == 0) {
1384			error = EADDRNOTAVAIL;
1385			splx(s);
1386			break;
1387		}
1388		/*
1389		 * See if the membership already exists or if all the
1390		 * membership slots are full.
1391		 */
1392		imo = ip_findmoptions(inp);
1393		for (i = 0; i < imo->imo_num_memberships; ++i) {
1394			if (imo->imo_membership[i]->inm_ifp == ifp &&
1395			    imo->imo_membership[i]->inm_addr.s_addr
1396						== mreq.imr_multiaddr.s_addr)
1397				break;
1398		}
1399		if (i < imo->imo_num_memberships) {
1400			INP_UNLOCK(inp);
1401			error = EADDRINUSE;
1402			splx(s);
1403			break;
1404		}
1405		if (imo->imo_num_memberships == imo->imo_max_memberships) {
1406		    struct in_multi **nmships, **omships;
1407		    size_t newmax;
1408		    /*
1409		     * Resize the vector to next power-of-two minus 1. If the
1410		     * size would exceed the maximum then we know we've really
1411		     * run out of entries. Otherwise, we realloc() the vector
1412		     * with the INP lock held to avoid introducing a race.
1413		     */
1414		    nmships = NULL;
1415		    omships = imo->imo_membership;
1416		    newmax = ((imo->imo_max_memberships + 1) * 2) - 1;
1417		    if (newmax <= IP_MAX_MEMBERSHIPS) {
1418			nmships = (struct in_multi **)realloc(omships,
1419sizeof(*nmships) * newmax, M_IPMOPTS, M_NOWAIT);
1420			if (nmships != NULL) {
1421			    imo->imo_membership = nmships;
1422			    imo->imo_max_memberships = newmax;
1423			}
1424		    }
1425		    if (nmships == NULL) {
1426			INP_UNLOCK(inp);
1427			error = ETOOMANYREFS;
1428			splx(s);
1429			break;
1430		    }
1431		}
1432		/*
1433		 * Everything looks good; add a new record to the multicast
1434		 * address list for the given interface.
1435		 */
1436		if ((imo->imo_membership[i] =
1437		    in_addmulti(&mreq.imr_multiaddr, ifp)) == NULL) {
1438			INP_UNLOCK(inp);
1439			error = ENOBUFS;
1440			splx(s);
1441			break;
1442		}
1443		++imo->imo_num_memberships;
1444		INP_UNLOCK(inp);
1445		splx(s);
1446		break;
1447
1448	case IP_DROP_MEMBERSHIP:
1449		/*
1450		 * Drop a multicast group membership.
1451		 * Group must be a valid IP multicast address.
1452		 */
1453		error = sooptcopyin(sopt, &mreq, sizeof mreq, sizeof mreq);
1454		if (error)
1455			break;
1456
1457		if (!IN_MULTICAST(ntohl(mreq.imr_multiaddr.s_addr))) {
1458			error = EINVAL;
1459			break;
1460		}
1461
1462		s = splimp();
1463		/*
1464		 * If an interface address was specified, get a pointer
1465		 * to its ifnet structure.
1466		 */
1467		if (mreq.imr_interface.s_addr == INADDR_ANY)
1468			ifp = NULL;
1469		else {
1470			ifp = ip_multicast_if(&mreq.imr_interface, NULL);
1471			if (ifp == NULL) {
1472				error = EADDRNOTAVAIL;
1473				splx(s);
1474				break;
1475			}
1476		}
1477		/*
1478		 * Find the membership in the membership array.
1479		 */
1480		imo = ip_findmoptions(inp);
1481		for (i = 0; i < imo->imo_num_memberships; ++i) {
1482			if ((ifp == NULL ||
1483			     imo->imo_membership[i]->inm_ifp == ifp) &&
1484			     imo->imo_membership[i]->inm_addr.s_addr ==
1485			     mreq.imr_multiaddr.s_addr)
1486				break;
1487		}
1488		if (i == imo->imo_num_memberships) {
1489			INP_UNLOCK(inp);
1490			error = EADDRNOTAVAIL;
1491			splx(s);
1492			break;
1493		}
1494		/*
1495		 * Give up the multicast address record to which the
1496		 * membership points.
1497		 */
1498		in_delmulti(imo->imo_membership[i]);
1499		/*
1500		 * Remove the gap in the membership array.
1501		 */
1502		for (++i; i < imo->imo_num_memberships; ++i)
1503			imo->imo_membership[i-1] = imo->imo_membership[i];
1504		--imo->imo_num_memberships;
1505		INP_UNLOCK(inp);
1506		splx(s);
1507		break;
1508
1509	default:
1510		error = EOPNOTSUPP;
1511		break;
1512	}
1513
1514	return (error);
1515}
1516
1517/*
1518 * Return the IP multicast options in response to user getsockopt().
1519 */
1520static int
1521ip_getmoptions(struct inpcb *inp, struct sockopt *sopt)
1522{
1523	struct ip_moptions *imo;
1524	struct in_addr addr;
1525	struct in_ifaddr *ia;
1526	int error, optval;
1527	u_char coptval;
1528
1529	INP_LOCK(inp);
1530	imo = inp->inp_moptions;
1531
1532	error = 0;
1533	switch (sopt->sopt_name) {
1534	case IP_MULTICAST_VIF:
1535		if (imo != NULL)
1536			optval = imo->imo_multicast_vif;
1537		else
1538			optval = -1;
1539		INP_UNLOCK(inp);
1540		error = sooptcopyout(sopt, &optval, sizeof optval);
1541		break;
1542
1543	case IP_MULTICAST_IF:
1544		if (imo == NULL || imo->imo_multicast_ifp == NULL)
1545			addr.s_addr = INADDR_ANY;
1546		else if (imo->imo_multicast_addr.s_addr) {
1547			/* return the value user has set */
1548			addr = imo->imo_multicast_addr;
1549		} else {
1550			IFP_TO_IA(imo->imo_multicast_ifp, ia);
1551			addr.s_addr = (ia == NULL) ? INADDR_ANY
1552				: IA_SIN(ia)->sin_addr.s_addr;
1553		}
1554		INP_UNLOCK(inp);
1555		error = sooptcopyout(sopt, &addr, sizeof addr);
1556		break;
1557
1558	case IP_MULTICAST_TTL:
1559		if (imo == 0)
1560			optval = coptval = IP_DEFAULT_MULTICAST_TTL;
1561		else
1562			optval = coptval = imo->imo_multicast_ttl;
1563		INP_UNLOCK(inp);
1564		if (sopt->sopt_valsize == 1)
1565			error = sooptcopyout(sopt, &coptval, 1);
1566		else
1567			error = sooptcopyout(sopt, &optval, sizeof optval);
1568		break;
1569
1570	case IP_MULTICAST_LOOP:
1571		if (imo == 0)
1572			optval = coptval = IP_DEFAULT_MULTICAST_LOOP;
1573		else
1574			optval = coptval = imo->imo_multicast_loop;
1575		INP_UNLOCK(inp);
1576		if (sopt->sopt_valsize == 1)
1577			error = sooptcopyout(sopt, &coptval, 1);
1578		else
1579			error = sooptcopyout(sopt, &optval, sizeof optval);
1580		break;
1581
1582	default:
1583		INP_UNLOCK(inp);
1584		error = ENOPROTOOPT;
1585		break;
1586	}
1587	INP_UNLOCK_ASSERT(inp);
1588
1589	return (error);
1590}
1591
1592/*
1593 * Discard the IP multicast options.
1594 */
1595void
1596ip_freemoptions(imo)
1597	register struct ip_moptions *imo;
1598{
1599	register int i;
1600
1601	if (imo != NULL) {
1602		for (i = 0; i < imo->imo_num_memberships; ++i)
1603			in_delmulti(imo->imo_membership[i]);
1604		free(imo->imo_membership, M_IPMOPTS);
1605		free(imo, M_IPMOPTS);
1606	}
1607}
1608
1609/*
1610 * Routine called from ip_output() to loop back a copy of an IP multicast
1611 * packet to the input queue of a specified interface.  Note that this
1612 * calls the output routine of the loopback "driver", but with an interface
1613 * pointer that might NOT be a loopback interface -- evil, but easier than
1614 * replicating that code here.
1615 */
1616static void
1617ip_mloopback(ifp, m, dst, hlen)
1618	struct ifnet *ifp;
1619	register struct mbuf *m;
1620	register struct sockaddr_in *dst;
1621	int hlen;
1622{
1623	register struct ip *ip;
1624	struct mbuf *copym;
1625
1626	copym = m_copy(m, 0, M_COPYALL);
1627	if (copym != NULL && (copym->m_flags & M_EXT || copym->m_len < hlen))
1628		copym = m_pullup(copym, hlen);
1629	if (copym != NULL) {
1630		/* If needed, compute the checksum and mark it as valid. */
1631		if (copym->m_pkthdr.csum_flags & CSUM_DELAY_DATA) {
1632			in_delayed_cksum(copym);
1633			copym->m_pkthdr.csum_flags &= ~CSUM_DELAY_DATA;
1634			copym->m_pkthdr.csum_flags |=
1635			    CSUM_DATA_VALID | CSUM_PSEUDO_HDR;
1636			copym->m_pkthdr.csum_data = 0xffff;
1637		}
1638		/*
1639		 * We don't bother to fragment if the IP length is greater
1640		 * than the interface's MTU.  Can this possibly matter?
1641		 */
1642		ip = mtod(copym, struct ip *);
1643		ip->ip_len = htons(ip->ip_len);
1644		ip->ip_off = htons(ip->ip_off);
1645		ip->ip_sum = 0;
1646		ip->ip_sum = in_cksum(copym, hlen);
1647		/*
1648		 * NB:
1649		 * It's not clear whether there are any lingering
1650		 * reentrancy problems in other areas which might
1651		 * be exposed by using ip_input directly (in
1652		 * particular, everything which modifies the packet
1653		 * in-place).  Yet another option is using the
1654		 * protosw directly to deliver the looped back
1655		 * packet.  For the moment, we'll err on the side
1656		 * of safety by using if_simloop().
1657		 */
1658#if 1 /* XXX */
1659		if (dst->sin_family != AF_INET) {
1660			printf("ip_mloopback: bad address family %d\n",
1661						dst->sin_family);
1662			dst->sin_family = AF_INET;
1663		}
1664#endif
1665
1666#ifdef notdef
1667		copym->m_pkthdr.rcvif = ifp;
1668		ip_input(copym);
1669#else
1670		if_simloop(ifp, copym, dst->sin_family, 0);
1671#endif
1672	}
1673}
1674