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