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