ip_input.c revision 105194
119370Spst/*
2130809Smarcel * Copyright (c) 1982, 1986, 1988, 1993
319370Spst *	The Regents of the University of California.  All rights reserved.
419370Spst *
598948Sobrien * Redistribution and use in source and binary forms, with or without
619370Spst * modification, are permitted provided that the following conditions
798948Sobrien * are met:
898948Sobrien * 1. Redistributions of source code must retain the above copyright
998948Sobrien *    notice, this list of conditions and the following disclaimer.
1098948Sobrien * 2. Redistributions in binary form must reproduce the above copyright
1119370Spst *    notice, this list of conditions and the following disclaimer in the
1298948Sobrien *    documentation and/or other materials provided with the distribution.
1398948Sobrien * 3. All advertising materials mentioning features or use of this software
1498948Sobrien *    must display the following acknowledgement:
1598948Sobrien *	This product includes software developed by the University of
1619370Spst *	California, Berkeley and its contributors.
1798948Sobrien * 4. Neither the name of the University nor the names of its contributors
1898948Sobrien *    may be used to endorse or promote products derived from this software
1998948Sobrien *    without specific prior written permission.
2098948Sobrien *
2119370Spst * THIS SOFTWARE IS PROVIDED BY THE REGENTS AND CONTRIBUTORS ``AS IS'' AND
2298948Sobrien * ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
2319370Spst * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE
2419370Spst * ARE DISCLAIMED.  IN NO EVENT SHALL THE REGENTS OR CONTRIBUTORS BE LIABLE
2519370Spst * FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL
2619370Spst * DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS
2719370Spst * OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION)
2819370Spst * HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT
2919370Spst * LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY
3019370Spst * OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF
3198948Sobrien * SUCH DAMAGE.
3224563Spst *
3319370Spst *	@(#)ip_input.c	8.2 (Berkeley) 1/4/94
34104993Smp * $FreeBSD: head/sys/netinet/ip_input.c 105194 2002-10-16 01:54:46Z sam $
35104993Smp */
36104993Smp
37104993Smp#define	_IP_VHL
38104993Smp
39104993Smp#include "opt_bootp.h"
40104993Smp#include "opt_ipfw.h"
41104993Smp#include "opt_ipdn.h"
42104993Smp#include "opt_ipdivert.h"
43104993Smp#include "opt_ipfilter.h"
4419370Spst#include "opt_ipstealth.h"
4519370Spst#include "opt_ipsec.h"
4619370Spst#include "opt_mac.h"
4719370Spst#include "opt_pfil_hooks.h"
4819370Spst#include "opt_random_ip_id.h"
4919370Spst
5019370Spst#include <sys/param.h>
5119370Spst#include <sys/systm.h>
5219370Spst#include <sys/mac.h>
5399675Sobrien#include <sys/mbuf.h>
5498948Sobrien#include <sys/malloc.h>
5519370Spst#include <sys/domain.h>
5698948Sobrien#include <sys/protosw.h>
5798948Sobrien#include <sys/socket.h>
5898948Sobrien#include <sys/time.h>
5998948Sobrien#include <sys/kernel.h>
6019370Spst#include <sys/syslog.h>
6119370Spst#include <sys/sysctl.h>
62130809Smarcel
63130809Smarcel#include <net/pfil.h>
64130809Smarcel#include <net/if.h>
65130809Smarcel#include <net/if_types.h>
6619370Spst#include <net/if_var.h>
6719370Spst#include <net/if_dl.h>
6819370Spst#include <net/route.h>
6919370Spst#include <net/netisr.h>
7019370Spst#include <net/intrq.h>
7119370Spst
7219370Spst#include <netinet/in.h>
7319370Spst#include <netinet/in_systm.h>
7419370Spst#include <netinet/in_var.h>
7519370Spst#include <netinet/ip.h>
7698948Sobrien#include <netinet/in_pcb.h>
7719370Spst#include <netinet/ip_var.h>
7819370Spst#include <netinet/ip_icmp.h>
7919370Spst#include <machine/in_cksum.h>
8019370Spst
8119370Spst#include <sys/socketvar.h>
8219370Spst
8319370Spst#include <netinet/ip_fw.h>
8419370Spst#include <netinet/ip_dummynet.h>
8599675Sobrien
8698948Sobrien#ifdef IPSEC
8719370Spst#include <netinet6/ipsec.h>
8819370Spst#include <netkey/key.h>
8919370Spst#endif
9019370Spst
9119370Spstint rsvp_on = 0;
9219370Spst
9319370Spstint	ipforwarding = 0;
9499675SobrienSYSCTL_INT(_net_inet_ip, IPCTL_FORWARDING, forwarding, CTLFLAG_RW,
9598948Sobrien    &ipforwarding, 0, "Enable IP forwarding between interfaces");
9619370Spst
9719370Spststatic int	ipsendredirects = 1; /* XXX */
9819370SpstSYSCTL_INT(_net_inet_ip, IPCTL_SENDREDIRECTS, redirect, CTLFLAG_RW,
9919370Spst    &ipsendredirects, 0, "Enable sending IP redirects");
10019370Spst
10119370Spstint	ip_defttl = IPDEFTTL;
10219370SpstSYSCTL_INT(_net_inet_ip, IPCTL_DEFTTL, ttl, CTLFLAG_RW,
10319370Spst    &ip_defttl, 0, "Maximum TTL on IP packets");
10419370Spst
10519370Spststatic int	ip_dosourceroute = 0;
10619370SpstSYSCTL_INT(_net_inet_ip, IPCTL_SOURCEROUTE, sourceroute, CTLFLAG_RW,
10719370Spst    &ip_dosourceroute, 0, "Enable forwarding source routed IP packets");
10819370Spst
10919370Spststatic int	ip_acceptsourceroute = 0;
11019370SpstSYSCTL_INT(_net_inet_ip, IPCTL_ACCEPTSOURCEROUTE, accept_sourceroute,
11119370Spst    CTLFLAG_RW, &ip_acceptsourceroute, 0,
11219370Spst    "Enable accepting source routed IP packets");
11319370Spst
11419370Spststatic int	ip_keepfaith = 0;
11519370SpstSYSCTL_INT(_net_inet_ip, IPCTL_KEEPFAITH, keepfaith, CTLFLAG_RW,
11619370Spst	&ip_keepfaith,	0,
11719370Spst	"Enable packet capture for FAITH IPv4->IPv6 translater daemon");
11819370Spst
11919370Spststatic int	ip_nfragpackets = 0;
12019370Spststatic int	ip_maxfragpackets;	/* initialized in ip_init() */
12198948SobrienSYSCTL_INT(_net_inet_ip, OID_AUTO, maxfragpackets, CTLFLAG_RW,
12298948Sobrien	&ip_maxfragpackets, 0,
12319370Spst	"Maximum number of IPv4 fragment reassembly queue entries");
12419370Spst
12598948Sobrien/*
12619370Spst * XXX - Setting ip_checkinterface mostly implements the receive side of
12719370Spst * the Strong ES model described in RFC 1122, but since the routing table
12898948Sobrien * and transmit implementation do not implement the Strong ES model,
12919370Spst * setting this to 1 results in an odd hybrid.
13019370Spst *
13119370Spst * XXX - ip_checkinterface currently must be disabled if you use ipnat
13219370Spst * to translate the destination address to another local interface.
13398948Sobrien *
13419370Spst * XXX - ip_checkinterface must be disabled if you add IP aliases
13519370Spst * to the loopback interface instead of the interface where the
13619370Spst * packets for those addresses are received.
13719370Spst */
13819370Spststatic int	ip_checkinterface = 1;
13998948SobrienSYSCTL_INT(_net_inet_ip, OID_AUTO, check_interface, CTLFLAG_RW,
14019370Spst    &ip_checkinterface, 0, "Verify packet arrives on correct interface");
14119370Spst
14298948Sobrien#ifdef DIAGNOSTIC
14319370Spststatic int	ipprintfs = 0;
14498948Sobrien#endif
14598948Sobrien
14619370Spststatic int	ipqmaxlen = IFQ_MAXLEN;
14719370Spst
14819370Spstextern	struct domain inetdomain;
14998948Sobrienextern	struct protosw inetsw[];
15098948Sobrienu_char	ip_protox[IPPROTO_MAX];
15119370Spststruct	in_ifaddrhead in_ifaddrhead; 		/* first inet address */
15219370Spststruct	in_ifaddrhashhead *in_ifaddrhashtbl;	/* inet addr hash table  */
15319370Spstu_long 	in_ifaddrhmask;				/* mask for hash table */
15419370Spst
15519370SpstSYSCTL_INT(_net_inet_ip, IPCTL_INTRQMAXLEN, intr_queue_maxlen, CTLFLAG_RW,
15619370Spst    &ipintrq.ifq_maxlen, 0, "Maximum size of the IP input queue");
15719370SpstSYSCTL_INT(_net_inet_ip, IPCTL_INTRQDROPS, intr_queue_drops, CTLFLAG_RD,
15819370Spst    &ipintrq.ifq_drops, 0, "Number of packets dropped from the IP input queue");
15998948Sobrien
16098948Sobrienstruct ipstat ipstat;
16119370SpstSYSCTL_STRUCT(_net_inet_ip, IPCTL_STATS, stats, CTLFLAG_RW,
16219370Spst    &ipstat, ipstat, "IP statistics (struct ipstat, netinet/ip_var.h)");
16319370Spst
16419370Spst/* Packet reassembly stuff */
16519370Spst#define IPREASS_NHASH_LOG2      6
16619370Spst#define IPREASS_NHASH           (1 << IPREASS_NHASH_LOG2)
16719370Spst#define IPREASS_HMASK           (IPREASS_NHASH - 1)
16819370Spst#define IPREASS_HASH(x,y) \
16919370Spst	(((((x) & 0xF) | ((((x) >> 8) & 0xF) << 4)) ^ (y)) & IPREASS_HMASK)
17019370Spst
17119370Spststatic TAILQ_HEAD(ipqhead, ipq) ipq[IPREASS_NHASH];
17219370Spststatic int    nipq = 0;         /* total # of reass queues */
17319370Spststatic int    maxnipq;
17419370Spst
17519370Spst#ifdef IPCTL_DEFMTU
17619370SpstSYSCTL_INT(_net_inet_ip, IPCTL_DEFMTU, mtu, CTLFLAG_RW,
17719370Spst    &ip_mtu, 0, "Default MTU");
17819370Spst#endif
17919370Spst
18098948Sobrien#ifdef IPSTEALTH
18119370Spststatic int	ipstealth = 0;
18219370SpstSYSCTL_INT(_net_inet_ip, OID_AUTO, stealth, CTLFLAG_RW,
18319370Spst    &ipstealth, 0, "");
18419370Spst#endif
18519370Spst
18619370Spst
18719370Spst/* Firewall hooks */
18819370Spstip_fw_chk_t *ip_fw_chk_ptr;
18919370Spstint fw_enable = 1 ;
19019370Spst
19119370Spst/* Dummynet hooks */
19219370Spstip_dn_io_t *ip_dn_io_ptr;
19319370Spst
19419370Spst
19519370Spst/*
19619370Spst * XXX this is ugly -- the following two global variables are
19719370Spst * used to store packet state while it travels through the stack.
19819370Spst * Note that the code even makes assumptions on the size and
19998948Sobrien * alignment of fields inside struct ip_srcrt so e.g. adding some
20098948Sobrien * fields will break the code. This needs to be fixed.
20198948Sobrien *
20298948Sobrien * We need to save the IP options in case a protocol wants to respond
20398948Sobrien * to an incoming packet over the same route if the packet got here
20498948Sobrien * using IP source routing.  This allows connection establishment and
20598948Sobrien * maintenance when the remote end is on a network that is not known
20698948Sobrien * to us.
20798948Sobrien */
20898948Sobrienstatic int	ip_nhops = 0;
20998948Sobrienstatic	struct ip_srcrt {
21098948Sobrien	struct	in_addr dst;			/* final destination */
21198948Sobrien	char	nop;				/* one NOP to align */
21298948Sobrien	char	srcopt[IPOPT_OFFSET + 1];	/* OPTVAL, OLEN and OFFSET */
21398948Sobrien	struct	in_addr route[MAX_IPOPTLEN/sizeof(struct in_addr)];
21498948Sobrien} ip_srcrt;
21598948Sobrien
21698948Sobrienstatic void	save_rte(u_char *, struct in_addr);
21798948Sobrienstatic int	ip_dooptions(struct mbuf *m, int,
21898948Sobrien			struct sockaddr_in *next_hop);
21919370Spststatic void	ip_forward(struct mbuf *m, int srcrt,
22019370Spst			struct sockaddr_in *next_hop);
22119370Spststatic void	ip_freef(struct ipqhead *, struct ipq *);
22219370Spststatic struct	mbuf *ip_reass(struct mbuf *, struct ipqhead *,
22319370Spst		struct ipq *, u_int32_t *, u_int16_t *);
22419370Spststatic void	ipintr(void);
22519370Spst
22619370Spst/*
22719370Spst * IP initialization: fill in IP protocol switch table.
22819370Spst * All protocols not implemented in kernel go to raw IP protocol handler.
22919370Spst */
23019370Spstvoid
23119370Spstip_init()
23219370Spst{
23319370Spst	register struct protosw *pr;
23419370Spst	register int i;
23519370Spst
23619370Spst	TAILQ_INIT(&in_ifaddrhead);
23719370Spst	in_ifaddrhashtbl = hashinit(INADDR_NHASH, M_IFADDR, &in_ifaddrhmask);
23819370Spst	pr = pffindproto(PF_INET, IPPROTO_RAW, SOCK_RAW);
23919370Spst	if (pr == 0)
24019370Spst		panic("ip_init");
24119370Spst	for (i = 0; i < IPPROTO_MAX; i++)
24299675Sobrien		ip_protox[i] = pr - inetsw;
24398948Sobrien	for (pr = inetdomain.dom_protosw;
24419370Spst	    pr < inetdomain.dom_protoswNPROTOSW; pr++)
24519370Spst		if (pr->pr_domain->dom_family == PF_INET &&
24619370Spst		    pr->pr_protocol && pr->pr_protocol != IPPROTO_RAW)
24719370Spst			ip_protox[pr->pr_protocol] = pr - inetsw;
24819370Spst
24919370Spst	for (i = 0; i < IPREASS_NHASH; i++)
25019370Spst	    TAILQ_INIT(&ipq[i]);
25119370Spst
25219370Spst	maxnipq = nmbclusters / 4;
25319370Spst	ip_maxfragpackets = nmbclusters / 4;
25419370Spst
25519370Spst#ifndef RANDOM_IP_ID
25619370Spst	ip_id = time_second & 0xffff;
25719370Spst#endif
25819370Spst	ipintrq.ifq_maxlen = ipqmaxlen;
25919370Spst	mtx_init(&ipintrq.ifq_mtx, "ip_inq", NULL, MTX_DEF);
26019370Spst	ipintrq_present = 1;
26198948Sobrien
26298948Sobrien	register_netisr(NETISR_IP, ipintr);
26319370Spst}
26419370Spst
26519370Spst/*
26619370Spst * XXX watch out this one. It is perhaps used as a cache for
26719370Spst * the most recently used route ? it is cleared in in_addroute()
26819370Spst * when a new route is successfully created.
26919370Spst */
27019370Spststruct	route ipforward_rt;
27119370Spst
27219370Spst/*
27399675Sobrien * Ip input routine.  Checksum and byte swap header.  If fragmented
27498948Sobrien * try to reassemble.  Process options.  Pass to next level.
27519370Spst */
27619370Spstvoid
27719370Spstip_input(struct mbuf *m)
27819370Spst{
27919370Spst	struct ip *ip;
28019370Spst	struct ipq *fp;
28119370Spst	struct in_ifaddr *ia = NULL;
28219370Spst	struct ifaddr *ifa;
28319370Spst	int    i, hlen, checkif;
28419370Spst	u_short sum;
28519370Spst	struct in_addr pkt_dst;
28619370Spst	u_int32_t divert_info = 0;		/* packet divert/tee info */
28719370Spst	struct ip_fw_args args;
28819370Spst#ifdef PFIL_HOOKS
28919370Spst	struct packet_filter_hook *pfh;
29019370Spst	struct mbuf *m0;
29119370Spst	int rv;
29298948Sobrien#endif /* PFIL_HOOKS */
29319370Spst
29419370Spst	args.eh = NULL;
29519370Spst	args.oif = NULL;
29619370Spst	args.rule = NULL;
29719370Spst	args.divert_rule = 0;			/* divert cookie */
29819370Spst	args.next_hop = NULL;
29919370Spst
30019370Spst	/* Grab info from MT_TAG mbufs prepended to the chain.	*/
30119370Spst	for (; m && m->m_type == MT_TAG; m = m->m_next) {
30219370Spst		switch(m->_m_tag_id) {
30319370Spst		default:
30419370Spst			printf("ip_input: unrecognised MT_TAG tag %d\n",
30519370Spst			    m->_m_tag_id);
30619370Spst			break;
30798948Sobrien
30819370Spst		case PACKET_TAG_DUMMYNET:
30919370Spst			args.rule = ((struct dn_pkt *)m)->rule;
31019370Spst			break;
31119370Spst
31219370Spst		case PACKET_TAG_DIVERT:
31319370Spst			args.divert_rule = (intptr_t)m->m_hdr.mh_data & 0xffff;
31419370Spst			break;
31519370Spst
31619370Spst		case PACKET_TAG_IPFORWARD:
31719370Spst			args.next_hop = (struct sockaddr_in *)m->m_hdr.mh_data;
31819370Spst			break;
31919370Spst		}
32019370Spst	}
32119370Spst
32219370Spst	KASSERT(m != NULL && (m->m_flags & M_PKTHDR) != 0,
32319370Spst	    ("ip_input: no HDR"));
32419370Spst
32519370Spst	if (args.rule) {	/* dummynet already filtered us */
32619370Spst		ip = mtod(m, struct ip *);
32719370Spst		hlen = IP_VHL_HL(ip->ip_vhl) << 2;
32819370Spst		goto iphack ;
32919370Spst	}
330
331	ipstat.ips_total++;
332
333	if (m->m_pkthdr.len < sizeof(struct ip))
334		goto tooshort;
335
336	if (m->m_len < sizeof (struct ip) &&
337	    (m = m_pullup(m, sizeof (struct ip))) == 0) {
338		ipstat.ips_toosmall++;
339		return;
340	}
341	ip = mtod(m, struct ip *);
342
343	if (IP_VHL_V(ip->ip_vhl) != IPVERSION) {
344		ipstat.ips_badvers++;
345		goto bad;
346	}
347
348	hlen = IP_VHL_HL(ip->ip_vhl) << 2;
349	if (hlen < sizeof(struct ip)) {	/* minimum header length */
350		ipstat.ips_badhlen++;
351		goto bad;
352	}
353	if (hlen > m->m_len) {
354		if ((m = m_pullup(m, hlen)) == 0) {
355			ipstat.ips_badhlen++;
356			return;
357		}
358		ip = mtod(m, struct ip *);
359	}
360
361	/* 127/8 must not appear on wire - RFC1122 */
362	if ((ntohl(ip->ip_dst.s_addr) >> IN_CLASSA_NSHIFT) == IN_LOOPBACKNET ||
363	    (ntohl(ip->ip_src.s_addr) >> IN_CLASSA_NSHIFT) == IN_LOOPBACKNET) {
364		if ((m->m_pkthdr.rcvif->if_flags & IFF_LOOPBACK) == 0) {
365			ipstat.ips_badaddr++;
366			goto bad;
367		}
368	}
369
370	if (m->m_pkthdr.csum_flags & CSUM_IP_CHECKED) {
371		sum = !(m->m_pkthdr.csum_flags & CSUM_IP_VALID);
372	} else {
373		if (hlen == sizeof(struct ip)) {
374			sum = in_cksum_hdr(ip);
375		} else {
376			sum = in_cksum(m, hlen);
377		}
378	}
379	if (sum) {
380		ipstat.ips_badsum++;
381		goto bad;
382	}
383
384	/*
385	 * Convert fields to host representation.
386	 */
387	ip->ip_len = ntohs(ip->ip_len);
388	if (ip->ip_len < hlen) {
389		ipstat.ips_badlen++;
390		goto bad;
391	}
392	ip->ip_off = ntohs(ip->ip_off);
393
394	/*
395	 * Check that the amount of data in the buffers
396	 * is as at least much as the IP header would have us expect.
397	 * Trim mbufs if longer than we expect.
398	 * Drop packet if shorter than we expect.
399	 */
400	if (m->m_pkthdr.len < ip->ip_len) {
401tooshort:
402		ipstat.ips_tooshort++;
403		goto bad;
404	}
405	if (m->m_pkthdr.len > ip->ip_len) {
406		if (m->m_len == m->m_pkthdr.len) {
407			m->m_len = ip->ip_len;
408			m->m_pkthdr.len = ip->ip_len;
409		} else
410			m_adj(m, ip->ip_len - m->m_pkthdr.len);
411	}
412
413#ifdef IPSEC
414	if (ipsec_gethist(m, NULL))
415		goto pass;
416#endif
417
418	/*
419	 * IpHack's section.
420	 * Right now when no processing on packet has done
421	 * and it is still fresh out of network we do our black
422	 * deals with it.
423	 * - Firewall: deny/allow/divert
424	 * - Xlate: translate packet's addr/port (NAT).
425	 * - Pipe: pass pkt through dummynet.
426	 * - Wrap: fake packet's addr/port <unimpl.>
427	 * - Encapsulate: put it in another IP and send out. <unimp.>
428 	 */
429
430iphack:
431
432#ifdef PFIL_HOOKS
433	/*
434	 * Run through list of hooks for input packets.  If there are any
435	 * filters which require that additional packets in the flow are
436	 * not fast-forwarded, they must clear the M_CANFASTFWD flag.
437	 * Note that filters must _never_ set this flag, as another filter
438	 * in the list may have previously cleared it.
439	 */
440	m0 = m;
441	pfh = pfil_hook_get(PFIL_IN, &inetsw[ip_protox[IPPROTO_IP]].pr_pfh);
442	for (; pfh; pfh = TAILQ_NEXT(pfh, pfil_link))
443		if (pfh->pfil_func) {
444			rv = pfh->pfil_func(ip, hlen,
445					    m->m_pkthdr.rcvif, 0, &m0);
446			if (rv)
447				return;
448			m = m0;
449			if (m == NULL)
450				return;
451			ip = mtod(m, struct ip *);
452		}
453#endif /* PFIL_HOOKS */
454
455	if (fw_enable && IPFW_LOADED) {
456		/*
457		 * If we've been forwarded from the output side, then
458		 * skip the firewall a second time
459		 */
460		if (args.next_hop)
461			goto ours;
462
463		args.m = m;
464		i = ip_fw_chk_ptr(&args);
465		m = args.m;
466
467		if ( (i & IP_FW_PORT_DENY_FLAG) || m == NULL) { /* drop */
468			if (m)
469				m_freem(m);
470			return;
471		}
472		ip = mtod(m, struct ip *); /* just in case m changed */
473		if (i == 0 && args.next_hop == NULL)	/* common case */
474			goto pass;
475                if (DUMMYNET_LOADED && (i & IP_FW_PORT_DYNT_FLAG) != 0) {
476			/* Send packet to the appropriate pipe */
477			ip_dn_io_ptr(m, i&0xffff, DN_TO_IP_IN, &args);
478			return;
479		}
480#ifdef IPDIVERT
481		if (i != 0 && (i & IP_FW_PORT_DYNT_FLAG) == 0) {
482			/* Divert or tee packet */
483			divert_info = i;
484			goto ours;
485		}
486#endif
487		if (i == 0 && args.next_hop != NULL)
488			goto pass;
489		/*
490		 * if we get here, the packet must be dropped
491		 */
492		m_freem(m);
493		return;
494	}
495pass:
496
497	/*
498	 * Process options and, if not destined for us,
499	 * ship it on.  ip_dooptions returns 1 when an
500	 * error was detected (causing an icmp message
501	 * to be sent and the original packet to be freed).
502	 */
503	ip_nhops = 0;		/* for source routed packets */
504	if (hlen > sizeof (struct ip) && ip_dooptions(m, 0, args.next_hop))
505		return;
506
507        /* greedy RSVP, snatches any PATH packet of the RSVP protocol and no
508         * matter if it is destined to another node, or whether it is
509         * a multicast one, RSVP wants it! and prevents it from being forwarded
510         * anywhere else. Also checks if the rsvp daemon is running before
511	 * grabbing the packet.
512         */
513	if (rsvp_on && ip->ip_p==IPPROTO_RSVP)
514		goto ours;
515
516	/*
517	 * Check our list of addresses, to see if the packet is for us.
518	 * If we don't have any addresses, assume any unicast packet
519	 * we receive might be for us (and let the upper layers deal
520	 * with it).
521	 */
522	if (TAILQ_EMPTY(&in_ifaddrhead) &&
523	    (m->m_flags & (M_MCAST|M_BCAST)) == 0)
524		goto ours;
525
526	/*
527	 * Cache the destination address of the packet; this may be
528	 * changed by use of 'ipfw fwd'.
529	 */
530	pkt_dst = args.next_hop ? args.next_hop->sin_addr : ip->ip_dst;
531
532	/*
533	 * Enable a consistency check between the destination address
534	 * and the arrival interface for a unicast packet (the RFC 1122
535	 * strong ES model) if IP forwarding is disabled and the packet
536	 * is not locally generated and the packet is not subject to
537	 * 'ipfw fwd'.
538	 *
539	 * XXX - Checking also should be disabled if the destination
540	 * address is ipnat'ed to a different interface.
541	 *
542	 * XXX - Checking is incompatible with IP aliases added
543	 * to the loopback interface instead of the interface where
544	 * the packets are received.
545	 */
546	checkif = ip_checkinterface && (ipforwarding == 0) &&
547	    m->m_pkthdr.rcvif != NULL &&
548	    ((m->m_pkthdr.rcvif->if_flags & IFF_LOOPBACK) == 0) &&
549	    (args.next_hop == NULL);
550
551	/*
552	 * Check for exact addresses in the hash bucket.
553	 */
554	LIST_FOREACH(ia, INADDR_HASH(pkt_dst.s_addr), ia_hash) {
555		/*
556		 * If the address matches, verify that the packet
557		 * arrived via the correct interface if checking is
558		 * enabled.
559		 */
560		if (IA_SIN(ia)->sin_addr.s_addr == pkt_dst.s_addr &&
561		    (!checkif || ia->ia_ifp == m->m_pkthdr.rcvif))
562			goto ours;
563	}
564	/*
565	 * Check for broadcast addresses.
566	 *
567	 * Only accept broadcast packets that arrive via the matching
568	 * interface.  Reception of forwarded directed broadcasts would
569	 * be handled via ip_forward() and ether_output() with the loopback
570	 * into the stack for SIMPLEX interfaces handled by ether_output().
571	 */
572	if (m->m_pkthdr.rcvif->if_flags & IFF_BROADCAST) {
573	        TAILQ_FOREACH(ifa, &m->m_pkthdr.rcvif->if_addrhead, ifa_link) {
574			if (ifa->ifa_addr->sa_family != AF_INET)
575				continue;
576			ia = ifatoia(ifa);
577			if (satosin(&ia->ia_broadaddr)->sin_addr.s_addr ==
578			    pkt_dst.s_addr)
579				goto ours;
580			if (ia->ia_netbroadcast.s_addr == pkt_dst.s_addr)
581				goto ours;
582#ifdef BOOTP_COMPAT
583			if (IA_SIN(ia)->sin_addr.s_addr == INADDR_ANY)
584				goto ours;
585#endif
586		}
587	}
588	if (IN_MULTICAST(ntohl(ip->ip_dst.s_addr))) {
589		struct in_multi *inm;
590		if (ip_mrouter) {
591			/*
592			 * If we are acting as a multicast router, all
593			 * incoming multicast packets are passed to the
594			 * kernel-level multicast forwarding function.
595			 * The packet is returned (relatively) intact; if
596			 * ip_mforward() returns a non-zero value, the packet
597			 * must be discarded, else it may be accepted below.
598			 */
599			if (ip_mforward(ip, m->m_pkthdr.rcvif, m, 0) != 0) {
600				ipstat.ips_cantforward++;
601				m_freem(m);
602				return;
603			}
604
605			/*
606			 * The process-level routing daemon needs to receive
607			 * all multicast IGMP packets, whether or not this
608			 * host belongs to their destination groups.
609			 */
610			if (ip->ip_p == IPPROTO_IGMP)
611				goto ours;
612			ipstat.ips_forward++;
613		}
614		/*
615		 * See if we belong to the destination multicast group on the
616		 * arrival interface.
617		 */
618		IN_LOOKUP_MULTI(ip->ip_dst, m->m_pkthdr.rcvif, inm);
619		if (inm == NULL) {
620			ipstat.ips_notmember++;
621			m_freem(m);
622			return;
623		}
624		goto ours;
625	}
626	if (ip->ip_dst.s_addr == (u_long)INADDR_BROADCAST)
627		goto ours;
628	if (ip->ip_dst.s_addr == INADDR_ANY)
629		goto ours;
630
631	/*
632	 * FAITH(Firewall Aided Internet Translator)
633	 */
634	if (m->m_pkthdr.rcvif && m->m_pkthdr.rcvif->if_type == IFT_FAITH) {
635		if (ip_keepfaith) {
636			if (ip->ip_p == IPPROTO_TCP || ip->ip_p == IPPROTO_ICMP)
637				goto ours;
638		}
639		m_freem(m);
640		return;
641	}
642
643	/*
644	 * Not for us; forward if possible and desirable.
645	 */
646	if (ipforwarding == 0) {
647		ipstat.ips_cantforward++;
648		m_freem(m);
649	} else {
650#ifdef IPSEC
651		/*
652		 * Enforce inbound IPsec SPD.
653		 */
654		if (ipsec4_in_reject(m, NULL)) {
655			ipsecstat.in_polvio++;
656			goto bad;
657		}
658#endif /* IPSEC */
659		ip_forward(m, 0, args.next_hop);
660	}
661	return;
662
663ours:
664#ifdef IPSTEALTH
665	/*
666	 * IPSTEALTH: Process non-routing options only
667	 * if the packet is destined for us.
668	 */
669	if (ipstealth && hlen > sizeof (struct ip) &&
670	    ip_dooptions(m, 1, args.next_hop))
671		return;
672#endif /* IPSTEALTH */
673
674	/* Count the packet in the ip address stats */
675	if (ia != NULL) {
676		ia->ia_ifa.if_ipackets++;
677		ia->ia_ifa.if_ibytes += m->m_pkthdr.len;
678	}
679
680	/*
681	 * If offset or IP_MF are set, must reassemble.
682	 * Otherwise, nothing need be done.
683	 * (We could look in the reassembly queue to see
684	 * if the packet was previously fragmented,
685	 * but it's not worth the time; just let them time out.)
686	 */
687	if (ip->ip_off & (IP_MF | IP_OFFMASK)) {
688
689		sum = IPREASS_HASH(ip->ip_src.s_addr, ip->ip_id);
690		/*
691		 * Look for queue of fragments
692		 * of this datagram.
693		 */
694		TAILQ_FOREACH(fp, &ipq[sum], ipq_list)
695			if (ip->ip_id == fp->ipq_id &&
696			    ip->ip_src.s_addr == fp->ipq_src.s_addr &&
697			    ip->ip_dst.s_addr == fp->ipq_dst.s_addr &&
698#ifdef MAC
699			    mac_fragment_match(m, fp) &&
700#endif
701			    ip->ip_p == fp->ipq_p)
702				goto found;
703
704		fp = 0;
705
706		/* check if there's a place for the new queue */
707		if (nipq > maxnipq) {
708		    /*
709		     * drop something from the tail of the current queue
710		     * before proceeding further
711		     */
712		    struct ipq *q = TAILQ_LAST(&ipq[sum], ipqhead);
713		    if (q == NULL) {   /* gak */
714			for (i = 0; i < IPREASS_NHASH; i++) {
715			    struct ipq *r = TAILQ_LAST(&ipq[i], ipqhead);
716			    if (r) {
717				ip_freef(&ipq[i], r);
718				break;
719			    }
720			}
721		    } else
722			ip_freef(&ipq[sum], q);
723		}
724found:
725		/*
726		 * Adjust ip_len to not reflect header,
727		 * convert offset of this to bytes.
728		 */
729		ip->ip_len -= hlen;
730		if (ip->ip_off & IP_MF) {
731		        /*
732		         * Make sure that fragments have a data length
733			 * that's a non-zero multiple of 8 bytes.
734		         */
735			if (ip->ip_len == 0 || (ip->ip_len & 0x7) != 0) {
736				ipstat.ips_toosmall++; /* XXX */
737				goto bad;
738			}
739			m->m_flags |= M_FRAG;
740		} else
741			m->m_flags &= ~M_FRAG;
742		ip->ip_off <<= 3;
743
744		/*
745		 * Attempt reassembly; if it succeeds, proceed.
746		 * ip_reass() will return a different mbuf, and update
747		 * the divert info in divert_info and args.divert_rule.
748		 */
749		ipstat.ips_fragments++;
750		m->m_pkthdr.header = ip;
751		m = ip_reass(m,
752		    &ipq[sum], fp, &divert_info, &args.divert_rule);
753		if (m == 0)
754			return;
755		ipstat.ips_reassembled++;
756		ip = mtod(m, struct ip *);
757		/* Get the header length of the reassembled packet */
758		hlen = IP_VHL_HL(ip->ip_vhl) << 2;
759#ifdef IPDIVERT
760		/* Restore original checksum before diverting packet */
761		if (divert_info != 0) {
762			ip->ip_len += hlen;
763			ip->ip_len = htons(ip->ip_len);
764			ip->ip_off = htons(ip->ip_off);
765			ip->ip_sum = 0;
766			if (hlen == sizeof(struct ip))
767				ip->ip_sum = in_cksum_hdr(ip);
768			else
769				ip->ip_sum = in_cksum(m, hlen);
770			ip->ip_off = ntohs(ip->ip_off);
771			ip->ip_len = ntohs(ip->ip_len);
772			ip->ip_len -= hlen;
773		}
774#endif
775	} else
776		ip->ip_len -= hlen;
777
778#ifdef IPDIVERT
779	/*
780	 * Divert or tee packet to the divert protocol if required.
781	 */
782	if (divert_info != 0) {
783		struct mbuf *clone = NULL;
784
785		/* Clone packet if we're doing a 'tee' */
786		if ((divert_info & IP_FW_PORT_TEE_FLAG) != 0)
787			clone = m_dup(m, M_DONTWAIT);
788
789		/* Restore packet header fields to original values */
790		ip->ip_len += hlen;
791		ip->ip_len = htons(ip->ip_len);
792		ip->ip_off = htons(ip->ip_off);
793
794		/* Deliver packet to divert input routine */
795		divert_packet(m, 1, divert_info & 0xffff, args.divert_rule);
796		ipstat.ips_delivered++;
797
798		/* If 'tee', continue with original packet */
799		if (clone == NULL)
800			return;
801		m = clone;
802		ip = mtod(m, struct ip *);
803		ip->ip_len += hlen;
804		/*
805		 * Jump backwards to complete processing of the
806		 * packet. But first clear divert_info to avoid
807		 * entering this block again.
808		 * We do not need to clear args.divert_rule
809		 * or args.next_hop as they will not be used.
810		 */
811		divert_info = 0;
812		goto pass;
813	}
814#endif
815
816#ifdef IPSEC
817	/*
818	 * enforce IPsec policy checking if we are seeing last header.
819	 * note that we do not visit this with protocols with pcb layer
820	 * code - like udp/tcp/raw ip.
821	 */
822	if ((inetsw[ip_protox[ip->ip_p]].pr_flags & PR_LASTHDR) != 0 &&
823	    ipsec4_in_reject(m, NULL)) {
824		ipsecstat.in_polvio++;
825		goto bad;
826	}
827#endif
828
829	/*
830	 * Switch out to protocol's input routine.
831	 */
832	ipstat.ips_delivered++;
833	if (args.next_hop && ip->ip_p == IPPROTO_TCP) {
834		/* TCP needs IPFORWARD info if available */
835		struct m_hdr tag;
836
837		tag.mh_type = MT_TAG;
838		tag.mh_flags = PACKET_TAG_IPFORWARD;
839		tag.mh_data = (caddr_t)args.next_hop;
840		tag.mh_next = m;
841
842		(*inetsw[ip_protox[ip->ip_p]].pr_input)(
843			(struct mbuf *)&tag, hlen);
844	} else
845		(*inetsw[ip_protox[ip->ip_p]].pr_input)(m, hlen);
846	return;
847bad:
848	m_freem(m);
849}
850
851/*
852 * IP software interrupt routine - to go away sometime soon
853 */
854static void
855ipintr(void)
856{
857	struct mbuf *m;
858
859	while (1) {
860		IF_DEQUEUE(&ipintrq, m);
861		if (m == 0)
862			return;
863		ip_input(m);
864	}
865}
866
867/*
868 * Take incoming datagram fragment and try to reassemble it into
869 * whole datagram.  If a chain for reassembly of this datagram already
870 * exists, then it is given as fp; otherwise have to make a chain.
871 *
872 * When IPDIVERT enabled, keep additional state with each packet that
873 * tells us if we need to divert or tee the packet we're building.
874 * In particular, *divinfo includes the port and TEE flag,
875 * *divert_rule is the number of the matching rule.
876 */
877
878static struct mbuf *
879ip_reass(struct mbuf *m, struct ipqhead *head, struct ipq *fp,
880	u_int32_t *divinfo, u_int16_t *divert_rule)
881{
882	struct ip *ip = mtod(m, struct ip *);
883	register struct mbuf *p, *q, *nq;
884	struct mbuf *t;
885	int hlen = IP_VHL_HL(ip->ip_vhl) << 2;
886	int i, next;
887
888	/*
889	 * Presence of header sizes in mbufs
890	 * would confuse code below.
891	 */
892	m->m_data += hlen;
893	m->m_len -= hlen;
894
895	/*
896	 * If first fragment to arrive, create a reassembly queue.
897	 */
898	if (fp == 0) {
899		/*
900		 * Enforce upper bound on number of fragmented packets
901		 * for which we attempt reassembly;
902		 * If maxfrag is 0, never accept fragments.
903		 * If maxfrag is -1, accept all fragments without limitation.
904		 */
905		if ((ip_maxfragpackets >= 0) && (ip_nfragpackets >= ip_maxfragpackets))
906			goto dropfrag;
907		ip_nfragpackets++;
908		if ((t = m_get(M_DONTWAIT, MT_FTABLE)) == NULL)
909			goto dropfrag;
910		fp = mtod(t, struct ipq *);
911#ifdef MAC
912		mac_init_ipq(fp);
913		mac_create_ipq(m, fp);
914#endif
915		TAILQ_INSERT_HEAD(head, fp, ipq_list);
916		nipq++;
917		fp->ipq_ttl = IPFRAGTTL;
918		fp->ipq_p = ip->ip_p;
919		fp->ipq_id = ip->ip_id;
920		fp->ipq_src = ip->ip_src;
921		fp->ipq_dst = ip->ip_dst;
922		fp->ipq_frags = m;
923		m->m_nextpkt = NULL;
924#ifdef IPDIVERT
925		fp->ipq_div_info = 0;
926		fp->ipq_div_cookie = 0;
927#endif
928		goto inserted;
929	} else {
930#ifdef MAC
931		mac_update_ipq(m, fp);
932#endif
933	}
934
935#define GETIP(m)	((struct ip*)((m)->m_pkthdr.header))
936
937	/*
938	 * Find a segment which begins after this one does.
939	 */
940	for (p = NULL, q = fp->ipq_frags; q; p = q, q = q->m_nextpkt)
941		if (GETIP(q)->ip_off > ip->ip_off)
942			break;
943
944	/*
945	 * If there is a preceding segment, it may provide some of
946	 * our data already.  If so, drop the data from the incoming
947	 * segment.  If it provides all of our data, drop us, otherwise
948	 * stick new segment in the proper place.
949	 *
950	 * If some of the data is dropped from the the preceding
951	 * segment, then it's checksum is invalidated.
952	 */
953	if (p) {
954		i = GETIP(p)->ip_off + GETIP(p)->ip_len - ip->ip_off;
955		if (i > 0) {
956			if (i >= ip->ip_len)
957				goto dropfrag;
958			m_adj(m, i);
959			m->m_pkthdr.csum_flags = 0;
960			ip->ip_off += i;
961			ip->ip_len -= i;
962		}
963		m->m_nextpkt = p->m_nextpkt;
964		p->m_nextpkt = m;
965	} else {
966		m->m_nextpkt = fp->ipq_frags;
967		fp->ipq_frags = m;
968	}
969
970	/*
971	 * While we overlap succeeding segments trim them or,
972	 * if they are completely covered, dequeue them.
973	 */
974	for (; q != NULL && ip->ip_off + ip->ip_len > GETIP(q)->ip_off;
975	     q = nq) {
976		i = (ip->ip_off + ip->ip_len) -
977		    GETIP(q)->ip_off;
978		if (i < GETIP(q)->ip_len) {
979			GETIP(q)->ip_len -= i;
980			GETIP(q)->ip_off += i;
981			m_adj(q, i);
982			q->m_pkthdr.csum_flags = 0;
983			break;
984		}
985		nq = q->m_nextpkt;
986		m->m_nextpkt = nq;
987		m_freem(q);
988	}
989
990inserted:
991
992#ifdef IPDIVERT
993	/*
994	 * Transfer firewall instructions to the fragment structure.
995	 * Only trust info in the fragment at offset 0.
996	 */
997	if (ip->ip_off == 0) {
998		fp->ipq_div_info = *divinfo;
999		fp->ipq_div_cookie = *divert_rule;
1000	}
1001	*divinfo = 0;
1002	*divert_rule = 0;
1003#endif
1004
1005	/*
1006	 * Check for complete reassembly.
1007	 */
1008	next = 0;
1009	for (p = NULL, q = fp->ipq_frags; q; p = q, q = q->m_nextpkt) {
1010		if (GETIP(q)->ip_off != next)
1011			return (0);
1012		next += GETIP(q)->ip_len;
1013	}
1014	/* Make sure the last packet didn't have the IP_MF flag */
1015	if (p->m_flags & M_FRAG)
1016		return (0);
1017
1018	/*
1019	 * Reassembly is complete.  Make sure the packet is a sane size.
1020	 */
1021	q = fp->ipq_frags;
1022	ip = GETIP(q);
1023	if (next + (IP_VHL_HL(ip->ip_vhl) << 2) > IP_MAXPACKET) {
1024		ipstat.ips_toolong++;
1025		ip_freef(head, fp);
1026		return (0);
1027	}
1028
1029	/*
1030	 * Concatenate fragments.
1031	 */
1032	m = q;
1033	t = m->m_next;
1034	m->m_next = 0;
1035	m_cat(m, t);
1036	nq = q->m_nextpkt;
1037	q->m_nextpkt = 0;
1038	for (q = nq; q != NULL; q = nq) {
1039		nq = q->m_nextpkt;
1040		q->m_nextpkt = NULL;
1041		m->m_pkthdr.csum_flags &= q->m_pkthdr.csum_flags;
1042		m->m_pkthdr.csum_data += q->m_pkthdr.csum_data;
1043		m_cat(m, q);
1044	}
1045#ifdef MAC
1046	mac_create_datagram_from_ipq(fp, m);
1047	mac_destroy_ipq(fp);
1048#endif
1049
1050#ifdef IPDIVERT
1051	/*
1052	 * Extract firewall instructions from the fragment structure.
1053	 */
1054	*divinfo = fp->ipq_div_info;
1055	*divert_rule = fp->ipq_div_cookie;
1056#endif
1057
1058	/*
1059	 * Create header for new ip packet by
1060	 * modifying header of first packet;
1061	 * dequeue and discard fragment reassembly header.
1062	 * Make header visible.
1063	 */
1064	ip->ip_len = next;
1065	ip->ip_src = fp->ipq_src;
1066	ip->ip_dst = fp->ipq_dst;
1067	TAILQ_REMOVE(head, fp, ipq_list);
1068	nipq--;
1069	(void) m_free(dtom(fp));
1070	ip_nfragpackets--;
1071	m->m_len += (IP_VHL_HL(ip->ip_vhl) << 2);
1072	m->m_data -= (IP_VHL_HL(ip->ip_vhl) << 2);
1073	/* some debugging cruft by sklower, below, will go away soon */
1074	if (m->m_flags & M_PKTHDR)	/* XXX this should be done elsewhere */
1075		m_fixhdr(m);
1076	return (m);
1077
1078dropfrag:
1079#ifdef IPDIVERT
1080	*divinfo = 0;
1081	*divert_rule = 0;
1082#endif
1083	ipstat.ips_fragdropped++;
1084	m_freem(m);
1085	return (0);
1086
1087#undef GETIP
1088}
1089
1090/*
1091 * Free a fragment reassembly header and all
1092 * associated datagrams.
1093 */
1094static void
1095ip_freef(fhp, fp)
1096	struct ipqhead *fhp;
1097	struct ipq *fp;
1098{
1099	register struct mbuf *q;
1100
1101	while (fp->ipq_frags) {
1102		q = fp->ipq_frags;
1103		fp->ipq_frags = q->m_nextpkt;
1104		m_freem(q);
1105	}
1106	TAILQ_REMOVE(fhp, fp, ipq_list);
1107	(void) m_free(dtom(fp));
1108	ip_nfragpackets--;
1109	nipq--;
1110}
1111
1112/*
1113 * IP timer processing;
1114 * if a timer expires on a reassembly
1115 * queue, discard it.
1116 */
1117void
1118ip_slowtimo()
1119{
1120	register struct ipq *fp;
1121	int s = splnet();
1122	int i;
1123
1124	for (i = 0; i < IPREASS_NHASH; i++) {
1125		for(fp = TAILQ_FIRST(&ipq[i]); fp;) {
1126			struct ipq *fpp;
1127
1128			fpp = fp;
1129			fp = TAILQ_NEXT(fp, ipq_list);
1130			if(--fpp->ipq_ttl == 0) {
1131				ipstat.ips_fragtimeout++;
1132				ip_freef(&ipq[i], fpp);
1133			}
1134		}
1135	}
1136	/*
1137	 * If we are over the maximum number of fragments
1138	 * (due to the limit being lowered), drain off
1139	 * enough to get down to the new limit.
1140	 */
1141	for (i = 0; i < IPREASS_NHASH; i++) {
1142		if (ip_maxfragpackets >= 0) {
1143			while (ip_nfragpackets > ip_maxfragpackets &&
1144				!TAILQ_EMPTY(&ipq[i])) {
1145				ipstat.ips_fragdropped++;
1146				ip_freef(&ipq[i], TAILQ_FIRST(&ipq[i]));
1147			}
1148		}
1149	}
1150	ipflow_slowtimo();
1151	splx(s);
1152}
1153
1154/*
1155 * Drain off all datagram fragments.
1156 */
1157void
1158ip_drain()
1159{
1160	int     i;
1161
1162	for (i = 0; i < IPREASS_NHASH; i++) {
1163		while(!TAILQ_EMPTY(&ipq[i])) {
1164			ipstat.ips_fragdropped++;
1165			ip_freef(&ipq[i], TAILQ_FIRST(&ipq[i]));
1166		}
1167	}
1168	in_rtqdrain();
1169}
1170
1171/*
1172 * Do option processing on a datagram,
1173 * possibly discarding it if bad options are encountered,
1174 * or forwarding it if source-routed.
1175 * The pass argument is used when operating in the IPSTEALTH
1176 * mode to tell what options to process:
1177 * [LS]SRR (pass 0) or the others (pass 1).
1178 * The reason for as many as two passes is that when doing IPSTEALTH,
1179 * non-routing options should be processed only if the packet is for us.
1180 * Returns 1 if packet has been forwarded/freed,
1181 * 0 if the packet should be processed further.
1182 */
1183static int
1184ip_dooptions(struct mbuf *m, int pass, struct sockaddr_in *next_hop)
1185{
1186	struct ip *ip = mtod(m, struct ip *);
1187	u_char *cp;
1188	struct in_ifaddr *ia;
1189	int opt, optlen, cnt, off, code, type = ICMP_PARAMPROB, forward = 0;
1190	struct in_addr *sin, dst;
1191	n_time ntime;
1192	struct	sockaddr_in ipaddr = { sizeof(ipaddr), AF_INET };
1193
1194	dst = ip->ip_dst;
1195	cp = (u_char *)(ip + 1);
1196	cnt = (IP_VHL_HL(ip->ip_vhl) << 2) - sizeof (struct ip);
1197	for (; cnt > 0; cnt -= optlen, cp += optlen) {
1198		opt = cp[IPOPT_OPTVAL];
1199		if (opt == IPOPT_EOL)
1200			break;
1201		if (opt == IPOPT_NOP)
1202			optlen = 1;
1203		else {
1204			if (cnt < IPOPT_OLEN + sizeof(*cp)) {
1205				code = &cp[IPOPT_OLEN] - (u_char *)ip;
1206				goto bad;
1207			}
1208			optlen = cp[IPOPT_OLEN];
1209			if (optlen < IPOPT_OLEN + sizeof(*cp) || optlen > cnt) {
1210				code = &cp[IPOPT_OLEN] - (u_char *)ip;
1211				goto bad;
1212			}
1213		}
1214		switch (opt) {
1215
1216		default:
1217			break;
1218
1219		/*
1220		 * Source routing with record.
1221		 * Find interface with current destination address.
1222		 * If none on this machine then drop if strictly routed,
1223		 * or do nothing if loosely routed.
1224		 * Record interface address and bring up next address
1225		 * component.  If strictly routed make sure next
1226		 * address is on directly accessible net.
1227		 */
1228		case IPOPT_LSRR:
1229		case IPOPT_SSRR:
1230#ifdef IPSTEALTH
1231			if (ipstealth && pass > 0)
1232				break;
1233#endif
1234			if (optlen < IPOPT_OFFSET + sizeof(*cp)) {
1235				code = &cp[IPOPT_OLEN] - (u_char *)ip;
1236				goto bad;
1237			}
1238			if ((off = cp[IPOPT_OFFSET]) < IPOPT_MINOFF) {
1239				code = &cp[IPOPT_OFFSET] - (u_char *)ip;
1240				goto bad;
1241			}
1242			ipaddr.sin_addr = ip->ip_dst;
1243			ia = (struct in_ifaddr *)
1244				ifa_ifwithaddr((struct sockaddr *)&ipaddr);
1245			if (ia == 0) {
1246				if (opt == IPOPT_SSRR) {
1247					type = ICMP_UNREACH;
1248					code = ICMP_UNREACH_SRCFAIL;
1249					goto bad;
1250				}
1251				if (!ip_dosourceroute)
1252					goto nosourcerouting;
1253				/*
1254				 * Loose routing, and not at next destination
1255				 * yet; nothing to do except forward.
1256				 */
1257				break;
1258			}
1259			off--;			/* 0 origin */
1260			if (off > optlen - (int)sizeof(struct in_addr)) {
1261				/*
1262				 * End of source route.  Should be for us.
1263				 */
1264				if (!ip_acceptsourceroute)
1265					goto nosourcerouting;
1266				save_rte(cp, ip->ip_src);
1267				break;
1268			}
1269#ifdef IPSTEALTH
1270			if (ipstealth)
1271				goto dropit;
1272#endif
1273			if (!ip_dosourceroute) {
1274				if (ipforwarding) {
1275					char buf[16]; /* aaa.bbb.ccc.ddd\0 */
1276					/*
1277					 * Acting as a router, so generate ICMP
1278					 */
1279nosourcerouting:
1280					strcpy(buf, inet_ntoa(ip->ip_dst));
1281					log(LOG_WARNING,
1282					    "attempted source route from %s to %s\n",
1283					    inet_ntoa(ip->ip_src), buf);
1284					type = ICMP_UNREACH;
1285					code = ICMP_UNREACH_SRCFAIL;
1286					goto bad;
1287				} else {
1288					/*
1289					 * Not acting as a router, so silently drop.
1290					 */
1291#ifdef IPSTEALTH
1292dropit:
1293#endif
1294					ipstat.ips_cantforward++;
1295					m_freem(m);
1296					return (1);
1297				}
1298			}
1299
1300			/*
1301			 * locate outgoing interface
1302			 */
1303			(void)memcpy(&ipaddr.sin_addr, cp + off,
1304			    sizeof(ipaddr.sin_addr));
1305
1306			if (opt == IPOPT_SSRR) {
1307#define	INA	struct in_ifaddr *
1308#define	SA	struct sockaddr *
1309			    if ((ia = (INA)ifa_ifwithdstaddr((SA)&ipaddr)) == 0)
1310				ia = (INA)ifa_ifwithnet((SA)&ipaddr);
1311			} else
1312				ia = ip_rtaddr(ipaddr.sin_addr, &ipforward_rt);
1313			if (ia == 0) {
1314				type = ICMP_UNREACH;
1315				code = ICMP_UNREACH_SRCFAIL;
1316				goto bad;
1317			}
1318			ip->ip_dst = ipaddr.sin_addr;
1319			(void)memcpy(cp + off, &(IA_SIN(ia)->sin_addr),
1320			    sizeof(struct in_addr));
1321			cp[IPOPT_OFFSET] += sizeof(struct in_addr);
1322			/*
1323			 * Let ip_intr's mcast routing check handle mcast pkts
1324			 */
1325			forward = !IN_MULTICAST(ntohl(ip->ip_dst.s_addr));
1326			break;
1327
1328		case IPOPT_RR:
1329#ifdef IPSTEALTH
1330			if (ipstealth && pass == 0)
1331				break;
1332#endif
1333			if (optlen < IPOPT_OFFSET + sizeof(*cp)) {
1334				code = &cp[IPOPT_OFFSET] - (u_char *)ip;
1335				goto bad;
1336			}
1337			if ((off = cp[IPOPT_OFFSET]) < IPOPT_MINOFF) {
1338				code = &cp[IPOPT_OFFSET] - (u_char *)ip;
1339				goto bad;
1340			}
1341			/*
1342			 * If no space remains, ignore.
1343			 */
1344			off--;			/* 0 origin */
1345			if (off > optlen - (int)sizeof(struct in_addr))
1346				break;
1347			(void)memcpy(&ipaddr.sin_addr, &ip->ip_dst,
1348			    sizeof(ipaddr.sin_addr));
1349			/*
1350			 * locate outgoing interface; if we're the destination,
1351			 * use the incoming interface (should be same).
1352			 */
1353			if ((ia = (INA)ifa_ifwithaddr((SA)&ipaddr)) == 0 &&
1354			    (ia = ip_rtaddr(ipaddr.sin_addr,
1355			    &ipforward_rt)) == 0) {
1356				type = ICMP_UNREACH;
1357				code = ICMP_UNREACH_HOST;
1358				goto bad;
1359			}
1360			(void)memcpy(cp + off, &(IA_SIN(ia)->sin_addr),
1361			    sizeof(struct in_addr));
1362			cp[IPOPT_OFFSET] += sizeof(struct in_addr);
1363			break;
1364
1365		case IPOPT_TS:
1366#ifdef IPSTEALTH
1367			if (ipstealth && pass == 0)
1368				break;
1369#endif
1370			code = cp - (u_char *)ip;
1371			if (optlen < 4 || optlen > 40) {
1372				code = &cp[IPOPT_OLEN] - (u_char *)ip;
1373				goto bad;
1374			}
1375			if ((off = cp[IPOPT_OFFSET]) < 5) {
1376				code = &cp[IPOPT_OLEN] - (u_char *)ip;
1377				goto bad;
1378			}
1379			if (off > optlen - (int)sizeof(int32_t)) {
1380				cp[IPOPT_OFFSET + 1] += (1 << 4);
1381				if ((cp[IPOPT_OFFSET + 1] & 0xf0) == 0) {
1382					code = &cp[IPOPT_OFFSET] - (u_char *)ip;
1383					goto bad;
1384				}
1385				break;
1386			}
1387			off--;				/* 0 origin */
1388			sin = (struct in_addr *)(cp + off);
1389			switch (cp[IPOPT_OFFSET + 1] & 0x0f) {
1390
1391			case IPOPT_TS_TSONLY:
1392				break;
1393
1394			case IPOPT_TS_TSANDADDR:
1395				if (off + sizeof(n_time) +
1396				    sizeof(struct in_addr) > optlen) {
1397					code = &cp[IPOPT_OFFSET] - (u_char *)ip;
1398					goto bad;
1399				}
1400				ipaddr.sin_addr = dst;
1401				ia = (INA)ifaof_ifpforaddr((SA)&ipaddr,
1402							    m->m_pkthdr.rcvif);
1403				if (ia == 0)
1404					continue;
1405				(void)memcpy(sin, &IA_SIN(ia)->sin_addr,
1406				    sizeof(struct in_addr));
1407				cp[IPOPT_OFFSET] += sizeof(struct in_addr);
1408				off += sizeof(struct in_addr);
1409				break;
1410
1411			case IPOPT_TS_PRESPEC:
1412				if (off + sizeof(n_time) +
1413				    sizeof(struct in_addr) > optlen) {
1414					code = &cp[IPOPT_OFFSET] - (u_char *)ip;
1415					goto bad;
1416				}
1417				(void)memcpy(&ipaddr.sin_addr, sin,
1418				    sizeof(struct in_addr));
1419				if (ifa_ifwithaddr((SA)&ipaddr) == 0)
1420					continue;
1421				cp[IPOPT_OFFSET] += sizeof(struct in_addr);
1422				off += sizeof(struct in_addr);
1423				break;
1424
1425			default:
1426				code = &cp[IPOPT_OFFSET + 1] - (u_char *)ip;
1427				goto bad;
1428			}
1429			ntime = iptime();
1430			(void)memcpy(cp + off, &ntime, sizeof(n_time));
1431			cp[IPOPT_OFFSET] += sizeof(n_time);
1432		}
1433	}
1434	if (forward && ipforwarding) {
1435		ip_forward(m, 1, next_hop);
1436		return (1);
1437	}
1438	return (0);
1439bad:
1440	icmp_error(m, type, code, 0, 0);
1441	ipstat.ips_badoptions++;
1442	return (1);
1443}
1444
1445/*
1446 * Given address of next destination (final or next hop),
1447 * return internet address info of interface to be used to get there.
1448 */
1449struct in_ifaddr *
1450ip_rtaddr(dst, rt)
1451	struct in_addr dst;
1452	struct route *rt;
1453{
1454	register struct sockaddr_in *sin;
1455
1456	sin = (struct sockaddr_in *)&rt->ro_dst;
1457
1458	if (rt->ro_rt == 0 ||
1459	    !(rt->ro_rt->rt_flags & RTF_UP) ||
1460	    dst.s_addr != sin->sin_addr.s_addr) {
1461		if (rt->ro_rt) {
1462			RTFREE(rt->ro_rt);
1463			rt->ro_rt = 0;
1464		}
1465		sin->sin_family = AF_INET;
1466		sin->sin_len = sizeof(*sin);
1467		sin->sin_addr = dst;
1468
1469		rtalloc_ign(rt, RTF_PRCLONING);
1470	}
1471	if (rt->ro_rt == 0)
1472		return ((struct in_ifaddr *)0);
1473	return (ifatoia(rt->ro_rt->rt_ifa));
1474}
1475
1476/*
1477 * Save incoming source route for use in replies,
1478 * to be picked up later by ip_srcroute if the receiver is interested.
1479 */
1480static void
1481save_rte(option, dst)
1482	u_char *option;
1483	struct in_addr dst;
1484{
1485	unsigned olen;
1486
1487	olen = option[IPOPT_OLEN];
1488#ifdef DIAGNOSTIC
1489	if (ipprintfs)
1490		printf("save_rte: olen %d\n", olen);
1491#endif
1492	if (olen > sizeof(ip_srcrt) - (1 + sizeof(dst)))
1493		return;
1494	bcopy(option, ip_srcrt.srcopt, olen);
1495	ip_nhops = (olen - IPOPT_OFFSET - 1) / sizeof(struct in_addr);
1496	ip_srcrt.dst = dst;
1497}
1498
1499/*
1500 * Retrieve incoming source route for use in replies,
1501 * in the same form used by setsockopt.
1502 * The first hop is placed before the options, will be removed later.
1503 */
1504struct mbuf *
1505ip_srcroute()
1506{
1507	register struct in_addr *p, *q;
1508	register struct mbuf *m;
1509
1510	if (ip_nhops == 0)
1511		return ((struct mbuf *)0);
1512	m = m_get(M_DONTWAIT, MT_HEADER);
1513	if (m == 0)
1514		return ((struct mbuf *)0);
1515
1516#define OPTSIZ	(sizeof(ip_srcrt.nop) + sizeof(ip_srcrt.srcopt))
1517
1518	/* length is (nhops+1)*sizeof(addr) + sizeof(nop + srcrt header) */
1519	m->m_len = ip_nhops * sizeof(struct in_addr) + sizeof(struct in_addr) +
1520	    OPTSIZ;
1521#ifdef DIAGNOSTIC
1522	if (ipprintfs)
1523		printf("ip_srcroute: nhops %d mlen %d", ip_nhops, m->m_len);
1524#endif
1525
1526	/*
1527	 * First save first hop for return route
1528	 */
1529	p = &ip_srcrt.route[ip_nhops - 1];
1530	*(mtod(m, struct in_addr *)) = *p--;
1531#ifdef DIAGNOSTIC
1532	if (ipprintfs)
1533		printf(" hops %lx", (u_long)ntohl(mtod(m, struct in_addr *)->s_addr));
1534#endif
1535
1536	/*
1537	 * Copy option fields and padding (nop) to mbuf.
1538	 */
1539	ip_srcrt.nop = IPOPT_NOP;
1540	ip_srcrt.srcopt[IPOPT_OFFSET] = IPOPT_MINOFF;
1541	(void)memcpy(mtod(m, caddr_t) + sizeof(struct in_addr),
1542	    &ip_srcrt.nop, OPTSIZ);
1543	q = (struct in_addr *)(mtod(m, caddr_t) +
1544	    sizeof(struct in_addr) + OPTSIZ);
1545#undef OPTSIZ
1546	/*
1547	 * Record return path as an IP source route,
1548	 * reversing the path (pointers are now aligned).
1549	 */
1550	while (p >= ip_srcrt.route) {
1551#ifdef DIAGNOSTIC
1552		if (ipprintfs)
1553			printf(" %lx", (u_long)ntohl(q->s_addr));
1554#endif
1555		*q++ = *p--;
1556	}
1557	/*
1558	 * Last hop goes to final destination.
1559	 */
1560	*q = ip_srcrt.dst;
1561#ifdef DIAGNOSTIC
1562	if (ipprintfs)
1563		printf(" %lx\n", (u_long)ntohl(q->s_addr));
1564#endif
1565	return (m);
1566}
1567
1568/*
1569 * Strip out IP options, at higher
1570 * level protocol in the kernel.
1571 * Second argument is buffer to which options
1572 * will be moved, and return value is their length.
1573 * XXX should be deleted; last arg currently ignored.
1574 */
1575void
1576ip_stripoptions(m, mopt)
1577	register struct mbuf *m;
1578	struct mbuf *mopt;
1579{
1580	register int i;
1581	struct ip *ip = mtod(m, struct ip *);
1582	register caddr_t opts;
1583	int olen;
1584
1585	olen = (IP_VHL_HL(ip->ip_vhl) << 2) - sizeof (struct ip);
1586	opts = (caddr_t)(ip + 1);
1587	i = m->m_len - (sizeof (struct ip) + olen);
1588	bcopy(opts + olen, opts, (unsigned)i);
1589	m->m_len -= olen;
1590	if (m->m_flags & M_PKTHDR)
1591		m->m_pkthdr.len -= olen;
1592	ip->ip_vhl = IP_MAKE_VHL(IPVERSION, sizeof(struct ip) >> 2);
1593}
1594
1595u_char inetctlerrmap[PRC_NCMDS] = {
1596	0,		0,		0,		0,
1597	0,		EMSGSIZE,	EHOSTDOWN,	EHOSTUNREACH,
1598	EHOSTUNREACH,	EHOSTUNREACH,	ECONNREFUSED,	ECONNREFUSED,
1599	EMSGSIZE,	EHOSTUNREACH,	0,		0,
1600	0,		0,		0,		0,
1601	ENOPROTOOPT,	ECONNREFUSED
1602};
1603
1604/*
1605 * Forward a packet.  If some error occurs return the sender
1606 * an icmp packet.  Note we can't always generate a meaningful
1607 * icmp message because icmp doesn't have a large enough repertoire
1608 * of codes and types.
1609 *
1610 * If not forwarding, just drop the packet.  This could be confusing
1611 * if ipforwarding was zero but some routing protocol was advancing
1612 * us as a gateway to somewhere.  However, we must let the routing
1613 * protocol deal with that.
1614 *
1615 * The srcrt parameter indicates whether the packet is being forwarded
1616 * via a source route.
1617 */
1618static void
1619ip_forward(struct mbuf *m, int srcrt, struct sockaddr_in *next_hop)
1620{
1621	struct ip *ip = mtod(m, struct ip *);
1622	struct rtentry *rt;
1623	int error, type = 0, code = 0;
1624	struct mbuf *mcopy;
1625	n_long dest;
1626	struct in_addr pkt_dst;
1627	struct ifnet *destifp;
1628#ifdef IPSEC
1629	struct ifnet dummyifp;
1630#endif
1631
1632	dest = 0;
1633	/*
1634	 * Cache the destination address of the packet; this may be
1635	 * changed by use of 'ipfw fwd'.
1636	 */
1637	pkt_dst = next_hop ? next_hop->sin_addr : ip->ip_dst;
1638
1639#ifdef DIAGNOSTIC
1640	if (ipprintfs)
1641		printf("forward: src %lx dst %lx ttl %x\n",
1642		    (u_long)ip->ip_src.s_addr, (u_long)pkt_dst.s_addr,
1643		    ip->ip_ttl);
1644#endif
1645
1646
1647	if (m->m_flags & (M_BCAST|M_MCAST) || in_canforward(pkt_dst) == 0) {
1648		ipstat.ips_cantforward++;
1649		m_freem(m);
1650		return;
1651	}
1652#ifdef IPSTEALTH
1653	if (!ipstealth) {
1654#endif
1655		if (ip->ip_ttl <= IPTTLDEC) {
1656			icmp_error(m, ICMP_TIMXCEED, ICMP_TIMXCEED_INTRANS,
1657			    dest, 0);
1658			return;
1659		}
1660#ifdef IPSTEALTH
1661	}
1662#endif
1663
1664	if (ip_rtaddr(pkt_dst, &ipforward_rt) == 0) {
1665		icmp_error(m, ICMP_UNREACH, ICMP_UNREACH_HOST, dest, 0);
1666		return;
1667	} else
1668		rt = ipforward_rt.ro_rt;
1669
1670	/*
1671	 * Save the IP header and at most 8 bytes of the payload,
1672	 * in case we need to generate an ICMP message to the src.
1673	 *
1674	 * XXX this can be optimized a lot by saving the data in a local
1675	 * buffer on the stack (72 bytes at most), and only allocating the
1676	 * mbuf if really necessary. The vast majority of the packets
1677	 * are forwarded without having to send an ICMP back (either
1678	 * because unnecessary, or because rate limited), so we are
1679	 * really we are wasting a lot of work here.
1680	 *
1681	 * We don't use m_copy() because it might return a reference
1682	 * to a shared cluster. Both this function and ip_output()
1683	 * assume exclusive access to the IP header in `m', so any
1684	 * data in a cluster may change before we reach icmp_error().
1685	 */
1686	MGET(mcopy, M_DONTWAIT, m->m_type);
1687	if (mcopy != NULL) {
1688		M_COPY_PKTHDR(mcopy, m);
1689		mcopy->m_len = imin((IP_VHL_HL(ip->ip_vhl) << 2) + 8,
1690		    (int)ip->ip_len);
1691		m_copydata(m, 0, mcopy->m_len, mtod(mcopy, caddr_t));
1692#ifdef MAC
1693		/*
1694		 * XXXMAC: This will eventually become an explicit
1695		 * labeling point.
1696		 */
1697		mac_create_mbuf_from_mbuf(m, mcopy);
1698#endif
1699	}
1700
1701#ifdef IPSTEALTH
1702	if (!ipstealth) {
1703#endif
1704		ip->ip_ttl -= IPTTLDEC;
1705#ifdef IPSTEALTH
1706	}
1707#endif
1708
1709	/*
1710	 * If forwarding packet using same interface that it came in on,
1711	 * perhaps should send a redirect to sender to shortcut a hop.
1712	 * Only send redirect if source is sending directly to us,
1713	 * and if packet was not source routed (or has any options).
1714	 * Also, don't send redirect if forwarding using a default route
1715	 * or a route modified by a redirect.
1716	 */
1717	if (rt->rt_ifp == m->m_pkthdr.rcvif &&
1718	    (rt->rt_flags & (RTF_DYNAMIC|RTF_MODIFIED)) == 0 &&
1719	    satosin(rt_key(rt))->sin_addr.s_addr != 0 &&
1720	    ipsendredirects && !srcrt && !next_hop) {
1721#define	RTA(rt)	((struct in_ifaddr *)(rt->rt_ifa))
1722		u_long src = ntohl(ip->ip_src.s_addr);
1723
1724		if (RTA(rt) &&
1725		    (src & RTA(rt)->ia_subnetmask) == RTA(rt)->ia_subnet) {
1726		    if (rt->rt_flags & RTF_GATEWAY)
1727			dest = satosin(rt->rt_gateway)->sin_addr.s_addr;
1728		    else
1729			dest = pkt_dst.s_addr;
1730		    /* Router requirements says to only send host redirects */
1731		    type = ICMP_REDIRECT;
1732		    code = ICMP_REDIRECT_HOST;
1733#ifdef DIAGNOSTIC
1734		    if (ipprintfs)
1735		        printf("redirect (%d) to %lx\n", code, (u_long)dest);
1736#endif
1737		}
1738	}
1739
1740    {
1741	struct m_hdr tag;
1742
1743	if (next_hop) {
1744		/* Pass IPFORWARD info if available */
1745
1746		tag.mh_type = MT_TAG;
1747		tag.mh_flags = PACKET_TAG_IPFORWARD;
1748		tag.mh_data = (caddr_t)next_hop;
1749		tag.mh_next = m;
1750		m = (struct mbuf *)&tag;
1751	}
1752	error = ip_output(m, (struct mbuf *)0, &ipforward_rt,
1753			  IP_FORWARDING, 0, NULL);
1754    }
1755	if (error)
1756		ipstat.ips_cantforward++;
1757	else {
1758		ipstat.ips_forward++;
1759		if (type)
1760			ipstat.ips_redirectsent++;
1761		else {
1762			if (mcopy) {
1763				ipflow_create(&ipforward_rt, mcopy);
1764				m_freem(mcopy);
1765			}
1766			return;
1767		}
1768	}
1769	if (mcopy == NULL)
1770		return;
1771	destifp = NULL;
1772
1773	switch (error) {
1774
1775	case 0:				/* forwarded, but need redirect */
1776		/* type, code set above */
1777		break;
1778
1779	case ENETUNREACH:		/* shouldn't happen, checked above */
1780	case EHOSTUNREACH:
1781	case ENETDOWN:
1782	case EHOSTDOWN:
1783	default:
1784		type = ICMP_UNREACH;
1785		code = ICMP_UNREACH_HOST;
1786		break;
1787
1788	case EMSGSIZE:
1789		type = ICMP_UNREACH;
1790		code = ICMP_UNREACH_NEEDFRAG;
1791#ifdef IPSEC
1792		/*
1793		 * If the packet is routed over IPsec tunnel, tell the
1794		 * originator the tunnel MTU.
1795		 *	tunnel MTU = if MTU - sizeof(IP) - ESP/AH hdrsiz
1796		 * XXX quickhack!!!
1797		 */
1798		if (ipforward_rt.ro_rt) {
1799			struct secpolicy *sp = NULL;
1800			int ipsecerror;
1801			int ipsechdr;
1802			struct route *ro;
1803
1804			sp = ipsec4_getpolicybyaddr(mcopy,
1805						    IPSEC_DIR_OUTBOUND,
1806			                            IP_FORWARDING,
1807			                            &ipsecerror);
1808
1809			if (sp == NULL)
1810				destifp = ipforward_rt.ro_rt->rt_ifp;
1811			else {
1812				/* count IPsec header size */
1813				ipsechdr = ipsec4_hdrsiz(mcopy,
1814							 IPSEC_DIR_OUTBOUND,
1815							 NULL);
1816
1817				/*
1818				 * find the correct route for outer IPv4
1819				 * header, compute tunnel MTU.
1820				 *
1821				 * XXX BUG ALERT
1822				 * The "dummyifp" code relies upon the fact
1823				 * that icmp_error() touches only ifp->if_mtu.
1824				 */
1825				/*XXX*/
1826				destifp = NULL;
1827				if (sp->req != NULL
1828				 && sp->req->sav != NULL
1829				 && sp->req->sav->sah != NULL) {
1830					ro = &sp->req->sav->sah->sa_route;
1831					if (ro->ro_rt && ro->ro_rt->rt_ifp) {
1832						dummyifp.if_mtu =
1833						    ro->ro_rt->rt_ifp->if_mtu;
1834						dummyifp.if_mtu -= ipsechdr;
1835						destifp = &dummyifp;
1836					}
1837				}
1838
1839				key_freesp(sp);
1840			}
1841		}
1842#else
1843		if (ipforward_rt.ro_rt)
1844			destifp = ipforward_rt.ro_rt->rt_ifp;
1845#endif /*IPSEC*/
1846		ipstat.ips_cantfrag++;
1847		break;
1848
1849	case ENOBUFS:
1850		type = ICMP_SOURCEQUENCH;
1851		code = 0;
1852		break;
1853
1854	case EACCES:			/* ipfw denied packet */
1855		m_freem(mcopy);
1856		return;
1857	}
1858	icmp_error(mcopy, type, code, dest, destifp);
1859}
1860
1861void
1862ip_savecontrol(inp, mp, ip, m)
1863	register struct inpcb *inp;
1864	register struct mbuf **mp;
1865	register struct ip *ip;
1866	register struct mbuf *m;
1867{
1868	if (inp->inp_socket->so_options & SO_TIMESTAMP) {
1869		struct timeval tv;
1870
1871		microtime(&tv);
1872		*mp = sbcreatecontrol((caddr_t) &tv, sizeof(tv),
1873			SCM_TIMESTAMP, SOL_SOCKET);
1874		if (*mp)
1875			mp = &(*mp)->m_next;
1876	}
1877	if (inp->inp_flags & INP_RECVDSTADDR) {
1878		*mp = sbcreatecontrol((caddr_t) &ip->ip_dst,
1879		    sizeof(struct in_addr), IP_RECVDSTADDR, IPPROTO_IP);
1880		if (*mp)
1881			mp = &(*mp)->m_next;
1882	}
1883#ifdef notyet
1884	/* XXX
1885	 * Moving these out of udp_input() made them even more broken
1886	 * than they already were.
1887	 */
1888	/* options were tossed already */
1889	if (inp->inp_flags & INP_RECVOPTS) {
1890		*mp = sbcreatecontrol((caddr_t) opts_deleted_above,
1891		    sizeof(struct in_addr), IP_RECVOPTS, IPPROTO_IP);
1892		if (*mp)
1893			mp = &(*mp)->m_next;
1894	}
1895	/* ip_srcroute doesn't do what we want here, need to fix */
1896	if (inp->inp_flags & INP_RECVRETOPTS) {
1897		*mp = sbcreatecontrol((caddr_t) ip_srcroute(),
1898		    sizeof(struct in_addr), IP_RECVRETOPTS, IPPROTO_IP);
1899		if (*mp)
1900			mp = &(*mp)->m_next;
1901	}
1902#endif
1903	if (inp->inp_flags & INP_RECVIF) {
1904		struct ifnet *ifp;
1905		struct sdlbuf {
1906			struct sockaddr_dl sdl;
1907			u_char	pad[32];
1908		} sdlbuf;
1909		struct sockaddr_dl *sdp;
1910		struct sockaddr_dl *sdl2 = &sdlbuf.sdl;
1911
1912		if (((ifp = m->m_pkthdr.rcvif))
1913		&& ( ifp->if_index && (ifp->if_index <= if_index))) {
1914			sdp = (struct sockaddr_dl *)
1915			    (ifaddr_byindex(ifp->if_index)->ifa_addr);
1916			/*
1917			 * Change our mind and don't try copy.
1918			 */
1919			if ((sdp->sdl_family != AF_LINK)
1920			|| (sdp->sdl_len > sizeof(sdlbuf))) {
1921				goto makedummy;
1922			}
1923			bcopy(sdp, sdl2, sdp->sdl_len);
1924		} else {
1925makedummy:
1926			sdl2->sdl_len
1927				= offsetof(struct sockaddr_dl, sdl_data[0]);
1928			sdl2->sdl_family = AF_LINK;
1929			sdl2->sdl_index = 0;
1930			sdl2->sdl_nlen = sdl2->sdl_alen = sdl2->sdl_slen = 0;
1931		}
1932		*mp = sbcreatecontrol((caddr_t) sdl2, sdl2->sdl_len,
1933			IP_RECVIF, IPPROTO_IP);
1934		if (*mp)
1935			mp = &(*mp)->m_next;
1936	}
1937}
1938
1939/*
1940 * XXX these routines are called from the upper part of the kernel.
1941 * They need to be locked when we remove Giant.
1942 *
1943 * They could also be moved to ip_mroute.c, since all the RSVP
1944 *  handling is done there already.
1945 */
1946static int ip_rsvp_on;
1947struct socket *ip_rsvpd;
1948int
1949ip_rsvp_init(struct socket *so)
1950{
1951	if (so->so_type != SOCK_RAW ||
1952	    so->so_proto->pr_protocol != IPPROTO_RSVP)
1953	  return EOPNOTSUPP;
1954
1955	if (ip_rsvpd != NULL)
1956	  return EADDRINUSE;
1957
1958	ip_rsvpd = so;
1959	/*
1960	 * This may seem silly, but we need to be sure we don't over-increment
1961	 * the RSVP counter, in case something slips up.
1962	 */
1963	if (!ip_rsvp_on) {
1964		ip_rsvp_on = 1;
1965		rsvp_on++;
1966	}
1967
1968	return 0;
1969}
1970
1971int
1972ip_rsvp_done(void)
1973{
1974	ip_rsvpd = NULL;
1975	/*
1976	 * This may seem silly, but we need to be sure we don't over-decrement
1977	 * the RSVP counter, in case something slips up.
1978	 */
1979	if (ip_rsvp_on) {
1980		ip_rsvp_on = 0;
1981		rsvp_on--;
1982	}
1983	return 0;
1984}
1985