ip_output.c revision 125875
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 * 3. All advertising materials mentioning features or use of this software
14 *    must display the following acknowledgement:
15 *	This product includes software developed by the University of
16 *	California, Berkeley and its contributors.
17 * 4. Neither the name of the University nor the names of its contributors
18 *    may be used to endorse or promote products derived from this software
19 *    without specific prior written permission.
20 *
21 * THIS SOFTWARE IS PROVIDED BY THE REGENTS AND CONTRIBUTORS ``AS IS'' AND
22 * ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
23 * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE
24 * ARE DISCLAIMED.  IN NO EVENT SHALL THE REGENTS OR CONTRIBUTORS BE LIABLE
25 * FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL
26 * DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS
27 * OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION)
28 * HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT
29 * LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY
30 * OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF
31 * SUCH DAMAGE.
32 *
33 *	@(#)ip_output.c	8.3 (Berkeley) 1/21/94
34 * $FreeBSD: head/sys/netinet/ip_output.c 125875 2004-02-16 17:05:06Z ume $
35 */
36
37#include "opt_ipfw.h"
38#include "opt_ipdn.h"
39#include "opt_ipdivert.h"
40#include "opt_ipfilter.h"
41#include "opt_ipsec.h"
42#include "opt_mac.h"
43#include "opt_pfil_hooks.h"
44#include "opt_random_ip_id.h"
45#include "opt_mbuf_stress_test.h"
46
47#include <sys/param.h>
48#include <sys/systm.h>
49#include <sys/kernel.h>
50#include <sys/mac.h>
51#include <sys/malloc.h>
52#include <sys/mbuf.h>
53#include <sys/protosw.h>
54#include <sys/socket.h>
55#include <sys/socketvar.h>
56#include <sys/sysctl.h>
57
58#include <net/if.h>
59#include <net/route.h>
60
61#include <netinet/in.h>
62#include <netinet/in_systm.h>
63#include <netinet/ip.h>
64#include <netinet/in_pcb.h>
65#include <netinet/in_var.h>
66#include <netinet/ip_var.h>
67
68#ifdef PFIL_HOOKS
69#include <net/pfil.h>
70#endif
71
72#include <machine/in_cksum.h>
73
74static MALLOC_DEFINE(M_IPMOPTS, "ip_moptions", "internet multicast options");
75
76#ifdef IPSEC
77#include <netinet6/ipsec.h>
78#include <netkey/key.h>
79#ifdef IPSEC_DEBUG
80#include <netkey/key_debug.h>
81#else
82#define	KEYDEBUG(lev,arg)
83#endif
84#endif /*IPSEC*/
85
86#ifdef FAST_IPSEC
87#include <netipsec/ipsec.h>
88#include <netipsec/xform.h>
89#include <netipsec/key.h>
90#endif /*FAST_IPSEC*/
91
92#include <netinet/ip_fw.h>
93#include <netinet/ip_divert.h>
94#include <netinet/ip_dummynet.h>
95
96#define print_ip(x, a, y)	 printf("%s %d.%d.%d.%d%s",\
97				x, (ntohl(a.s_addr)>>24)&0xFF,\
98				  (ntohl(a.s_addr)>>16)&0xFF,\
99				  (ntohl(a.s_addr)>>8)&0xFF,\
100				  (ntohl(a.s_addr))&0xFF, y);
101
102u_short ip_id;
103
104#ifdef MBUF_STRESS_TEST
105int mbuf_frag_size = 0;
106SYSCTL_INT(_net_inet_ip, OID_AUTO, mbuf_frag_size, CTLFLAG_RW,
107	&mbuf_frag_size, 0, "Fragment outgoing mbufs to this size");
108#endif
109
110static struct mbuf *ip_insertoptions(struct mbuf *, struct mbuf *, int *);
111static struct ifnet *ip_multicast_if(struct in_addr *, int *);
112static void	ip_mloopback
113	(struct ifnet *, struct mbuf *, struct sockaddr_in *, int);
114static int	ip_getmoptions
115	(struct sockopt *, struct ip_moptions *);
116static int	ip_pcbopts(int, struct mbuf **, struct mbuf *);
117static int	ip_setmoptions
118	(struct sockopt *, struct ip_moptions **);
119
120int	ip_optcopy(struct ip *, struct ip *);
121
122
123extern	struct protosw inetsw[];
124
125/*
126 * IP output.  The packet in mbuf chain m contains a skeletal IP
127 * header (with len, off, ttl, proto, tos, src, dst).
128 * The mbuf chain containing the packet will be freed.
129 * The mbuf opt, if present, will not be freed.
130 * In the IP forwarding case, the packet will arrive with options already
131 * inserted, so must have a NULL opt pointer.
132 */
133int
134ip_output(struct mbuf *m, struct mbuf *opt, struct route *ro,
135	int flags, struct ip_moptions *imo, struct inpcb *inp)
136{
137	struct ip *ip;
138	struct ifnet *ifp = NULL;	/* keep compiler happy */
139	int hlen = sizeof (struct ip);
140	int len, off, error = 0;
141	struct sockaddr_in *dst = NULL;	/* keep compiler happy */
142	struct in_ifaddr *ia = NULL;
143	int isbroadcast, sw_csum;
144	struct in_addr pkt_dst;
145	struct route iproute;
146	struct m_tag *dummytag;		/* dummynet packet tag */
147	struct m_tag *mtag;
148	struct mbuf *m0;		/* XXX */
149#ifdef IPSEC
150	struct secpolicy *sp = NULL;
151#endif
152#ifdef FAST_IPSEC
153	struct secpolicy *sp = NULL;
154	struct tdb_ident *tdbi;
155	int s;
156#endif /* FAST_IPSEC */
157	struct ip_fw_args args;
158	int src_was_INADDR_ANY = 0;	/* as the name says... */
159
160	args.eh = NULL;
161	args.rule = NULL;
162	args.next_hop = ip_claim_next_hop(m);
163
164	M_ASSERTPKTHDR(m);
165
166	if (ro == NULL) {
167		ro = &iproute;
168		bzero(ro, sizeof (*ro));
169	}
170
171	if (inp != NULL)
172		INP_LOCK_ASSERT(inp);
173
174	/*
175	 * When packet comes from dummynet restore state from
176	 * previous processing instead of the header.  Yech!
177	 *
178	 * XXX add conditional compilation?
179	 */
180	dummytag = m_tag_find(m, PACKET_TAG_DUMMYNET, NULL);
181	if (dummytag != NULL) {
182		struct dn_pkt_tag *dt = (struct dn_pkt_tag *)(dummytag+1);
183
184		/*
185		 * NB: the route in the tag is known to have a
186		 * reference that must be free'd, but doing this
187		 * before the storage is reclaimed is painful due
188		 * to some of the contorted code in this routine.
189		 * So instead unlink the tag from the mbuf so it
190		 * doesn't get reclaimed and do the cleanup explicitly
191		 * below.  We should be able to do this automatically
192		 * using a uma dtor method when m_tag's can be
193		 * allocated from zones.
194		 */
195		m_tag_unlink(m, dummytag);
196
197		args.rule = dt->rule;
198		ro = &dt->ro;
199		dst = dt->dn_dst;
200		ifp = dt->ifp;
201
202		ip = mtod(m, struct ip *);
203		hlen = ip->ip_hl << 2 ;
204		if (ro->ro_rt)
205			ia = ifatoia(ro->ro_rt->rt_ifa);
206		goto sendit;
207	}
208
209	if (opt) {
210		len = 0;
211		m = ip_insertoptions(m, opt, &len);
212		if (len != 0)
213			hlen = len;
214	}
215	ip = mtod(m, struct ip *);
216	pkt_dst = args.next_hop ? args.next_hop->sin_addr : ip->ip_dst;
217
218	/*
219	 * Fill in IP header.  If we are not allowing fragmentation,
220	 * then the ip_id field is meaningless, but we don't set it
221	 * to zero.  Doing so causes various problems when devices along
222	 * the path (routers, load balancers, firewalls, etc.) illegally
223	 * disable DF on our packet.  Note that a 16-bit counter
224	 * will wrap around in less than 10 seconds at 100 Mbit/s on a
225	 * medium with MTU 1500.  See Steven M. Bellovin, "A Technique
226	 * for Counting NATted Hosts", Proc. IMW'02, available at
227	 * <http://www.research.att.com/~smb/papers/fnat.pdf>.
228	 */
229	if ((flags & (IP_FORWARDING|IP_RAWOUTPUT)) == 0) {
230		ip->ip_v = IPVERSION;
231		ip->ip_hl = hlen >> 2;
232#ifdef RANDOM_IP_ID
233		ip->ip_id = ip_randomid();
234#else
235		ip->ip_id = htons(ip_id++);
236#endif
237		ipstat.ips_localout++;
238	} else {
239		hlen = ip->ip_hl << 2;
240	}
241
242	dst = (struct sockaddr_in *)&ro->ro_dst;
243	/*
244	 * If there is a cached route,
245	 * check that it is to the same destination
246	 * and is still up.  If not, free it and try again.
247	 * The address family should also be checked in case of sharing the
248	 * cache with IPv6.
249	 */
250	if (ro->ro_rt && ((ro->ro_rt->rt_flags & RTF_UP) == 0 ||
251			  dst->sin_family != AF_INET ||
252			  dst->sin_addr.s_addr != pkt_dst.s_addr)) {
253		RTFREE(ro->ro_rt);
254		ro->ro_rt = (struct rtentry *)0;
255	}
256	if (ro->ro_rt == 0) {
257		bzero(dst, sizeof(*dst));
258		dst->sin_family = AF_INET;
259		dst->sin_len = sizeof(*dst);
260		dst->sin_addr = pkt_dst;
261	}
262	/*
263	 * If routing to interface only,
264	 * short circuit routing lookup.
265	 */
266	if (flags & IP_ROUTETOIF) {
267		if ((ia = ifatoia(ifa_ifwithdstaddr(sintosa(dst)))) == 0 &&
268		    (ia = ifatoia(ifa_ifwithnet(sintosa(dst)))) == 0) {
269			ipstat.ips_noroute++;
270			error = ENETUNREACH;
271			goto bad;
272		}
273		ifp = ia->ia_ifp;
274		ip->ip_ttl = 1;
275		isbroadcast = in_broadcast(dst->sin_addr, ifp);
276	} else if (IN_MULTICAST(ntohl(ip->ip_dst.s_addr)) &&
277	    imo != NULL && imo->imo_multicast_ifp != NULL) {
278		/*
279		 * Bypass the normal routing lookup for multicast
280		 * packets if the interface is specified.
281		 */
282		ifp = imo->imo_multicast_ifp;
283		IFP_TO_IA(ifp, ia);
284		isbroadcast = 0;	/* fool gcc */
285	} else {
286		/*
287		 * We want to do any cloning requested by the link layer,
288		 * as this is probably required in all cases for correct
289		 * operation (as it is for ARP).
290		 */
291		if (ro->ro_rt == 0)
292			rtalloc(ro);
293		if (ro->ro_rt == 0) {
294			ipstat.ips_noroute++;
295			error = EHOSTUNREACH;
296			goto bad;
297		}
298		ia = ifatoia(ro->ro_rt->rt_ifa);
299		ifp = ro->ro_rt->rt_ifp;
300		ro->ro_rt->rt_rmx.rmx_pksent++;
301		if (ro->ro_rt->rt_flags & RTF_GATEWAY)
302			dst = (struct sockaddr_in *)ro->ro_rt->rt_gateway;
303		if (ro->ro_rt->rt_flags & RTF_HOST)
304			isbroadcast = (ro->ro_rt->rt_flags & RTF_BROADCAST);
305		else
306			isbroadcast = in_broadcast(dst->sin_addr, ifp);
307	}
308	if (IN_MULTICAST(ntohl(pkt_dst.s_addr))) {
309		struct in_multi *inm;
310
311		m->m_flags |= M_MCAST;
312		/*
313		 * IP destination address is multicast.  Make sure "dst"
314		 * still points to the address in "ro".  (It may have been
315		 * changed to point to a gateway address, above.)
316		 */
317		dst = (struct sockaddr_in *)&ro->ro_dst;
318		/*
319		 * See if the caller provided any multicast options
320		 */
321		if (imo != NULL) {
322			ip->ip_ttl = imo->imo_multicast_ttl;
323			if (imo->imo_multicast_vif != -1)
324				ip->ip_src.s_addr =
325				    ip_mcast_src ?
326				    ip_mcast_src(imo->imo_multicast_vif) :
327				    INADDR_ANY;
328		} else
329			ip->ip_ttl = IP_DEFAULT_MULTICAST_TTL;
330		/*
331		 * Confirm that the outgoing interface supports multicast.
332		 */
333		if ((imo == NULL) || (imo->imo_multicast_vif == -1)) {
334			if ((ifp->if_flags & IFF_MULTICAST) == 0) {
335				ipstat.ips_noroute++;
336				error = ENETUNREACH;
337				goto bad;
338			}
339		}
340		/*
341		 * If source address not specified yet, use address
342		 * of outgoing interface.
343		 */
344		if (ip->ip_src.s_addr == INADDR_ANY) {
345			/* Interface may have no addresses. */
346			if (ia != NULL)
347				ip->ip_src = IA_SIN(ia)->sin_addr;
348		}
349
350		if (ip_mrouter && (flags & IP_FORWARDING) == 0) {
351			/*
352			 * XXX
353			 * delayed checksums are not currently
354			 * compatible with IP multicast routing
355			 */
356			if (m->m_pkthdr.csum_flags & CSUM_DELAY_DATA) {
357				in_delayed_cksum(m);
358				m->m_pkthdr.csum_flags &=
359					~CSUM_DELAY_DATA;
360			}
361		}
362		IN_LOOKUP_MULTI(pkt_dst, ifp, inm);
363		if (inm != NULL &&
364		   (imo == NULL || imo->imo_multicast_loop)) {
365			/*
366			 * If we belong to the destination multicast group
367			 * on the outgoing interface, and the caller did not
368			 * forbid loopback, loop back a copy.
369			 */
370			ip_mloopback(ifp, m, dst, hlen);
371		}
372		else {
373			/*
374			 * If we are acting as a multicast router, perform
375			 * multicast forwarding as if the packet had just
376			 * arrived on the interface to which we are about
377			 * to send.  The multicast forwarding function
378			 * recursively calls this function, using the
379			 * IP_FORWARDING flag to prevent infinite recursion.
380			 *
381			 * Multicasts that are looped back by ip_mloopback(),
382			 * above, will be forwarded by the ip_input() routine,
383			 * if necessary.
384			 */
385			if (ip_mrouter && (flags & IP_FORWARDING) == 0) {
386				/*
387				 * If rsvp daemon is not running, do not
388				 * set ip_moptions. This ensures that the packet
389				 * is multicast and not just sent down one link
390				 * as prescribed by rsvpd.
391				 */
392				if (!rsvp_on)
393					imo = NULL;
394				if (ip_mforward &&
395				    ip_mforward(ip, ifp, m, imo) != 0) {
396					m_freem(m);
397					goto done;
398				}
399			}
400		}
401
402		/*
403		 * Multicasts with a time-to-live of zero may be looped-
404		 * back, above, but must not be transmitted on a network.
405		 * Also, multicasts addressed to the loopback interface
406		 * are not sent -- the above call to ip_mloopback() will
407		 * loop back a copy if this host actually belongs to the
408		 * destination group on the loopback interface.
409		 */
410		if (ip->ip_ttl == 0 || ifp->if_flags & IFF_LOOPBACK) {
411			m_freem(m);
412			goto done;
413		}
414
415		goto sendit;
416	}
417#ifndef notdef
418	/*
419	 * If the source address is not specified yet, use the address
420	 * of the outoing interface. In case, keep note we did that, so
421	 * if the the firewall changes the next-hop causing the output
422	 * interface to change, we can fix that.
423	 */
424	if (ip->ip_src.s_addr == INADDR_ANY) {
425		/* Interface may have no addresses. */
426		if (ia != NULL) {
427			ip->ip_src = IA_SIN(ia)->sin_addr;
428			src_was_INADDR_ANY = 1;
429		}
430	}
431#endif /* notdef */
432	/*
433	 * Verify that we have any chance at all of being able to queue
434	 *      the packet or packet fragments
435	 */
436	if ((ifp->if_snd.ifq_len + ip->ip_len / ifp->if_mtu + 1) >=
437		ifp->if_snd.ifq_maxlen) {
438			error = ENOBUFS;
439			ipstat.ips_odropped++;
440			goto bad;
441	}
442
443	/*
444	 * Look for broadcast address and
445	 * verify user is allowed to send
446	 * such a packet.
447	 */
448	if (isbroadcast) {
449		if ((ifp->if_flags & IFF_BROADCAST) == 0) {
450			error = EADDRNOTAVAIL;
451			goto bad;
452		}
453		if ((flags & IP_ALLOWBROADCAST) == 0) {
454			error = EACCES;
455			goto bad;
456		}
457		/* don't allow broadcast messages to be fragmented */
458		if (ip->ip_len > ifp->if_mtu) {
459			error = EMSGSIZE;
460			goto bad;
461		}
462		if (flags & IP_SENDONES)
463			ip->ip_dst.s_addr = INADDR_BROADCAST;
464		m->m_flags |= M_BCAST;
465	} else {
466		m->m_flags &= ~M_BCAST;
467	}
468
469sendit:
470#ifdef IPSEC
471	/* get SP for this packet */
472	if (inp == NULL)
473		sp = ipsec4_getpolicybyaddr(m, IPSEC_DIR_OUTBOUND,
474		    flags, &error);
475	else
476		sp = ipsec4_getpolicybypcb(m, IPSEC_DIR_OUTBOUND, inp, &error);
477
478	if (sp == NULL) {
479		ipsecstat.out_inval++;
480		goto bad;
481	}
482
483	error = 0;
484
485	/* check policy */
486	switch (sp->policy) {
487	case IPSEC_POLICY_DISCARD:
488		/*
489		 * This packet is just discarded.
490		 */
491		ipsecstat.out_polvio++;
492		goto bad;
493
494	case IPSEC_POLICY_BYPASS:
495	case IPSEC_POLICY_NONE:
496	case IPSEC_POLICY_TCP:
497		/* no need to do IPsec. */
498		goto skip_ipsec;
499
500	case IPSEC_POLICY_IPSEC:
501		if (sp->req == NULL) {
502			/* acquire a policy */
503			error = key_spdacquire(sp);
504			goto bad;
505		}
506		break;
507
508	case IPSEC_POLICY_ENTRUST:
509	default:
510		printf("ip_output: Invalid policy found. %d\n", sp->policy);
511	}
512    {
513	struct ipsec_output_state state;
514	bzero(&state, sizeof(state));
515	state.m = m;
516	if (flags & IP_ROUTETOIF) {
517		state.ro = &iproute;
518		bzero(&iproute, sizeof(iproute));
519	} else
520		state.ro = ro;
521	state.dst = (struct sockaddr *)dst;
522
523	ip->ip_sum = 0;
524
525	/*
526	 * XXX
527	 * delayed checksums are not currently compatible with IPsec
528	 */
529	if (m->m_pkthdr.csum_flags & CSUM_DELAY_DATA) {
530		in_delayed_cksum(m);
531		m->m_pkthdr.csum_flags &= ~CSUM_DELAY_DATA;
532	}
533
534	ip->ip_len = htons(ip->ip_len);
535	ip->ip_off = htons(ip->ip_off);
536
537	error = ipsec4_output(&state, sp, flags);
538
539	m = state.m;
540	if (flags & IP_ROUTETOIF) {
541		/*
542		 * if we have tunnel mode SA, we may need to ignore
543		 * IP_ROUTETOIF.
544		 */
545		if (state.ro != &iproute || state.ro->ro_rt != NULL) {
546			flags &= ~IP_ROUTETOIF;
547			ro = state.ro;
548		}
549	} else
550		ro = state.ro;
551	dst = (struct sockaddr_in *)state.dst;
552	if (error) {
553		/* mbuf is already reclaimed in ipsec4_output. */
554		m = NULL;
555		switch (error) {
556		case EHOSTUNREACH:
557		case ENETUNREACH:
558		case EMSGSIZE:
559		case ENOBUFS:
560		case ENOMEM:
561			break;
562		default:
563			printf("ip4_output (ipsec): error code %d\n", error);
564			/*fall through*/
565		case ENOENT:
566			/* don't show these error codes to the user */
567			error = 0;
568			break;
569		}
570		goto bad;
571	}
572
573	/* be sure to update variables that are affected by ipsec4_output() */
574	ip = mtod(m, struct ip *);
575	hlen = ip->ip_hl << 2;
576	if (ro->ro_rt == NULL) {
577		if ((flags & IP_ROUTETOIF) == 0) {
578			printf("ip_output: "
579				"can't update route after IPsec processing\n");
580			error = EHOSTUNREACH;	/*XXX*/
581			goto bad;
582		}
583	} else {
584		if (state.encap) {
585			ia = ifatoia(ro->ro_rt->rt_ifa);
586			ifp = ro->ro_rt->rt_ifp;
587		}
588	}
589    }
590
591	/* make it flipped, again. */
592	ip->ip_len = ntohs(ip->ip_len);
593	ip->ip_off = ntohs(ip->ip_off);
594skip_ipsec:
595#endif /*IPSEC*/
596#ifdef FAST_IPSEC
597	/*
598	 * Check the security policy (SP) for the packet and, if
599	 * required, do IPsec-related processing.  There are two
600	 * cases here; the first time a packet is sent through
601	 * it will be untagged and handled by ipsec4_checkpolicy.
602	 * If the packet is resubmitted to ip_output (e.g. after
603	 * AH, ESP, etc. processing), there will be a tag to bypass
604	 * the lookup and related policy checking.
605	 */
606	mtag = m_tag_find(m, PACKET_TAG_IPSEC_PENDING_TDB, NULL);
607	s = splnet();
608	if (mtag != NULL) {
609		tdbi = (struct tdb_ident *)(mtag + 1);
610		sp = ipsec_getpolicy(tdbi, IPSEC_DIR_OUTBOUND);
611		if (sp == NULL)
612			error = -EINVAL;	/* force silent drop */
613		m_tag_delete(m, mtag);
614	} else {
615		sp = ipsec4_checkpolicy(m, IPSEC_DIR_OUTBOUND, flags,
616					&error, inp);
617	}
618	/*
619	 * There are four return cases:
620	 *    sp != NULL	 	    apply IPsec policy
621	 *    sp == NULL, error == 0	    no IPsec handling needed
622	 *    sp == NULL, error == -EINVAL  discard packet w/o error
623	 *    sp == NULL, error != 0	    discard packet, report error
624	 */
625	if (sp != NULL) {
626		/* Loop detection, check if ipsec processing already done */
627		KASSERT(sp->req != NULL, ("ip_output: no ipsec request"));
628		for (mtag = m_tag_first(m); mtag != NULL;
629		     mtag = m_tag_next(m, mtag)) {
630			if (mtag->m_tag_cookie != MTAG_ABI_COMPAT)
631				continue;
632			if (mtag->m_tag_id != PACKET_TAG_IPSEC_OUT_DONE &&
633			    mtag->m_tag_id != PACKET_TAG_IPSEC_OUT_CRYPTO_NEEDED)
634				continue;
635			/*
636			 * Check if policy has an SA associated with it.
637			 * This can happen when an SP has yet to acquire
638			 * an SA; e.g. on first reference.  If it occurs,
639			 * then we let ipsec4_process_packet do its thing.
640			 */
641			if (sp->req->sav == NULL)
642				break;
643			tdbi = (struct tdb_ident *)(mtag + 1);
644			if (tdbi->spi == sp->req->sav->spi &&
645			    tdbi->proto == sp->req->sav->sah->saidx.proto &&
646			    bcmp(&tdbi->dst, &sp->req->sav->sah->saidx.dst,
647				 sizeof (union sockaddr_union)) == 0) {
648				/*
649				 * No IPsec processing is needed, free
650				 * reference to SP.
651				 *
652				 * NB: null pointer to avoid free at
653				 *     done: below.
654				 */
655				KEY_FREESP(&sp), sp = NULL;
656				splx(s);
657				goto spd_done;
658			}
659		}
660
661		/*
662		 * Do delayed checksums now because we send before
663		 * this is done in the normal processing path.
664		 */
665		if (m->m_pkthdr.csum_flags & CSUM_DELAY_DATA) {
666			in_delayed_cksum(m);
667			m->m_pkthdr.csum_flags &= ~CSUM_DELAY_DATA;
668		}
669
670		ip->ip_len = htons(ip->ip_len);
671		ip->ip_off = htons(ip->ip_off);
672
673		/* NB: callee frees mbuf */
674		error = ipsec4_process_packet(m, sp->req, flags, 0);
675		/*
676		 * Preserve KAME behaviour: ENOENT can be returned
677		 * when an SA acquire is in progress.  Don't propagate
678		 * this to user-level; it confuses applications.
679		 *
680		 * XXX this will go away when the SADB is redone.
681		 */
682		if (error == ENOENT)
683			error = 0;
684		splx(s);
685		goto done;
686	} else {
687		splx(s);
688
689		if (error != 0) {
690			/*
691			 * Hack: -EINVAL is used to signal that a packet
692			 * should be silently discarded.  This is typically
693			 * because we asked key management for an SA and
694			 * it was delayed (e.g. kicked up to IKE).
695			 */
696			if (error == -EINVAL)
697				error = 0;
698			goto bad;
699		} else {
700			/* No IPsec processing for this packet. */
701		}
702#ifdef notyet
703		/*
704		 * If deferred crypto processing is needed, check that
705		 * the interface supports it.
706		 */
707		mtag = m_tag_find(m, PACKET_TAG_IPSEC_OUT_CRYPTO_NEEDED, NULL);
708		if (mtag != NULL && (ifp->if_capenable & IFCAP_IPSEC) == 0) {
709			/* notify IPsec to do its own crypto */
710			ipsp_skipcrypto_unmark((struct tdb_ident *)(mtag + 1));
711			error = EHOSTUNREACH;
712			goto bad;
713		}
714#endif
715	}
716spd_done:
717#endif /* FAST_IPSEC */
718
719	/*
720	 * IpHack's section.
721	 * - Xlate: translate packet's addr/port (NAT).
722	 * - Firewall: deny/allow/etc.
723	 * - Wrap: fake packet's addr/port <unimpl.>
724	 * - Encapsulate: put it in another IP and send out. <unimp.>
725	 */
726#ifdef PFIL_HOOKS
727	/*
728	 * Run through list of hooks for output packets.
729	 */
730	error = pfil_run_hooks(&inet_pfil_hook, &m, ifp, PFIL_OUT);
731	if (error != 0 || m == NULL)
732		goto done;
733	ip = mtod(m, struct ip *);
734#endif /* PFIL_HOOKS */
735
736	/*
737	 * Check with the firewall...
738	 * but not if we are already being fwd'd from a firewall.
739	 */
740	if (fw_enable && IPFW_LOADED && !args.next_hop) {
741		struct sockaddr_in *old = dst;
742
743		args.m = m;
744		args.next_hop = dst;
745		args.oif = ifp;
746		off = ip_fw_chk_ptr(&args);
747		m = args.m;
748		dst = args.next_hop;
749
750                /*
751		 * On return we must do the following:
752		 * m == NULL	-> drop the pkt (old interface, deprecated)
753		 * (off & IP_FW_PORT_DENY_FLAG)	-> drop the pkt (new interface)
754		 * 1<=off<= 0xffff		-> DIVERT
755		 * (off & IP_FW_PORT_DYNT_FLAG)	-> send to a DUMMYNET pipe
756		 * (off & IP_FW_PORT_TEE_FLAG)	-> TEE the packet
757		 * dst != old			-> IPFIREWALL_FORWARD
758		 * off==0, dst==old		-> accept
759		 * If some of the above modules are not compiled in, then
760		 * we should't have to check the corresponding condition
761		 * (because the ipfw control socket should not accept
762		 * unsupported rules), but better play safe and drop
763		 * packets in case of doubt.
764		 */
765		if ( (off & IP_FW_PORT_DENY_FLAG) || m == NULL) {
766			if (m)
767				m_freem(m);
768			error = EACCES;
769			goto done;
770		}
771		ip = mtod(m, struct ip *);
772		if (off == 0 && dst == old)		/* common case */
773			goto pass;
774                if (DUMMYNET_LOADED && (off & IP_FW_PORT_DYNT_FLAG) != 0) {
775			/*
776			 * pass the pkt to dummynet. Need to include
777			 * pipe number, m, ifp, ro, dst because these are
778			 * not recomputed in the next pass.
779			 * All other parameters have been already used and
780			 * so they are not needed anymore.
781			 * XXX note: if the ifp or ro entry are deleted
782			 * while a pkt is in dummynet, we are in trouble!
783			 */
784			args.ro = ro;
785			args.dst = dst;
786			args.flags = flags;
787
788			error = ip_dn_io_ptr(m, off & 0xffff, DN_TO_IP_OUT,
789				&args);
790			goto done;
791		}
792#ifdef IPDIVERT
793		if (off != 0 && (off & IP_FW_PORT_DYNT_FLAG) == 0) {
794			struct mbuf *clone;
795
796			/* Clone packet if we're doing a 'tee' */
797			if ((off & IP_FW_PORT_TEE_FLAG) != 0)
798				clone = divert_clone(m);
799			else
800				clone = NULL;
801
802			/*
803			 * XXX
804			 * delayed checksums are not currently compatible
805			 * with divert sockets.
806			 */
807			if (m->m_pkthdr.csum_flags & CSUM_DELAY_DATA) {
808				in_delayed_cksum(m);
809				m->m_pkthdr.csum_flags &= ~CSUM_DELAY_DATA;
810			}
811
812			/* Restore packet header fields to original values */
813			ip->ip_len = htons(ip->ip_len);
814			ip->ip_off = htons(ip->ip_off);
815
816			/* Deliver packet to divert input routine */
817			divert_packet(m, 0);
818
819			/* If 'tee', continue with original packet */
820			if (clone != NULL) {
821				m = clone;
822				ip = mtod(m, struct ip *);
823				goto pass;
824			}
825			goto done;
826		}
827#endif
828
829		/* IPFIREWALL_FORWARD */
830		/*
831		 * Check dst to make sure it is directly reachable on the
832		 * interface we previously thought it was.
833		 * If it isn't (which may be likely in some situations) we have
834		 * to re-route it (ie, find a route for the next-hop and the
835		 * associated interface) and set them here. This is nested
836		 * forwarding which in most cases is undesirable, except where
837		 * such control is nigh impossible. So we do it here.
838		 * And I'm babbling.
839		 */
840		if (off == 0 && old != dst) { /* FORWARD, dst has changed */
841#if 0
842			/*
843			 * XXX To improve readability, this block should be
844			 * changed into a function call as below:
845			 */
846			error = ip_ipforward(&m, &dst, &ifp);
847			if (error)
848				goto bad;
849			if (m == NULL) /* ip_input consumed the mbuf */
850				goto done;
851#else
852			struct in_ifaddr *ia;
853
854			/*
855			 * XXX sro_fwd below is static, and a pointer
856			 * to it gets passed to routines downstream.
857			 * This could have surprisingly bad results in
858			 * practice, because its content is overwritten
859			 * by subsequent packets.
860			 */
861			/* There must be a better way to do this next line... */
862			static struct route sro_fwd;
863			struct route *ro_fwd = &sro_fwd;
864
865#if 0
866			print_ip("IPFIREWALL_FORWARD: New dst ip: ",
867			    dst->sin_addr, "\n");
868#endif
869
870			/*
871			 * We need to figure out if we have been forwarded
872			 * to a local socket. If so, then we should somehow
873			 * "loop back" to ip_input, and get directed to the
874			 * PCB as if we had received this packet. This is
875			 * because it may be dificult to identify the packets
876			 * you want to forward until they are being output
877			 * and have selected an interface. (e.g. locally
878			 * initiated packets) If we used the loopback inteface,
879			 * we would not be able to control what happens
880			 * as the packet runs through ip_input() as
881			 * it is done through an ISR.
882			 */
883			LIST_FOREACH(ia,
884			    INADDR_HASH(dst->sin_addr.s_addr), ia_hash) {
885				/*
886				 * If the addr to forward to is one
887				 * of ours, we pretend to
888				 * be the destination for this packet.
889				 */
890				if (IA_SIN(ia)->sin_addr.s_addr ==
891						 dst->sin_addr.s_addr)
892					break;
893			}
894			if (ia) {	/* tell ip_input "dont filter" */
895				mtag = m_tag_get(PACKET_TAG_IPFORWARD,
896						sizeof(struct sockaddr_in *),
897						M_NOWAIT);
898				if (mtag == NULL) {
899					/* XXX statistic */
900					error = ENOBUFS;	/* XXX */
901					goto bad;
902				}
903				*(struct sockaddr_in **)(mtag+1) =
904					args.next_hop;
905				m_tag_prepend(m, mtag);
906
907				if (m->m_pkthdr.rcvif == NULL)
908					m->m_pkthdr.rcvif = ifunit("lo0");
909				if (m->m_pkthdr.csum_flags & CSUM_DELAY_DATA) {
910					m->m_pkthdr.csum_flags |=
911					    CSUM_DATA_VALID | CSUM_PSEUDO_HDR;
912					m->m_pkthdr.csum_data = 0xffff;
913				}
914				m->m_pkthdr.csum_flags |=
915				    CSUM_IP_CHECKED | CSUM_IP_VALID;
916				ip->ip_len = htons(ip->ip_len);
917				ip->ip_off = htons(ip->ip_off);
918				/* XXX netisr_queue(NETISR_IP, m); */
919				ip_input(m);
920				goto done;
921			}
922			/*
923			 * Some of the logic for this was
924			 * nicked from above.
925			 */
926			bcopy(dst, &ro_fwd->ro_dst, sizeof(*dst));
927
928			ro_fwd->ro_rt = 0;
929			rtalloc_ign(ro_fwd, RTF_CLONING);
930
931			if (ro_fwd->ro_rt == 0) {
932				ipstat.ips_noroute++;
933				error = EHOSTUNREACH;
934				goto bad;
935			}
936
937			ia = ifatoia(ro_fwd->ro_rt->rt_ifa);
938			ifp = ro_fwd->ro_rt->rt_ifp;
939			ro_fwd->ro_rt->rt_rmx.rmx_pksent++;
940			if (ro_fwd->ro_rt->rt_flags & RTF_GATEWAY)
941				dst = (struct sockaddr_in *)
942					ro_fwd->ro_rt->rt_gateway;
943			if (ro_fwd->ro_rt->rt_flags & RTF_HOST)
944				isbroadcast =
945				    (ro_fwd->ro_rt->rt_flags & RTF_BROADCAST);
946			else
947				isbroadcast = in_broadcast(dst->sin_addr, ifp);
948			if (ro->ro_rt)
949				RTFREE(ro->ro_rt);
950			ro->ro_rt = ro_fwd->ro_rt;
951			dst = (struct sockaddr_in *)&ro_fwd->ro_dst;
952
953#endif	/* ... block to be put into a function */
954			/*
955			 * If we added a default src ip earlier,
956			 * which would have been gotten from the-then
957			 * interface, do it again, from the new one.
958			 */
959			if (src_was_INADDR_ANY)
960				ip->ip_src = IA_SIN(ia)->sin_addr;
961			goto pass ;
962		}
963
964                /*
965                 * if we get here, none of the above matches, and
966                 * we have to drop the pkt
967                 */
968		m_freem(m);
969                error = EACCES; /* not sure this is the right error msg */
970                goto done;
971	}
972
973pass:
974	/* 127/8 must not appear on wire - RFC1122. */
975	if ((ntohl(ip->ip_dst.s_addr) >> IN_CLASSA_NSHIFT) == IN_LOOPBACKNET ||
976	    (ntohl(ip->ip_src.s_addr) >> IN_CLASSA_NSHIFT) == IN_LOOPBACKNET) {
977		if ((ifp->if_flags & IFF_LOOPBACK) == 0) {
978			ipstat.ips_badaddr++;
979			error = EADDRNOTAVAIL;
980			goto bad;
981		}
982	}
983
984	m->m_pkthdr.csum_flags |= CSUM_IP;
985	sw_csum = m->m_pkthdr.csum_flags & ~ifp->if_hwassist;
986	if (sw_csum & CSUM_DELAY_DATA) {
987		in_delayed_cksum(m);
988		sw_csum &= ~CSUM_DELAY_DATA;
989	}
990	m->m_pkthdr.csum_flags &= ifp->if_hwassist;
991
992	/*
993	 * If small enough for interface, or the interface will take
994	 * care of the fragmentation for us, can just send directly.
995	 */
996	if (ip->ip_len <= ifp->if_mtu || (ifp->if_hwassist & CSUM_FRAGMENT &&
997	    ((ip->ip_off & IP_DF) == 0))) {
998		ip->ip_len = htons(ip->ip_len);
999		ip->ip_off = htons(ip->ip_off);
1000		ip->ip_sum = 0;
1001		if (sw_csum & CSUM_DELAY_IP)
1002			ip->ip_sum = in_cksum(m, hlen);
1003
1004		/* Record statistics for this interface address. */
1005		if (!(flags & IP_FORWARDING) && ia) {
1006			ia->ia_ifa.if_opackets++;
1007			ia->ia_ifa.if_obytes += m->m_pkthdr.len;
1008		}
1009
1010#ifdef IPSEC
1011		/* clean ipsec history once it goes out of the node */
1012		ipsec_delaux(m);
1013#endif
1014
1015#ifdef MBUF_STRESS_TEST
1016		if (mbuf_frag_size && m->m_pkthdr.len > mbuf_frag_size)
1017			m = m_fragment(m, M_DONTWAIT, mbuf_frag_size);
1018#endif
1019		error = (*ifp->if_output)(ifp, m,
1020				(struct sockaddr *)dst, ro->ro_rt);
1021		goto done;
1022	}
1023
1024	if (ip->ip_off & IP_DF) {
1025		error = EMSGSIZE;
1026		/*
1027		 * This case can happen if the user changed the MTU
1028		 * of an interface after enabling IP on it.  Because
1029		 * most netifs don't keep track of routes pointing to
1030		 * them, there is no way for one to update all its
1031		 * routes when the MTU is changed.
1032		 */
1033		if ((ro->ro_rt->rt_flags & (RTF_UP | RTF_HOST)) &&
1034		    (ro->ro_rt->rt_rmx.rmx_mtu > ifp->if_mtu)) {
1035			ro->ro_rt->rt_rmx.rmx_mtu = ifp->if_mtu;
1036		}
1037		ipstat.ips_cantfrag++;
1038		goto bad;
1039	}
1040
1041	/*
1042	 * Too large for interface; fragment if possible. If successful,
1043	 * on return, m will point to a list of packets to be sent.
1044	 */
1045	error = ip_fragment(ip, &m, ifp->if_mtu, ifp->if_hwassist, sw_csum);
1046	if (error)
1047		goto bad;
1048	for (; m; m = m0) {
1049		m0 = m->m_nextpkt;
1050		m->m_nextpkt = 0;
1051#ifdef IPSEC
1052		/* clean ipsec history once it goes out of the node */
1053		ipsec_delaux(m);
1054#endif
1055		if (error == 0) {
1056			/* Record statistics for this interface address. */
1057			if (ia != NULL) {
1058				ia->ia_ifa.if_opackets++;
1059				ia->ia_ifa.if_obytes += m->m_pkthdr.len;
1060			}
1061
1062			error = (*ifp->if_output)(ifp, m,
1063			    (struct sockaddr *)dst, ro->ro_rt);
1064		} else
1065			m_freem(m);
1066	}
1067
1068	if (error == 0)
1069		ipstat.ips_fragmented++;
1070
1071done:
1072	if (ro == &iproute && ro->ro_rt) {
1073		RTFREE(ro->ro_rt);
1074		ro->ro_rt = NULL;
1075	}
1076	if (dummytag) {
1077		struct dn_pkt_tag *dt = (struct dn_pkt_tag *)(dummytag+1);
1078		if (dt->ro.ro_rt)
1079			RTFREE(dt->ro.ro_rt);
1080		m_tag_free(dummytag);
1081	}
1082#ifdef IPSEC
1083	if (sp != NULL) {
1084		KEYDEBUG(KEYDEBUG_IPSEC_STAMP,
1085			printf("DP ip_output call free SP:%p\n", sp));
1086		key_freesp(sp);
1087	}
1088#endif
1089#ifdef FAST_IPSEC
1090	if (sp != NULL)
1091		KEY_FREESP(&sp);
1092#endif
1093	return (error);
1094bad:
1095	m_freem(m);
1096	goto done;
1097}
1098
1099/*
1100 * Create a chain of fragments which fit the given mtu. m_frag points to the
1101 * mbuf to be fragmented; on return it points to the chain with the fragments.
1102 * Return 0 if no error. If error, m_frag may contain a partially built
1103 * chain of fragments that should be freed by the caller.
1104 *
1105 * if_hwassist_flags is the hw offload capabilities (see if_data.ifi_hwassist)
1106 * sw_csum contains the delayed checksums flags (e.g., CSUM_DELAY_IP).
1107 */
1108int
1109ip_fragment(struct ip *ip, struct mbuf **m_frag, int mtu,
1110	    u_long if_hwassist_flags, int sw_csum)
1111{
1112	int error = 0;
1113	int hlen = ip->ip_hl << 2;
1114	int len = (mtu - hlen) & ~7;	/* size of payload in each fragment */
1115	int off;
1116	struct mbuf *m0 = *m_frag;	/* the original packet		*/
1117	int firstlen;
1118	struct mbuf **mnext;
1119	int nfrags;
1120
1121	if (ip->ip_off & IP_DF) {	/* Fragmentation not allowed */
1122		ipstat.ips_cantfrag++;
1123		return EMSGSIZE;
1124	}
1125
1126	/*
1127	 * Must be able to put at least 8 bytes per fragment.
1128	 */
1129	if (len < 8)
1130		return EMSGSIZE;
1131
1132	/*
1133	 * If the interface will not calculate checksums on
1134	 * fragmented packets, then do it here.
1135	 */
1136	if (m0->m_pkthdr.csum_flags & CSUM_DELAY_DATA &&
1137	    (if_hwassist_flags & CSUM_IP_FRAGS) == 0) {
1138		in_delayed_cksum(m0);
1139		m0->m_pkthdr.csum_flags &= ~CSUM_DELAY_DATA;
1140	}
1141
1142	if (len > PAGE_SIZE) {
1143		/*
1144		 * Fragment large datagrams such that each segment
1145		 * contains a multiple of PAGE_SIZE amount of data,
1146		 * plus headers. This enables a receiver to perform
1147		 * page-flipping zero-copy optimizations.
1148		 *
1149		 * XXX When does this help given that sender and receiver
1150		 * could have different page sizes, and also mtu could
1151		 * be less than the receiver's page size ?
1152		 */
1153		int newlen;
1154		struct mbuf *m;
1155
1156		for (m = m0, off = 0; m && (off+m->m_len) <= mtu; m = m->m_next)
1157			off += m->m_len;
1158
1159		/*
1160		 * firstlen (off - hlen) must be aligned on an
1161		 * 8-byte boundary
1162		 */
1163		if (off < hlen)
1164			goto smart_frag_failure;
1165		off = ((off - hlen) & ~7) + hlen;
1166		newlen = (~PAGE_MASK) & mtu;
1167		if ((newlen + sizeof (struct ip)) > mtu) {
1168			/* we failed, go back the default */
1169smart_frag_failure:
1170			newlen = len;
1171			off = hlen + len;
1172		}
1173		len = newlen;
1174
1175	} else {
1176		off = hlen + len;
1177	}
1178
1179	firstlen = off - hlen;
1180	mnext = &m0->m_nextpkt;		/* pointer to next packet */
1181
1182	/*
1183	 * Loop through length of segment after first fragment,
1184	 * make new header and copy data of each part and link onto chain.
1185	 * Here, m0 is the original packet, m is the fragment being created.
1186	 * The fragments are linked off the m_nextpkt of the original
1187	 * packet, which after processing serves as the first fragment.
1188	 */
1189	for (nfrags = 1; off < ip->ip_len; off += len, nfrags++) {
1190		struct ip *mhip;	/* ip header on the fragment */
1191		struct mbuf *m;
1192		int mhlen = sizeof (struct ip);
1193
1194		MGETHDR(m, M_DONTWAIT, MT_HEADER);
1195		if (m == 0) {
1196			error = ENOBUFS;
1197			ipstat.ips_odropped++;
1198			goto done;
1199		}
1200		m->m_flags |= (m0->m_flags & M_MCAST) | M_FRAG;
1201		/*
1202		 * In the first mbuf, leave room for the link header, then
1203		 * copy the original IP header including options. The payload
1204		 * goes into an additional mbuf chain returned by m_copy().
1205		 */
1206		m->m_data += max_linkhdr;
1207		mhip = mtod(m, struct ip *);
1208		*mhip = *ip;
1209		if (hlen > sizeof (struct ip)) {
1210			mhlen = ip_optcopy(ip, mhip) + sizeof (struct ip);
1211			mhip->ip_v = IPVERSION;
1212			mhip->ip_hl = mhlen >> 2;
1213		}
1214		m->m_len = mhlen;
1215		/* XXX do we need to add ip->ip_off below ? */
1216		mhip->ip_off = ((off - hlen) >> 3) + ip->ip_off;
1217		if (off + len >= ip->ip_len) {	/* last fragment */
1218			len = ip->ip_len - off;
1219			m->m_flags |= M_LASTFRAG;
1220		} else
1221			mhip->ip_off |= IP_MF;
1222		mhip->ip_len = htons((u_short)(len + mhlen));
1223		m->m_next = m_copy(m0, off, len);
1224		if (m->m_next == 0) {		/* copy failed */
1225			m_free(m);
1226			error = ENOBUFS;	/* ??? */
1227			ipstat.ips_odropped++;
1228			goto done;
1229		}
1230		m->m_pkthdr.len = mhlen + len;
1231		m->m_pkthdr.rcvif = (struct ifnet *)0;
1232#ifdef MAC
1233		mac_create_fragment(m0, m);
1234#endif
1235		m->m_pkthdr.csum_flags = m0->m_pkthdr.csum_flags;
1236		mhip->ip_off = htons(mhip->ip_off);
1237		mhip->ip_sum = 0;
1238		if (sw_csum & CSUM_DELAY_IP)
1239			mhip->ip_sum = in_cksum(m, mhlen);
1240		*mnext = m;
1241		mnext = &m->m_nextpkt;
1242	}
1243	ipstat.ips_ofragments += nfrags;
1244
1245	/* set first marker for fragment chain */
1246	m0->m_flags |= M_FIRSTFRAG | M_FRAG;
1247	m0->m_pkthdr.csum_data = nfrags;
1248
1249	/*
1250	 * Update first fragment by trimming what's been copied out
1251	 * and updating header.
1252	 */
1253	m_adj(m0, hlen + firstlen - ip->ip_len);
1254	m0->m_pkthdr.len = hlen + firstlen;
1255	ip->ip_len = htons((u_short)m0->m_pkthdr.len);
1256	ip->ip_off |= IP_MF;
1257	ip->ip_off = htons(ip->ip_off);
1258	ip->ip_sum = 0;
1259	if (sw_csum & CSUM_DELAY_IP)
1260		ip->ip_sum = in_cksum(m0, hlen);
1261
1262done:
1263	*m_frag = m0;
1264	return error;
1265}
1266
1267void
1268in_delayed_cksum(struct mbuf *m)
1269{
1270	struct ip *ip;
1271	u_short csum, offset;
1272
1273	ip = mtod(m, struct ip *);
1274	offset = ip->ip_hl << 2 ;
1275	csum = in_cksum_skip(m, ip->ip_len, offset);
1276	if (m->m_pkthdr.csum_flags & CSUM_UDP && csum == 0)
1277		csum = 0xffff;
1278	offset += m->m_pkthdr.csum_data;	/* checksum offset */
1279
1280	if (offset + sizeof(u_short) > m->m_len) {
1281		printf("delayed m_pullup, m->len: %d  off: %d  p: %d\n",
1282		    m->m_len, offset, ip->ip_p);
1283		/*
1284		 * XXX
1285		 * this shouldn't happen, but if it does, the
1286		 * correct behavior may be to insert the checksum
1287		 * in the existing chain instead of rearranging it.
1288		 */
1289		m = m_pullup(m, offset + sizeof(u_short));
1290	}
1291	*(u_short *)(m->m_data + offset) = csum;
1292}
1293
1294/*
1295 * Insert IP options into preformed packet.
1296 * Adjust IP destination as required for IP source routing,
1297 * as indicated by a non-zero in_addr at the start of the options.
1298 *
1299 * XXX This routine assumes that the packet has no options in place.
1300 */
1301static struct mbuf *
1302ip_insertoptions(m, opt, phlen)
1303	register struct mbuf *m;
1304	struct mbuf *opt;
1305	int *phlen;
1306{
1307	register struct ipoption *p = mtod(opt, struct ipoption *);
1308	struct mbuf *n;
1309	register struct ip *ip = mtod(m, struct ip *);
1310	unsigned optlen;
1311
1312	optlen = opt->m_len - sizeof(p->ipopt_dst);
1313	if (optlen + ip->ip_len > IP_MAXPACKET) {
1314		*phlen = 0;
1315		return (m);		/* XXX should fail */
1316	}
1317	if (p->ipopt_dst.s_addr)
1318		ip->ip_dst = p->ipopt_dst;
1319	if (m->m_flags & M_EXT || m->m_data - optlen < m->m_pktdat) {
1320		MGETHDR(n, M_DONTWAIT, MT_HEADER);
1321		if (n == 0) {
1322			*phlen = 0;
1323			return (m);
1324		}
1325		n->m_pkthdr.rcvif = (struct ifnet *)0;
1326#ifdef MAC
1327		mac_create_mbuf_from_mbuf(m, n);
1328#endif
1329		n->m_pkthdr.len = m->m_pkthdr.len + optlen;
1330		m->m_len -= sizeof(struct ip);
1331		m->m_data += sizeof(struct ip);
1332		n->m_next = m;
1333		m = n;
1334		m->m_len = optlen + sizeof(struct ip);
1335		m->m_data += max_linkhdr;
1336		bcopy(ip, mtod(m, void *), sizeof(struct ip));
1337	} else {
1338		m->m_data -= optlen;
1339		m->m_len += optlen;
1340		m->m_pkthdr.len += optlen;
1341		bcopy(ip, mtod(m, void *), sizeof(struct ip));
1342	}
1343	ip = mtod(m, struct ip *);
1344	bcopy(p->ipopt_list, ip + 1, optlen);
1345	*phlen = sizeof(struct ip) + optlen;
1346	ip->ip_v = IPVERSION;
1347	ip->ip_hl = *phlen >> 2;
1348	ip->ip_len += optlen;
1349	return (m);
1350}
1351
1352/*
1353 * Copy options from ip to jp,
1354 * omitting those not copied during fragmentation.
1355 */
1356int
1357ip_optcopy(ip, jp)
1358	struct ip *ip, *jp;
1359{
1360	register u_char *cp, *dp;
1361	int opt, optlen, cnt;
1362
1363	cp = (u_char *)(ip + 1);
1364	dp = (u_char *)(jp + 1);
1365	cnt = (ip->ip_hl << 2) - sizeof (struct ip);
1366	for (; cnt > 0; cnt -= optlen, cp += optlen) {
1367		opt = cp[0];
1368		if (opt == IPOPT_EOL)
1369			break;
1370		if (opt == IPOPT_NOP) {
1371			/* Preserve for IP mcast tunnel's LSRR alignment. */
1372			*dp++ = IPOPT_NOP;
1373			optlen = 1;
1374			continue;
1375		}
1376
1377		KASSERT(cnt >= IPOPT_OLEN + sizeof(*cp),
1378		    ("ip_optcopy: malformed ipv4 option"));
1379		optlen = cp[IPOPT_OLEN];
1380		KASSERT(optlen >= IPOPT_OLEN + sizeof(*cp) && optlen <= cnt,
1381		    ("ip_optcopy: malformed ipv4 option"));
1382
1383		/* bogus lengths should have been caught by ip_dooptions */
1384		if (optlen > cnt)
1385			optlen = cnt;
1386		if (IPOPT_COPIED(opt)) {
1387			bcopy(cp, dp, optlen);
1388			dp += optlen;
1389		}
1390	}
1391	for (optlen = dp - (u_char *)(jp+1); optlen & 0x3; optlen++)
1392		*dp++ = IPOPT_EOL;
1393	return (optlen);
1394}
1395
1396/*
1397 * IP socket option processing.
1398 */
1399int
1400ip_ctloutput(so, sopt)
1401	struct socket *so;
1402	struct sockopt *sopt;
1403{
1404	struct	inpcb *inp = sotoinpcb(so);
1405	int	error, optval;
1406
1407	error = optval = 0;
1408	if (sopt->sopt_level != IPPROTO_IP) {
1409		return (EINVAL);
1410	}
1411
1412	switch (sopt->sopt_dir) {
1413	case SOPT_SET:
1414		switch (sopt->sopt_name) {
1415		case IP_OPTIONS:
1416#ifdef notyet
1417		case IP_RETOPTS:
1418#endif
1419		{
1420			struct mbuf *m;
1421			if (sopt->sopt_valsize > MLEN) {
1422				error = EMSGSIZE;
1423				break;
1424			}
1425			MGET(m, sopt->sopt_td ? M_TRYWAIT : M_DONTWAIT, MT_HEADER);
1426			if (m == 0) {
1427				error = ENOBUFS;
1428				break;
1429			}
1430			m->m_len = sopt->sopt_valsize;
1431			error = sooptcopyin(sopt, mtod(m, char *), m->m_len,
1432					    m->m_len);
1433
1434			return (ip_pcbopts(sopt->sopt_name, &inp->inp_options,
1435					   m));
1436		}
1437
1438		case IP_TOS:
1439		case IP_TTL:
1440		case IP_RECVOPTS:
1441		case IP_RECVRETOPTS:
1442		case IP_RECVDSTADDR:
1443		case IP_RECVTTL:
1444		case IP_RECVIF:
1445		case IP_FAITH:
1446		case IP_ONESBCAST:
1447			error = sooptcopyin(sopt, &optval, sizeof optval,
1448					    sizeof optval);
1449			if (error)
1450				break;
1451
1452			switch (sopt->sopt_name) {
1453			case IP_TOS:
1454				inp->inp_ip_tos = optval;
1455				break;
1456
1457			case IP_TTL:
1458				inp->inp_ip_ttl = optval;
1459				break;
1460#define	OPTSET(bit) \
1461	if (optval) \
1462		inp->inp_flags |= bit; \
1463	else \
1464		inp->inp_flags &= ~bit;
1465
1466			case IP_RECVOPTS:
1467				OPTSET(INP_RECVOPTS);
1468				break;
1469
1470			case IP_RECVRETOPTS:
1471				OPTSET(INP_RECVRETOPTS);
1472				break;
1473
1474			case IP_RECVDSTADDR:
1475				OPTSET(INP_RECVDSTADDR);
1476				break;
1477
1478			case IP_RECVTTL:
1479				OPTSET(INP_RECVTTL);
1480				break;
1481
1482			case IP_RECVIF:
1483				OPTSET(INP_RECVIF);
1484				break;
1485
1486			case IP_FAITH:
1487				OPTSET(INP_FAITH);
1488				break;
1489
1490			case IP_ONESBCAST:
1491				OPTSET(INP_ONESBCAST);
1492				break;
1493			}
1494			break;
1495#undef OPTSET
1496
1497		case IP_MULTICAST_IF:
1498		case IP_MULTICAST_VIF:
1499		case IP_MULTICAST_TTL:
1500		case IP_MULTICAST_LOOP:
1501		case IP_ADD_MEMBERSHIP:
1502		case IP_DROP_MEMBERSHIP:
1503			error = ip_setmoptions(sopt, &inp->inp_moptions);
1504			break;
1505
1506		case IP_PORTRANGE:
1507			error = sooptcopyin(sopt, &optval, sizeof optval,
1508					    sizeof optval);
1509			if (error)
1510				break;
1511
1512			switch (optval) {
1513			case IP_PORTRANGE_DEFAULT:
1514				inp->inp_flags &= ~(INP_LOWPORT);
1515				inp->inp_flags &= ~(INP_HIGHPORT);
1516				break;
1517
1518			case IP_PORTRANGE_HIGH:
1519				inp->inp_flags &= ~(INP_LOWPORT);
1520				inp->inp_flags |= INP_HIGHPORT;
1521				break;
1522
1523			case IP_PORTRANGE_LOW:
1524				inp->inp_flags &= ~(INP_HIGHPORT);
1525				inp->inp_flags |= INP_LOWPORT;
1526				break;
1527
1528			default:
1529				error = EINVAL;
1530				break;
1531			}
1532			break;
1533
1534#if defined(IPSEC) || defined(FAST_IPSEC)
1535		case IP_IPSEC_POLICY:
1536		{
1537			caddr_t req;
1538			size_t len = 0;
1539			int priv;
1540			struct mbuf *m;
1541			int optname;
1542
1543			if ((error = soopt_getm(sopt, &m)) != 0) /* XXX */
1544				break;
1545			if ((error = soopt_mcopyin(sopt, m)) != 0) /* XXX */
1546				break;
1547			priv = (sopt->sopt_td != NULL &&
1548				suser(sopt->sopt_td) != 0) ? 0 : 1;
1549			req = mtod(m, caddr_t);
1550			len = m->m_len;
1551			optname = sopt->sopt_name;
1552			error = ipsec4_set_policy(inp, optname, req, len, priv);
1553			m_freem(m);
1554			break;
1555		}
1556#endif /*IPSEC*/
1557
1558		default:
1559			error = ENOPROTOOPT;
1560			break;
1561		}
1562		break;
1563
1564	case SOPT_GET:
1565		switch (sopt->sopt_name) {
1566		case IP_OPTIONS:
1567		case IP_RETOPTS:
1568			if (inp->inp_options)
1569				error = sooptcopyout(sopt,
1570						     mtod(inp->inp_options,
1571							  char *),
1572						     inp->inp_options->m_len);
1573			else
1574				sopt->sopt_valsize = 0;
1575			break;
1576
1577		case IP_TOS:
1578		case IP_TTL:
1579		case IP_RECVOPTS:
1580		case IP_RECVRETOPTS:
1581		case IP_RECVDSTADDR:
1582		case IP_RECVTTL:
1583		case IP_RECVIF:
1584		case IP_PORTRANGE:
1585		case IP_FAITH:
1586		case IP_ONESBCAST:
1587			switch (sopt->sopt_name) {
1588
1589			case IP_TOS:
1590				optval = inp->inp_ip_tos;
1591				break;
1592
1593			case IP_TTL:
1594				optval = inp->inp_ip_ttl;
1595				break;
1596
1597#define	OPTBIT(bit)	(inp->inp_flags & bit ? 1 : 0)
1598
1599			case IP_RECVOPTS:
1600				optval = OPTBIT(INP_RECVOPTS);
1601				break;
1602
1603			case IP_RECVRETOPTS:
1604				optval = OPTBIT(INP_RECVRETOPTS);
1605				break;
1606
1607			case IP_RECVDSTADDR:
1608				optval = OPTBIT(INP_RECVDSTADDR);
1609				break;
1610
1611			case IP_RECVTTL:
1612				optval = OPTBIT(INP_RECVTTL);
1613				break;
1614
1615			case IP_RECVIF:
1616				optval = OPTBIT(INP_RECVIF);
1617				break;
1618
1619			case IP_PORTRANGE:
1620				if (inp->inp_flags & INP_HIGHPORT)
1621					optval = IP_PORTRANGE_HIGH;
1622				else if (inp->inp_flags & INP_LOWPORT)
1623					optval = IP_PORTRANGE_LOW;
1624				else
1625					optval = 0;
1626				break;
1627
1628			case IP_FAITH:
1629				optval = OPTBIT(INP_FAITH);
1630				break;
1631
1632			case IP_ONESBCAST:
1633				optval = OPTBIT(INP_ONESBCAST);
1634				break;
1635			}
1636			error = sooptcopyout(sopt, &optval, sizeof optval);
1637			break;
1638
1639		case IP_MULTICAST_IF:
1640		case IP_MULTICAST_VIF:
1641		case IP_MULTICAST_TTL:
1642		case IP_MULTICAST_LOOP:
1643		case IP_ADD_MEMBERSHIP:
1644		case IP_DROP_MEMBERSHIP:
1645			error = ip_getmoptions(sopt, inp->inp_moptions);
1646			break;
1647
1648#if defined(IPSEC) || defined(FAST_IPSEC)
1649		case IP_IPSEC_POLICY:
1650		{
1651			struct mbuf *m = NULL;
1652			caddr_t req = NULL;
1653			size_t len = 0;
1654
1655			if (m != 0) {
1656				req = mtod(m, caddr_t);
1657				len = m->m_len;
1658			}
1659			error = ipsec4_get_policy(sotoinpcb(so), req, len, &m);
1660			if (error == 0)
1661				error = soopt_mcopyout(sopt, m); /* XXX */
1662			if (error == 0)
1663				m_freem(m);
1664			break;
1665		}
1666#endif /*IPSEC*/
1667
1668		default:
1669			error = ENOPROTOOPT;
1670			break;
1671		}
1672		break;
1673	}
1674	return (error);
1675}
1676
1677/*
1678 * Set up IP options in pcb for insertion in output packets.
1679 * Store in mbuf with pointer in pcbopt, adding pseudo-option
1680 * with destination address if source routed.
1681 */
1682static int
1683ip_pcbopts(optname, pcbopt, m)
1684	int optname;
1685	struct mbuf **pcbopt;
1686	register struct mbuf *m;
1687{
1688	register int cnt, optlen;
1689	register u_char *cp;
1690	u_char opt;
1691
1692	/* turn off any old options */
1693	if (*pcbopt)
1694		(void)m_free(*pcbopt);
1695	*pcbopt = 0;
1696	if (m == (struct mbuf *)0 || m->m_len == 0) {
1697		/*
1698		 * Only turning off any previous options.
1699		 */
1700		if (m)
1701			(void)m_free(m);
1702		return (0);
1703	}
1704
1705	if (m->m_len % sizeof(int32_t))
1706		goto bad;
1707	/*
1708	 * IP first-hop destination address will be stored before
1709	 * actual options; move other options back
1710	 * and clear it when none present.
1711	 */
1712	if (m->m_data + m->m_len + sizeof(struct in_addr) >= &m->m_dat[MLEN])
1713		goto bad;
1714	cnt = m->m_len;
1715	m->m_len += sizeof(struct in_addr);
1716	cp = mtod(m, u_char *) + sizeof(struct in_addr);
1717	bcopy(mtod(m, void *), cp, (unsigned)cnt);
1718	bzero(mtod(m, void *), sizeof(struct in_addr));
1719
1720	for (; cnt > 0; cnt -= optlen, cp += optlen) {
1721		opt = cp[IPOPT_OPTVAL];
1722		if (opt == IPOPT_EOL)
1723			break;
1724		if (opt == IPOPT_NOP)
1725			optlen = 1;
1726		else {
1727			if (cnt < IPOPT_OLEN + sizeof(*cp))
1728				goto bad;
1729			optlen = cp[IPOPT_OLEN];
1730			if (optlen < IPOPT_OLEN + sizeof(*cp) || optlen > cnt)
1731				goto bad;
1732		}
1733		switch (opt) {
1734
1735		default:
1736			break;
1737
1738		case IPOPT_LSRR:
1739		case IPOPT_SSRR:
1740			/*
1741			 * user process specifies route as:
1742			 *	->A->B->C->D
1743			 * D must be our final destination (but we can't
1744			 * check that since we may not have connected yet).
1745			 * A is first hop destination, which doesn't appear in
1746			 * actual IP option, but is stored before the options.
1747			 */
1748			if (optlen < IPOPT_MINOFF - 1 + sizeof(struct in_addr))
1749				goto bad;
1750			m->m_len -= sizeof(struct in_addr);
1751			cnt -= sizeof(struct in_addr);
1752			optlen -= sizeof(struct in_addr);
1753			cp[IPOPT_OLEN] = optlen;
1754			/*
1755			 * Move first hop before start of options.
1756			 */
1757			bcopy((caddr_t)&cp[IPOPT_OFFSET+1], mtod(m, caddr_t),
1758			    sizeof(struct in_addr));
1759			/*
1760			 * Then copy rest of options back
1761			 * to close up the deleted entry.
1762			 */
1763			bcopy((&cp[IPOPT_OFFSET+1] + sizeof(struct in_addr)),
1764			    &cp[IPOPT_OFFSET+1],
1765			    (unsigned)cnt + sizeof(struct in_addr));
1766			break;
1767		}
1768	}
1769	if (m->m_len > MAX_IPOPTLEN + sizeof(struct in_addr))
1770		goto bad;
1771	*pcbopt = m;
1772	return (0);
1773
1774bad:
1775	(void)m_free(m);
1776	return (EINVAL);
1777}
1778
1779/*
1780 * XXX
1781 * The whole multicast option thing needs to be re-thought.
1782 * Several of these options are equally applicable to non-multicast
1783 * transmission, and one (IP_MULTICAST_TTL) totally duplicates a
1784 * standard option (IP_TTL).
1785 */
1786
1787/*
1788 * following RFC1724 section 3.3, 0.0.0.0/8 is interpreted as interface index.
1789 */
1790static struct ifnet *
1791ip_multicast_if(a, ifindexp)
1792	struct in_addr *a;
1793	int *ifindexp;
1794{
1795	int ifindex;
1796	struct ifnet *ifp;
1797
1798	if (ifindexp)
1799		*ifindexp = 0;
1800	if (ntohl(a->s_addr) >> 24 == 0) {
1801		ifindex = ntohl(a->s_addr) & 0xffffff;
1802		if (ifindex < 0 || if_index < ifindex)
1803			return NULL;
1804		ifp = ifnet_byindex(ifindex);
1805		if (ifindexp)
1806			*ifindexp = ifindex;
1807	} else {
1808		INADDR_TO_IFP(*a, ifp);
1809	}
1810	return ifp;
1811}
1812
1813/*
1814 * Set the IP multicast options in response to user setsockopt().
1815 */
1816static int
1817ip_setmoptions(sopt, imop)
1818	struct sockopt *sopt;
1819	struct ip_moptions **imop;
1820{
1821	int error = 0;
1822	int i;
1823	struct in_addr addr;
1824	struct ip_mreq mreq;
1825	struct ifnet *ifp;
1826	struct ip_moptions *imo = *imop;
1827	struct route ro;
1828	struct sockaddr_in *dst;
1829	int ifindex;
1830	int s;
1831
1832	if (imo == NULL) {
1833		/*
1834		 * No multicast option buffer attached to the pcb;
1835		 * allocate one and initialize to default values.
1836		 */
1837		imo = (struct ip_moptions*)malloc(sizeof(*imo), M_IPMOPTS,
1838		    M_WAITOK);
1839
1840		if (imo == NULL)
1841			return (ENOBUFS);
1842		*imop = imo;
1843		imo->imo_multicast_ifp = NULL;
1844		imo->imo_multicast_addr.s_addr = INADDR_ANY;
1845		imo->imo_multicast_vif = -1;
1846		imo->imo_multicast_ttl = IP_DEFAULT_MULTICAST_TTL;
1847		imo->imo_multicast_loop = IP_DEFAULT_MULTICAST_LOOP;
1848		imo->imo_num_memberships = 0;
1849	}
1850
1851	switch (sopt->sopt_name) {
1852	/* store an index number for the vif you wanna use in the send */
1853	case IP_MULTICAST_VIF:
1854		if (legal_vif_num == 0) {
1855			error = EOPNOTSUPP;
1856			break;
1857		}
1858		error = sooptcopyin(sopt, &i, sizeof i, sizeof i);
1859		if (error)
1860			break;
1861		if (!legal_vif_num(i) && (i != -1)) {
1862			error = EINVAL;
1863			break;
1864		}
1865		imo->imo_multicast_vif = i;
1866		break;
1867
1868	case IP_MULTICAST_IF:
1869		/*
1870		 * Select the interface for outgoing multicast packets.
1871		 */
1872		error = sooptcopyin(sopt, &addr, sizeof addr, sizeof addr);
1873		if (error)
1874			break;
1875		/*
1876		 * INADDR_ANY is used to remove a previous selection.
1877		 * When no interface is selected, a default one is
1878		 * chosen every time a multicast packet is sent.
1879		 */
1880		if (addr.s_addr == INADDR_ANY) {
1881			imo->imo_multicast_ifp = NULL;
1882			break;
1883		}
1884		/*
1885		 * The selected interface is identified by its local
1886		 * IP address.  Find the interface and confirm that
1887		 * it supports multicasting.
1888		 */
1889		s = splimp();
1890		ifp = ip_multicast_if(&addr, &ifindex);
1891		if (ifp == NULL || (ifp->if_flags & IFF_MULTICAST) == 0) {
1892			splx(s);
1893			error = EADDRNOTAVAIL;
1894			break;
1895		}
1896		imo->imo_multicast_ifp = ifp;
1897		if (ifindex)
1898			imo->imo_multicast_addr = addr;
1899		else
1900			imo->imo_multicast_addr.s_addr = INADDR_ANY;
1901		splx(s);
1902		break;
1903
1904	case IP_MULTICAST_TTL:
1905		/*
1906		 * Set the IP time-to-live for outgoing multicast packets.
1907		 * The original multicast API required a char argument,
1908		 * which is inconsistent with the rest of the socket API.
1909		 * We allow either a char or an int.
1910		 */
1911		if (sopt->sopt_valsize == 1) {
1912			u_char ttl;
1913			error = sooptcopyin(sopt, &ttl, 1, 1);
1914			if (error)
1915				break;
1916			imo->imo_multicast_ttl = ttl;
1917		} else {
1918			u_int ttl;
1919			error = sooptcopyin(sopt, &ttl, sizeof ttl,
1920					    sizeof ttl);
1921			if (error)
1922				break;
1923			if (ttl > 255)
1924				error = EINVAL;
1925			else
1926				imo->imo_multicast_ttl = ttl;
1927		}
1928		break;
1929
1930	case IP_MULTICAST_LOOP:
1931		/*
1932		 * Set the loopback flag for outgoing multicast packets.
1933		 * Must be zero or one.  The original multicast API required a
1934		 * char argument, which is inconsistent with the rest
1935		 * of the socket API.  We allow either a char or an int.
1936		 */
1937		if (sopt->sopt_valsize == 1) {
1938			u_char loop;
1939			error = sooptcopyin(sopt, &loop, 1, 1);
1940			if (error)
1941				break;
1942			imo->imo_multicast_loop = !!loop;
1943		} else {
1944			u_int loop;
1945			error = sooptcopyin(sopt, &loop, sizeof loop,
1946					    sizeof loop);
1947			if (error)
1948				break;
1949			imo->imo_multicast_loop = !!loop;
1950		}
1951		break;
1952
1953	case IP_ADD_MEMBERSHIP:
1954		/*
1955		 * Add a multicast group membership.
1956		 * Group must be a valid IP multicast address.
1957		 */
1958		error = sooptcopyin(sopt, &mreq, sizeof mreq, sizeof mreq);
1959		if (error)
1960			break;
1961
1962		if (!IN_MULTICAST(ntohl(mreq.imr_multiaddr.s_addr))) {
1963			error = EINVAL;
1964			break;
1965		}
1966		s = splimp();
1967		/*
1968		 * If no interface address was provided, use the interface of
1969		 * the route to the given multicast address.
1970		 */
1971		if (mreq.imr_interface.s_addr == INADDR_ANY) {
1972			bzero((caddr_t)&ro, sizeof(ro));
1973			dst = (struct sockaddr_in *)&ro.ro_dst;
1974			dst->sin_len = sizeof(*dst);
1975			dst->sin_family = AF_INET;
1976			dst->sin_addr = mreq.imr_multiaddr;
1977			rtalloc_ign(&ro, RTF_CLONING);
1978			if (ro.ro_rt == NULL) {
1979				error = EADDRNOTAVAIL;
1980				splx(s);
1981				break;
1982			}
1983			ifp = ro.ro_rt->rt_ifp;
1984			RTFREE(ro.ro_rt);
1985		}
1986		else {
1987			ifp = ip_multicast_if(&mreq.imr_interface, NULL);
1988		}
1989
1990		/*
1991		 * See if we found an interface, and confirm that it
1992		 * supports multicast.
1993		 */
1994		if (ifp == NULL || (ifp->if_flags & IFF_MULTICAST) == 0) {
1995			error = EADDRNOTAVAIL;
1996			splx(s);
1997			break;
1998		}
1999		/*
2000		 * See if the membership already exists or if all the
2001		 * membership slots are full.
2002		 */
2003		for (i = 0; i < imo->imo_num_memberships; ++i) {
2004			if (imo->imo_membership[i]->inm_ifp == ifp &&
2005			    imo->imo_membership[i]->inm_addr.s_addr
2006						== mreq.imr_multiaddr.s_addr)
2007				break;
2008		}
2009		if (i < imo->imo_num_memberships) {
2010			error = EADDRINUSE;
2011			splx(s);
2012			break;
2013		}
2014		if (i == IP_MAX_MEMBERSHIPS) {
2015			error = ETOOMANYREFS;
2016			splx(s);
2017			break;
2018		}
2019		/*
2020		 * Everything looks good; add a new record to the multicast
2021		 * address list for the given interface.
2022		 */
2023		if ((imo->imo_membership[i] =
2024		    in_addmulti(&mreq.imr_multiaddr, ifp)) == NULL) {
2025			error = ENOBUFS;
2026			splx(s);
2027			break;
2028		}
2029		++imo->imo_num_memberships;
2030		splx(s);
2031		break;
2032
2033	case IP_DROP_MEMBERSHIP:
2034		/*
2035		 * Drop a multicast group membership.
2036		 * Group must be a valid IP multicast address.
2037		 */
2038		error = sooptcopyin(sopt, &mreq, sizeof mreq, sizeof mreq);
2039		if (error)
2040			break;
2041
2042		if (!IN_MULTICAST(ntohl(mreq.imr_multiaddr.s_addr))) {
2043			error = EINVAL;
2044			break;
2045		}
2046
2047		s = splimp();
2048		/*
2049		 * If an interface address was specified, get a pointer
2050		 * to its ifnet structure.
2051		 */
2052		if (mreq.imr_interface.s_addr == INADDR_ANY)
2053			ifp = NULL;
2054		else {
2055			ifp = ip_multicast_if(&mreq.imr_interface, NULL);
2056			if (ifp == NULL) {
2057				error = EADDRNOTAVAIL;
2058				splx(s);
2059				break;
2060			}
2061		}
2062		/*
2063		 * Find the membership in the membership array.
2064		 */
2065		for (i = 0; i < imo->imo_num_memberships; ++i) {
2066			if ((ifp == NULL ||
2067			     imo->imo_membership[i]->inm_ifp == ifp) &&
2068			     imo->imo_membership[i]->inm_addr.s_addr ==
2069			     mreq.imr_multiaddr.s_addr)
2070				break;
2071		}
2072		if (i == imo->imo_num_memberships) {
2073			error = EADDRNOTAVAIL;
2074			splx(s);
2075			break;
2076		}
2077		/*
2078		 * Give up the multicast address record to which the
2079		 * membership points.
2080		 */
2081		in_delmulti(imo->imo_membership[i]);
2082		/*
2083		 * Remove the gap in the membership array.
2084		 */
2085		for (++i; i < imo->imo_num_memberships; ++i)
2086			imo->imo_membership[i-1] = imo->imo_membership[i];
2087		--imo->imo_num_memberships;
2088		splx(s);
2089		break;
2090
2091	default:
2092		error = EOPNOTSUPP;
2093		break;
2094	}
2095
2096	/*
2097	 * If all options have default values, no need to keep the mbuf.
2098	 */
2099	if (imo->imo_multicast_ifp == NULL &&
2100	    imo->imo_multicast_vif == -1 &&
2101	    imo->imo_multicast_ttl == IP_DEFAULT_MULTICAST_TTL &&
2102	    imo->imo_multicast_loop == IP_DEFAULT_MULTICAST_LOOP &&
2103	    imo->imo_num_memberships == 0) {
2104		free(*imop, M_IPMOPTS);
2105		*imop = NULL;
2106	}
2107
2108	return (error);
2109}
2110
2111/*
2112 * Return the IP multicast options in response to user getsockopt().
2113 */
2114static int
2115ip_getmoptions(sopt, imo)
2116	struct sockopt *sopt;
2117	register struct ip_moptions *imo;
2118{
2119	struct in_addr addr;
2120	struct in_ifaddr *ia;
2121	int error, optval;
2122	u_char coptval;
2123
2124	error = 0;
2125	switch (sopt->sopt_name) {
2126	case IP_MULTICAST_VIF:
2127		if (imo != NULL)
2128			optval = imo->imo_multicast_vif;
2129		else
2130			optval = -1;
2131		error = sooptcopyout(sopt, &optval, sizeof optval);
2132		break;
2133
2134	case IP_MULTICAST_IF:
2135		if (imo == NULL || imo->imo_multicast_ifp == NULL)
2136			addr.s_addr = INADDR_ANY;
2137		else if (imo->imo_multicast_addr.s_addr) {
2138			/* return the value user has set */
2139			addr = imo->imo_multicast_addr;
2140		} else {
2141			IFP_TO_IA(imo->imo_multicast_ifp, ia);
2142			addr.s_addr = (ia == NULL) ? INADDR_ANY
2143				: IA_SIN(ia)->sin_addr.s_addr;
2144		}
2145		error = sooptcopyout(sopt, &addr, sizeof addr);
2146		break;
2147
2148	case IP_MULTICAST_TTL:
2149		if (imo == 0)
2150			optval = coptval = IP_DEFAULT_MULTICAST_TTL;
2151		else
2152			optval = coptval = imo->imo_multicast_ttl;
2153		if (sopt->sopt_valsize == 1)
2154			error = sooptcopyout(sopt, &coptval, 1);
2155		else
2156			error = sooptcopyout(sopt, &optval, sizeof optval);
2157		break;
2158
2159	case IP_MULTICAST_LOOP:
2160		if (imo == 0)
2161			optval = coptval = IP_DEFAULT_MULTICAST_LOOP;
2162		else
2163			optval = coptval = imo->imo_multicast_loop;
2164		if (sopt->sopt_valsize == 1)
2165			error = sooptcopyout(sopt, &coptval, 1);
2166		else
2167			error = sooptcopyout(sopt, &optval, sizeof optval);
2168		break;
2169
2170	default:
2171		error = ENOPROTOOPT;
2172		break;
2173	}
2174	return (error);
2175}
2176
2177/*
2178 * Discard the IP multicast options.
2179 */
2180void
2181ip_freemoptions(imo)
2182	register struct ip_moptions *imo;
2183{
2184	register int i;
2185
2186	if (imo != NULL) {
2187		for (i = 0; i < imo->imo_num_memberships; ++i)
2188			in_delmulti(imo->imo_membership[i]);
2189		free(imo, M_IPMOPTS);
2190	}
2191}
2192
2193/*
2194 * Routine called from ip_output() to loop back a copy of an IP multicast
2195 * packet to the input queue of a specified interface.  Note that this
2196 * calls the output routine of the loopback "driver", but with an interface
2197 * pointer that might NOT be a loopback interface -- evil, but easier than
2198 * replicating that code here.
2199 */
2200static void
2201ip_mloopback(ifp, m, dst, hlen)
2202	struct ifnet *ifp;
2203	register struct mbuf *m;
2204	register struct sockaddr_in *dst;
2205	int hlen;
2206{
2207	register struct ip *ip;
2208	struct mbuf *copym;
2209
2210	copym = m_copy(m, 0, M_COPYALL);
2211	if (copym != NULL && (copym->m_flags & M_EXT || copym->m_len < hlen))
2212		copym = m_pullup(copym, hlen);
2213	if (copym != NULL) {
2214		/*
2215		 * We don't bother to fragment if the IP length is greater
2216		 * than the interface's MTU.  Can this possibly matter?
2217		 */
2218		ip = mtod(copym, struct ip *);
2219		ip->ip_len = htons(ip->ip_len);
2220		ip->ip_off = htons(ip->ip_off);
2221		ip->ip_sum = 0;
2222		ip->ip_sum = in_cksum(copym, hlen);
2223		/*
2224		 * NB:
2225		 * It's not clear whether there are any lingering
2226		 * reentrancy problems in other areas which might
2227		 * be exposed by using ip_input directly (in
2228		 * particular, everything which modifies the packet
2229		 * in-place).  Yet another option is using the
2230		 * protosw directly to deliver the looped back
2231		 * packet.  For the moment, we'll err on the side
2232		 * of safety by using if_simloop().
2233		 */
2234#if 1 /* XXX */
2235		if (dst->sin_family != AF_INET) {
2236			printf("ip_mloopback: bad address family %d\n",
2237						dst->sin_family);
2238			dst->sin_family = AF_INET;
2239		}
2240#endif
2241
2242#ifdef notdef
2243		copym->m_pkthdr.rcvif = ifp;
2244		ip_input(copym);
2245#else
2246		/* if the checksum hasn't been computed, mark it as valid */
2247		if (copym->m_pkthdr.csum_flags & CSUM_DELAY_DATA) {
2248			copym->m_pkthdr.csum_flags |=
2249			    CSUM_DATA_VALID | CSUM_PSEUDO_HDR;
2250			copym->m_pkthdr.csum_data = 0xffff;
2251		}
2252		if_simloop(ifp, copym, dst->sin_family, 0);
2253#endif
2254	}
2255}
2256