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