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