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