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