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