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