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