ip_reass.c revision 135275
1/*
2 * Copyright (c) 1982, 1986, 1988, 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 * 4. Neither the name of the University nor the names of its contributors
14 *    may be used to endorse or promote products derived from this software
15 *    without specific prior written permission.
16 *
17 * THIS SOFTWARE IS PROVIDED BY THE REGENTS AND CONTRIBUTORS ``AS IS'' AND
18 * ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
19 * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE
20 * ARE DISCLAIMED.  IN NO EVENT SHALL THE REGENTS OR CONTRIBUTORS BE LIABLE
21 * FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL
22 * DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS
23 * OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION)
24 * HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT
25 * LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY
26 * OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF
27 * SUCH DAMAGE.
28 *
29 *	@(#)ip_input.c	8.2 (Berkeley) 1/4/94
30 * $FreeBSD: head/sys/netinet/ip_input.c 135275 2004-09-15 20:17:03Z andre $
31 */
32
33#include "opt_bootp.h"
34#include "opt_ipfw.h"
35#include "opt_ipstealth.h"
36#include "opt_ipsec.h"
37#include "opt_mac.h"
38
39#include <sys/param.h>
40#include <sys/systm.h>
41#include <sys/mac.h>
42#include <sys/mbuf.h>
43#include <sys/malloc.h>
44#include <sys/domain.h>
45#include <sys/protosw.h>
46#include <sys/socket.h>
47#include <sys/time.h>
48#include <sys/kernel.h>
49#include <sys/syslog.h>
50#include <sys/sysctl.h>
51
52#include <net/pfil.h>
53#include <net/if.h>
54#include <net/if_types.h>
55#include <net/if_var.h>
56#include <net/if_dl.h>
57#include <net/route.h>
58#include <net/netisr.h>
59
60#include <netinet/in.h>
61#include <netinet/in_systm.h>
62#include <netinet/in_var.h>
63#include <netinet/ip.h>
64#include <netinet/in_pcb.h>
65#include <netinet/ip_var.h>
66#include <netinet/ip_icmp.h>
67#include <machine/in_cksum.h>
68
69#include <sys/socketvar.h>
70
71/* XXX: Temporary until ipfw_ether and ipfw_bridge are converted. */
72#include <netinet/ip_fw.h>
73#include <netinet/ip_dummynet.h>
74
75#ifdef IPSEC
76#include <netinet6/ipsec.h>
77#include <netkey/key.h>
78#endif
79
80#ifdef FAST_IPSEC
81#include <netipsec/ipsec.h>
82#include <netipsec/key.h>
83#endif
84
85int rsvp_on = 0;
86
87int	ipforwarding = 0;
88SYSCTL_INT(_net_inet_ip, IPCTL_FORWARDING, forwarding, CTLFLAG_RW,
89    &ipforwarding, 0, "Enable IP forwarding between interfaces");
90
91static int	ipsendredirects = 1; /* XXX */
92SYSCTL_INT(_net_inet_ip, IPCTL_SENDREDIRECTS, redirect, CTLFLAG_RW,
93    &ipsendredirects, 0, "Enable sending IP redirects");
94
95int	ip_defttl = IPDEFTTL;
96SYSCTL_INT(_net_inet_ip, IPCTL_DEFTTL, ttl, CTLFLAG_RW,
97    &ip_defttl, 0, "Maximum TTL on IP packets");
98
99static int	ip_dosourceroute = 0;
100SYSCTL_INT(_net_inet_ip, IPCTL_SOURCEROUTE, sourceroute, CTLFLAG_RW,
101    &ip_dosourceroute, 0, "Enable forwarding source routed IP packets");
102
103static int	ip_acceptsourceroute = 0;
104SYSCTL_INT(_net_inet_ip, IPCTL_ACCEPTSOURCEROUTE, accept_sourceroute,
105    CTLFLAG_RW, &ip_acceptsourceroute, 0,
106    "Enable accepting source routed IP packets");
107
108int		ip_doopts = 1;	/* 0 = ignore, 1 = process, 2 = reject */
109SYSCTL_INT(_net_inet_ip, OID_AUTO, process_options, CTLFLAG_RW,
110    &ip_doopts, 0, "Enable IP options processing ([LS]SRR, RR, TS)");
111
112static int	ip_keepfaith = 0;
113SYSCTL_INT(_net_inet_ip, IPCTL_KEEPFAITH, keepfaith, CTLFLAG_RW,
114	&ip_keepfaith,	0,
115	"Enable packet capture for FAITH IPv4->IPv6 translater daemon");
116
117static int    nipq = 0;         /* total # of reass queues */
118static int    maxnipq;
119SYSCTL_INT(_net_inet_ip, OID_AUTO, maxfragpackets, CTLFLAG_RW,
120	&maxnipq, 0,
121	"Maximum number of IPv4 fragment reassembly queue entries");
122
123static int    maxfragsperpacket;
124SYSCTL_INT(_net_inet_ip, OID_AUTO, maxfragsperpacket, CTLFLAG_RW,
125	&maxfragsperpacket, 0,
126	"Maximum number of IPv4 fragments allowed per packet");
127
128static int	ip_sendsourcequench = 0;
129SYSCTL_INT(_net_inet_ip, OID_AUTO, sendsourcequench, CTLFLAG_RW,
130	&ip_sendsourcequench, 0,
131	"Enable the transmission of source quench packets");
132
133int	ip_do_randomid = 0;
134SYSCTL_INT(_net_inet_ip, OID_AUTO, random_id, CTLFLAG_RW,
135	&ip_do_randomid, 0,
136	"Assign random ip_id values");
137
138/*
139 * XXX - Setting ip_checkinterface mostly implements the receive side of
140 * the Strong ES model described in RFC 1122, but since the routing table
141 * and transmit implementation do not implement the Strong ES model,
142 * setting this to 1 results in an odd hybrid.
143 *
144 * XXX - ip_checkinterface currently must be disabled if you use ipnat
145 * to translate the destination address to another local interface.
146 *
147 * XXX - ip_checkinterface must be disabled if you add IP aliases
148 * to the loopback interface instead of the interface where the
149 * packets for those addresses are received.
150 */
151static int	ip_checkinterface = 1;
152SYSCTL_INT(_net_inet_ip, OID_AUTO, check_interface, CTLFLAG_RW,
153    &ip_checkinterface, 0, "Verify packet arrives on correct interface");
154
155#ifdef DIAGNOSTIC
156static int	ipprintfs = 0;
157#endif
158
159struct pfil_head inet_pfil_hook;	/* Packet filter hooks */
160
161static struct	ifqueue ipintrq;
162static int	ipqmaxlen = IFQ_MAXLEN;
163
164extern	struct domain inetdomain;
165extern	struct protosw inetsw[];
166u_char	ip_protox[IPPROTO_MAX];
167struct	in_ifaddrhead in_ifaddrhead; 		/* first inet address */
168struct	in_ifaddrhashhead *in_ifaddrhashtbl;	/* inet addr hash table  */
169u_long 	in_ifaddrhmask;				/* mask for hash table */
170
171SYSCTL_INT(_net_inet_ip, IPCTL_INTRQMAXLEN, intr_queue_maxlen, CTLFLAG_RW,
172    &ipintrq.ifq_maxlen, 0, "Maximum size of the IP input queue");
173SYSCTL_INT(_net_inet_ip, IPCTL_INTRQDROPS, intr_queue_drops, CTLFLAG_RD,
174    &ipintrq.ifq_drops, 0, "Number of packets dropped from the IP input queue");
175
176struct ipstat ipstat;
177SYSCTL_STRUCT(_net_inet_ip, IPCTL_STATS, stats, CTLFLAG_RW,
178    &ipstat, ipstat, "IP statistics (struct ipstat, netinet/ip_var.h)");
179
180/* Packet reassembly stuff */
181#define IPREASS_NHASH_LOG2      6
182#define IPREASS_NHASH           (1 << IPREASS_NHASH_LOG2)
183#define IPREASS_HMASK           (IPREASS_NHASH - 1)
184#define IPREASS_HASH(x,y) \
185	(((((x) & 0xF) | ((((x) >> 8) & 0xF) << 4)) ^ (y)) & IPREASS_HMASK)
186
187static TAILQ_HEAD(ipqhead, ipq) ipq[IPREASS_NHASH];
188struct mtx ipqlock;
189
190#define	IPQ_LOCK()	mtx_lock(&ipqlock)
191#define	IPQ_UNLOCK()	mtx_unlock(&ipqlock)
192#define	IPQ_LOCK_INIT()	mtx_init(&ipqlock, "ipqlock", NULL, MTX_DEF)
193#define	IPQ_LOCK_ASSERT()	mtx_assert(&ipqlock, MA_OWNED)
194
195#ifdef IPCTL_DEFMTU
196SYSCTL_INT(_net_inet_ip, IPCTL_DEFMTU, mtu, CTLFLAG_RW,
197    &ip_mtu, 0, "Default MTU");
198#endif
199
200#ifdef IPSTEALTH
201int	ipstealth = 0;
202SYSCTL_INT(_net_inet_ip, OID_AUTO, stealth, CTLFLAG_RW,
203    &ipstealth, 0, "");
204#endif
205
206/*
207 * ipfw_ether and ipfw_bridge hooks.
208 * XXX: Temporary until those are converted to pfil_hooks as well.
209 */
210ip_fw_chk_t *ip_fw_chk_ptr = NULL;
211ip_dn_io_t *ip_dn_io_ptr = NULL;
212int fw_enable = 1;
213int fw_one_pass = 1;
214
215/*
216 * XXX this is ugly.  IP options source routing magic.
217 */
218struct ipoptrt {
219	struct	in_addr dst;			/* final destination */
220	char	nop;				/* one NOP to align */
221	char	srcopt[IPOPT_OFFSET + 1];	/* OPTVAL, OLEN and OFFSET */
222	struct	in_addr route[MAX_IPOPTLEN/sizeof(struct in_addr)];
223};
224
225struct ipopt_tag {
226	struct	m_tag tag;
227	int	ip_nhops;
228	struct	ipoptrt ip_srcrt;
229};
230
231static void	save_rte(struct mbuf *, u_char *, struct in_addr);
232static int	ip_dooptions(struct mbuf *m, int);
233static void	ip_forward(struct mbuf *m, int srcrt);
234static void	ip_freef(struct ipqhead *, struct ipq *);
235
236/*
237 * IP initialization: fill in IP protocol switch table.
238 * All protocols not implemented in kernel go to raw IP protocol handler.
239 */
240void
241ip_init()
242{
243	register struct protosw *pr;
244	register int i;
245
246	TAILQ_INIT(&in_ifaddrhead);
247	in_ifaddrhashtbl = hashinit(INADDR_NHASH, M_IFADDR, &in_ifaddrhmask);
248	pr = pffindproto(PF_INET, IPPROTO_RAW, SOCK_RAW);
249	if (pr == 0)
250		panic("ip_init");
251	for (i = 0; i < IPPROTO_MAX; i++)
252		ip_protox[i] = pr - inetsw;
253	for (pr = inetdomain.dom_protosw;
254	    pr < inetdomain.dom_protoswNPROTOSW; pr++)
255		if (pr->pr_domain->dom_family == PF_INET &&
256		    pr->pr_protocol && pr->pr_protocol != IPPROTO_RAW)
257			ip_protox[pr->pr_protocol] = pr - inetsw;
258
259	/* Initialize packet filter hooks. */
260	inet_pfil_hook.ph_type = PFIL_TYPE_AF;
261	inet_pfil_hook.ph_af = AF_INET;
262	if ((i = pfil_head_register(&inet_pfil_hook)) != 0)
263		printf("%s: WARNING: unable to register pfil hook, "
264			"error %d\n", __func__, i);
265
266	IPQ_LOCK_INIT();
267	for (i = 0; i < IPREASS_NHASH; i++)
268	    TAILQ_INIT(&ipq[i]);
269
270	maxnipq = nmbclusters / 32;
271	maxfragsperpacket = 16;
272
273	ip_id = time_second & 0xffff;
274	ipintrq.ifq_maxlen = ipqmaxlen;
275	mtx_init(&ipintrq.ifq_mtx, "ip_inq", NULL, MTX_DEF);
276	netisr_register(NETISR_IP, ip_input, &ipintrq, NETISR_MPSAFE);
277}
278
279/*
280 * Ip input routine.  Checksum and byte swap header.  If fragmented
281 * try to reassemble.  Process options.  Pass to next level.
282 */
283void
284ip_input(struct mbuf *m)
285{
286	struct ip *ip = NULL;
287	struct in_ifaddr *ia = NULL;
288	struct ifaddr *ifa;
289	int    checkif, hlen = 0;
290	u_short sum;
291	int dchg = 0;				/* dest changed after fw */
292	struct in_addr odst;			/* original dst address */
293#ifdef FAST_IPSEC
294	struct m_tag *mtag;
295	struct tdb_ident *tdbi;
296	struct secpolicy *sp;
297	int s, error;
298#endif /* FAST_IPSEC */
299
300  	M_ASSERTPKTHDR(m);
301
302	if (m->m_flags & M_FASTFWD_OURS) {
303		/*
304		 * Firewall or NAT changed destination to local.
305		 * We expect ip_len and ip_off to be in host byte order.
306		 */
307		m->m_flags &= ~M_FASTFWD_OURS;
308		/* Set up some basics that will be used later. */
309		ip = mtod(m, struct ip *);
310		hlen = ip->ip_hl << 2;
311  		goto ours;
312  	}
313
314	ipstat.ips_total++;
315
316	if (m->m_pkthdr.len < sizeof(struct ip))
317		goto tooshort;
318
319	if (m->m_len < sizeof (struct ip) &&
320	    (m = m_pullup(m, sizeof (struct ip))) == NULL) {
321		ipstat.ips_toosmall++;
322		return;
323	}
324	ip = mtod(m, struct ip *);
325
326	if (ip->ip_v != IPVERSION) {
327		ipstat.ips_badvers++;
328		goto bad;
329	}
330
331	hlen = ip->ip_hl << 2;
332	if (hlen < sizeof(struct ip)) {	/* minimum header length */
333		ipstat.ips_badhlen++;
334		goto bad;
335	}
336	if (hlen > m->m_len) {
337		if ((m = m_pullup(m, hlen)) == NULL) {
338			ipstat.ips_badhlen++;
339			return;
340		}
341		ip = mtod(m, struct ip *);
342	}
343
344	/* 127/8 must not appear on wire - RFC1122 */
345	if ((ntohl(ip->ip_dst.s_addr) >> IN_CLASSA_NSHIFT) == IN_LOOPBACKNET ||
346	    (ntohl(ip->ip_src.s_addr) >> IN_CLASSA_NSHIFT) == IN_LOOPBACKNET) {
347		if ((m->m_pkthdr.rcvif->if_flags & IFF_LOOPBACK) == 0) {
348			ipstat.ips_badaddr++;
349			goto bad;
350		}
351	}
352
353	if (m->m_pkthdr.csum_flags & CSUM_IP_CHECKED) {
354		sum = !(m->m_pkthdr.csum_flags & CSUM_IP_VALID);
355	} else {
356		if (hlen == sizeof(struct ip)) {
357			sum = in_cksum_hdr(ip);
358		} else {
359			sum = in_cksum(m, hlen);
360		}
361	}
362	if (sum) {
363		ipstat.ips_badsum++;
364		goto bad;
365	}
366
367#ifdef ALTQ
368	if (altq_input != NULL && (*altq_input)(m, AF_INET) == 0)
369		/* packet is dropped by traffic conditioner */
370		return;
371#endif
372
373	/*
374	 * Convert fields to host representation.
375	 */
376	ip->ip_len = ntohs(ip->ip_len);
377	if (ip->ip_len < hlen) {
378		ipstat.ips_badlen++;
379		goto bad;
380	}
381	ip->ip_off = ntohs(ip->ip_off);
382
383	/*
384	 * Check that the amount of data in the buffers
385	 * is as at least much as the IP header would have us expect.
386	 * Trim mbufs if longer than we expect.
387	 * Drop packet if shorter than we expect.
388	 */
389	if (m->m_pkthdr.len < ip->ip_len) {
390tooshort:
391		ipstat.ips_tooshort++;
392		goto bad;
393	}
394	if (m->m_pkthdr.len > ip->ip_len) {
395		if (m->m_len == m->m_pkthdr.len) {
396			m->m_len = ip->ip_len;
397			m->m_pkthdr.len = ip->ip_len;
398		} else
399			m_adj(m, ip->ip_len - m->m_pkthdr.len);
400	}
401#if defined(IPSEC) && !defined(IPSEC_FILTERGIF)
402	/*
403	 * Bypass packet filtering for packets from a tunnel (gif).
404	 */
405	if (ipsec_getnhist(m))
406		goto passin;
407#endif
408#if defined(FAST_IPSEC) && !defined(IPSEC_FILTERGIF)
409	/*
410	 * Bypass packet filtering for packets from a tunnel (gif).
411	 */
412	if (m_tag_find(m, PACKET_TAG_IPSEC_IN_DONE, NULL) != NULL)
413		goto passin;
414#endif
415
416	/*
417	 * Run through list of hooks for input packets.
418	 *
419	 * NB: Beware of the destination address changing (e.g.
420	 *     by NAT rewriting).  When this happens, tell
421	 *     ip_forward to do the right thing.
422	 */
423
424	/* Jump over all PFIL processing if hooks are not active. */
425	if (inet_pfil_hook.ph_busy_count == -1)
426		goto passin;
427
428	odst = ip->ip_dst;
429	if (pfil_run_hooks(&inet_pfil_hook, &m, m->m_pkthdr.rcvif,
430	    PFIL_IN) != 0)
431		return;
432	if (m == NULL)			/* consumed by filter */
433		return;
434
435	ip = mtod(m, struct ip *);
436	dchg = (odst.s_addr != ip->ip_dst.s_addr);
437
438#ifdef IPFIREWALL_FORWARD
439	if (m->m_flags & M_FASTFWD_OURS) {
440		m->m_flags &= ~M_FASTFWD_OURS;
441		goto ours;
442	}
443	dchg = (m_tag_find(m, PACKET_TAG_IPFORWARD, NULL) != NULL);
444#endif /* IPFIREWALL_FORWARD */
445
446passin:
447	/*
448	 * Process options and, if not destined for us,
449	 * ship it on.  ip_dooptions returns 1 when an
450	 * error was detected (causing an icmp message
451	 * to be sent and the original packet to be freed).
452	 */
453	if (hlen > sizeof (struct ip) && ip_dooptions(m, 0))
454		return;
455
456        /* greedy RSVP, snatches any PATH packet of the RSVP protocol and no
457         * matter if it is destined to another node, or whether it is
458         * a multicast one, RSVP wants it! and prevents it from being forwarded
459         * anywhere else. Also checks if the rsvp daemon is running before
460	 * grabbing the packet.
461         */
462	if (rsvp_on && ip->ip_p==IPPROTO_RSVP)
463		goto ours;
464
465	/*
466	 * Check our list of addresses, to see if the packet is for us.
467	 * If we don't have any addresses, assume any unicast packet
468	 * we receive might be for us (and let the upper layers deal
469	 * with it).
470	 */
471	if (TAILQ_EMPTY(&in_ifaddrhead) &&
472	    (m->m_flags & (M_MCAST|M_BCAST)) == 0)
473		goto ours;
474
475	/*
476	 * Enable a consistency check between the destination address
477	 * and the arrival interface for a unicast packet (the RFC 1122
478	 * strong ES model) if IP forwarding is disabled and the packet
479	 * is not locally generated and the packet is not subject to
480	 * 'ipfw fwd'.
481	 *
482	 * XXX - Checking also should be disabled if the destination
483	 * address is ipnat'ed to a different interface.
484	 *
485	 * XXX - Checking is incompatible with IP aliases added
486	 * to the loopback interface instead of the interface where
487	 * the packets are received.
488	 */
489	checkif = ip_checkinterface && (ipforwarding == 0) &&
490	    m->m_pkthdr.rcvif != NULL &&
491	    ((m->m_pkthdr.rcvif->if_flags & IFF_LOOPBACK) == 0) &&
492	    (dchg == 0);
493
494	/*
495	 * Check for exact addresses in the hash bucket.
496	 */
497	LIST_FOREACH(ia, INADDR_HASH(ip->ip_dst.s_addr), ia_hash) {
498		/*
499		 * If the address matches, verify that the packet
500		 * arrived via the correct interface if checking is
501		 * enabled.
502		 */
503		if (IA_SIN(ia)->sin_addr.s_addr == ip->ip_dst.s_addr &&
504		    (!checkif || ia->ia_ifp == m->m_pkthdr.rcvif))
505			goto ours;
506	}
507	/*
508	 * Check for broadcast addresses.
509	 *
510	 * Only accept broadcast packets that arrive via the matching
511	 * interface.  Reception of forwarded directed broadcasts would
512	 * be handled via ip_forward() and ether_output() with the loopback
513	 * into the stack for SIMPLEX interfaces handled by ether_output().
514	 */
515	if (m->m_pkthdr.rcvif != NULL &&
516	    m->m_pkthdr.rcvif->if_flags & IFF_BROADCAST) {
517	        TAILQ_FOREACH(ifa, &m->m_pkthdr.rcvif->if_addrhead, ifa_link) {
518			if (ifa->ifa_addr->sa_family != AF_INET)
519				continue;
520			ia = ifatoia(ifa);
521			if (satosin(&ia->ia_broadaddr)->sin_addr.s_addr ==
522			    ip->ip_dst.s_addr)
523				goto ours;
524			if (ia->ia_netbroadcast.s_addr == ip->ip_dst.s_addr)
525				goto ours;
526#ifdef BOOTP_COMPAT
527			if (IA_SIN(ia)->sin_addr.s_addr == INADDR_ANY)
528				goto ours;
529#endif
530		}
531	}
532	if (IN_MULTICAST(ntohl(ip->ip_dst.s_addr))) {
533		struct in_multi *inm;
534		if (ip_mrouter) {
535			/*
536			 * If we are acting as a multicast router, all
537			 * incoming multicast packets are passed to the
538			 * kernel-level multicast forwarding function.
539			 * The packet is returned (relatively) intact; if
540			 * ip_mforward() returns a non-zero value, the packet
541			 * must be discarded, else it may be accepted below.
542			 */
543			if (ip_mforward &&
544			    ip_mforward(ip, m->m_pkthdr.rcvif, m, 0) != 0) {
545				ipstat.ips_cantforward++;
546				m_freem(m);
547				return;
548			}
549
550			/*
551			 * The process-level routing daemon needs to receive
552			 * all multicast IGMP packets, whether or not this
553			 * host belongs to their destination groups.
554			 */
555			if (ip->ip_p == IPPROTO_IGMP)
556				goto ours;
557			ipstat.ips_forward++;
558		}
559		/*
560		 * See if we belong to the destination multicast group on the
561		 * arrival interface.
562		 */
563		IN_LOOKUP_MULTI(ip->ip_dst, m->m_pkthdr.rcvif, inm);
564		if (inm == NULL) {
565			ipstat.ips_notmember++;
566			m_freem(m);
567			return;
568		}
569		goto ours;
570	}
571	if (ip->ip_dst.s_addr == (u_long)INADDR_BROADCAST)
572		goto ours;
573	if (ip->ip_dst.s_addr == INADDR_ANY)
574		goto ours;
575
576	/*
577	 * FAITH(Firewall Aided Internet Translator)
578	 */
579	if (m->m_pkthdr.rcvif && m->m_pkthdr.rcvif->if_type == IFT_FAITH) {
580		if (ip_keepfaith) {
581			if (ip->ip_p == IPPROTO_TCP || ip->ip_p == IPPROTO_ICMP)
582				goto ours;
583		}
584		m_freem(m);
585		return;
586	}
587
588	/*
589	 * Not for us; forward if possible and desirable.
590	 */
591	if (ipforwarding == 0) {
592		ipstat.ips_cantforward++;
593		m_freem(m);
594	} else {
595#ifdef IPSEC
596		/*
597		 * Enforce inbound IPsec SPD.
598		 */
599		if (ipsec4_in_reject(m, NULL)) {
600			ipsecstat.in_polvio++;
601			goto bad;
602		}
603#endif /* IPSEC */
604#ifdef FAST_IPSEC
605		mtag = m_tag_find(m, PACKET_TAG_IPSEC_IN_DONE, NULL);
606		s = splnet();
607		if (mtag != NULL) {
608			tdbi = (struct tdb_ident *)(mtag + 1);
609			sp = ipsec_getpolicy(tdbi, IPSEC_DIR_INBOUND);
610		} else {
611			sp = ipsec_getpolicybyaddr(m, IPSEC_DIR_INBOUND,
612						   IP_FORWARDING, &error);
613		}
614		if (sp == NULL) {	/* NB: can happen if error */
615			splx(s);
616			/*XXX error stat???*/
617			DPRINTF(("ip_input: no SP for forwarding\n"));	/*XXX*/
618			goto bad;
619		}
620
621		/*
622		 * Check security policy against packet attributes.
623		 */
624		error = ipsec_in_reject(sp, m);
625		KEY_FREESP(&sp);
626		splx(s);
627		if (error) {
628			ipstat.ips_cantforward++;
629			goto bad;
630		}
631#endif /* FAST_IPSEC */
632		ip_forward(m, dchg);
633	}
634	return;
635
636ours:
637#ifdef IPSTEALTH
638	/*
639	 * IPSTEALTH: Process non-routing options only
640	 * if the packet is destined for us.
641	 */
642	if (ipstealth && hlen > sizeof (struct ip) &&
643	    ip_dooptions(m, 1))
644		return;
645#endif /* IPSTEALTH */
646
647	/* Count the packet in the ip address stats */
648	if (ia != NULL) {
649		ia->ia_ifa.if_ipackets++;
650		ia->ia_ifa.if_ibytes += m->m_pkthdr.len;
651	}
652
653	/*
654	 * Attempt reassembly; if it succeeds, proceed.
655	 * ip_reass() will return a different mbuf.
656	 */
657	if (ip->ip_off & (IP_MF | IP_OFFMASK)) {
658		m = ip_reass(m);
659		if (m == NULL)
660			return;
661		ip = mtod(m, struct ip *);
662		/* Get the header length of the reassembled packet */
663		hlen = ip->ip_hl << 2;
664	}
665
666	/*
667	 * Further protocols expect the packet length to be w/o the
668	 * IP header.
669	 */
670	ip->ip_len -= hlen;
671
672#ifdef IPSEC
673	/*
674	 * enforce IPsec policy checking if we are seeing last header.
675	 * note that we do not visit this with protocols with pcb layer
676	 * code - like udp/tcp/raw ip.
677	 */
678	if ((inetsw[ip_protox[ip->ip_p]].pr_flags & PR_LASTHDR) != 0 &&
679	    ipsec4_in_reject(m, NULL)) {
680		ipsecstat.in_polvio++;
681		goto bad;
682	}
683#endif
684#if FAST_IPSEC
685	/*
686	 * enforce IPsec policy checking if we are seeing last header.
687	 * note that we do not visit this with protocols with pcb layer
688	 * code - like udp/tcp/raw ip.
689	 */
690	if ((inetsw[ip_protox[ip->ip_p]].pr_flags & PR_LASTHDR) != 0) {
691		/*
692		 * Check if the packet has already had IPsec processing
693		 * done.  If so, then just pass it along.  This tag gets
694		 * set during AH, ESP, etc. input handling, before the
695		 * packet is returned to the ip input queue for delivery.
696		 */
697		mtag = m_tag_find(m, PACKET_TAG_IPSEC_IN_DONE, NULL);
698		s = splnet();
699		if (mtag != NULL) {
700			tdbi = (struct tdb_ident *)(mtag + 1);
701			sp = ipsec_getpolicy(tdbi, IPSEC_DIR_INBOUND);
702		} else {
703			sp = ipsec_getpolicybyaddr(m, IPSEC_DIR_INBOUND,
704						   IP_FORWARDING, &error);
705		}
706		if (sp != NULL) {
707			/*
708			 * Check security policy against packet attributes.
709			 */
710			error = ipsec_in_reject(sp, m);
711			KEY_FREESP(&sp);
712		} else {
713			/* XXX error stat??? */
714			error = EINVAL;
715DPRINTF(("ip_input: no SP, packet discarded\n"));/*XXX*/
716			goto bad;
717		}
718		splx(s);
719		if (error)
720			goto bad;
721	}
722#endif /* FAST_IPSEC */
723
724	/*
725	 * Switch out to protocol's input routine.
726	 */
727	ipstat.ips_delivered++;
728
729	(*inetsw[ip_protox[ip->ip_p]].pr_input)(m, hlen);
730	return;
731bad:
732	m_freem(m);
733}
734
735/*
736 * Take incoming datagram fragment and try to reassemble it into
737 * whole datagram.  If the argument is the first fragment or one
738 * in between the function will return NULL and store the mbuf
739 * in the fragment chain.  If the argument is the last fragment
740 * the packet will be reassembled and the pointer to the new
741 * mbuf returned for further processing.  Only m_tags attached
742 * to the first packet/fragment are preserved.
743 * The IP header is *NOT* adjusted out of iplen.
744 */
745
746struct mbuf *
747ip_reass(struct mbuf *m)
748{
749	struct ip *ip;
750	struct mbuf *p, *q, *nq, *t;
751	struct ipq *fp = NULL;
752	struct ipqhead *head;
753	int i, hlen, next;
754	u_int8_t ecn, ecn0;
755	u_short hash;
756
757	/* If maxnipq is 0, never accept fragments. */
758	if (maxnipq == 0) {
759		ipstat.ips_fragments++;
760		ipstat.ips_fragdropped++;
761		m_freem(m);
762		return (NULL);
763	}
764
765	ip = mtod(m, struct ip *);
766	hlen = ip->ip_hl << 2;
767
768	hash = IPREASS_HASH(ip->ip_src.s_addr, ip->ip_id);
769	head = &ipq[hash];
770	IPQ_LOCK();
771
772	/*
773	 * Look for queue of fragments
774	 * of this datagram.
775	 */
776	TAILQ_FOREACH(fp, head, ipq_list)
777		if (ip->ip_id == fp->ipq_id &&
778		    ip->ip_src.s_addr == fp->ipq_src.s_addr &&
779		    ip->ip_dst.s_addr == fp->ipq_dst.s_addr &&
780#ifdef MAC
781		    mac_fragment_match(m, fp) &&
782#endif
783		    ip->ip_p == fp->ipq_p)
784			goto found;
785
786	fp = NULL;
787
788	/*
789	 * Enforce upper bound on number of fragmented packets
790	 * for which we attempt reassembly;
791	 * If maxnipq is -1, accept all fragments without limitation.
792	 */
793	if ((nipq > maxnipq) && (maxnipq > 0)) {
794		/*
795		 * drop something from the tail of the current queue
796		 * before proceeding further
797		 */
798		struct ipq *q = TAILQ_LAST(head, ipqhead);
799		if (q == NULL) {   /* gak */
800			for (i = 0; i < IPREASS_NHASH; i++) {
801				struct ipq *r = TAILQ_LAST(&ipq[i], ipqhead);
802				if (r) {
803					ipstat.ips_fragtimeout += r->ipq_nfrags;
804					ip_freef(&ipq[i], r);
805					break;
806				}
807			}
808		} else {
809			ipstat.ips_fragtimeout += q->ipq_nfrags;
810			ip_freef(head, q);
811		}
812	}
813
814found:
815	/*
816	 * Adjust ip_len to not reflect header,
817	 * convert offset of this to bytes.
818	 */
819	ip->ip_len -= hlen;
820	if (ip->ip_off & IP_MF) {
821		/*
822		 * Make sure that fragments have a data length
823		 * that's a non-zero multiple of 8 bytes.
824		 */
825		if (ip->ip_len == 0 || (ip->ip_len & 0x7) != 0) {
826			ipstat.ips_toosmall++; /* XXX */
827			goto dropfrag;
828		}
829		m->m_flags |= M_FRAG;
830	} else
831		m->m_flags &= ~M_FRAG;
832	ip->ip_off <<= 3;
833
834
835	/*
836	 * Attempt reassembly; if it succeeds, proceed.
837	 * ip_reass() will return a different mbuf.
838	 */
839	ipstat.ips_fragments++;
840	m->m_pkthdr.header = ip;
841
842	/* Previous ip_reass() started here. */
843	/*
844	 * Presence of header sizes in mbufs
845	 * would confuse code below.
846	 */
847	m->m_data += hlen;
848	m->m_len -= hlen;
849
850	/*
851	 * If first fragment to arrive, create a reassembly queue.
852	 */
853	if (fp == NULL) {
854		if ((t = m_get(M_DONTWAIT, MT_FTABLE)) == NULL)
855			goto dropfrag;
856		fp = mtod(t, struct ipq *);
857#ifdef MAC
858		if (mac_init_ipq(fp, M_NOWAIT) != 0) {
859			m_free(t);
860			goto dropfrag;
861		}
862		mac_create_ipq(m, fp);
863#endif
864		TAILQ_INSERT_HEAD(head, fp, ipq_list);
865		nipq++;
866		fp->ipq_nfrags = 1;
867		fp->ipq_ttl = IPFRAGTTL;
868		fp->ipq_p = ip->ip_p;
869		fp->ipq_id = ip->ip_id;
870		fp->ipq_src = ip->ip_src;
871		fp->ipq_dst = ip->ip_dst;
872		fp->ipq_frags = m;
873		m->m_nextpkt = NULL;
874		goto inserted;
875	} else {
876		fp->ipq_nfrags++;
877#ifdef MAC
878		mac_update_ipq(m, fp);
879#endif
880	}
881
882#define GETIP(m)	((struct ip*)((m)->m_pkthdr.header))
883
884	/*
885	 * Handle ECN by comparing this segment with the first one;
886	 * if CE is set, do not lose CE.
887	 * drop if CE and not-ECT are mixed for the same packet.
888	 */
889	ecn = ip->ip_tos & IPTOS_ECN_MASK;
890	ecn0 = GETIP(fp->ipq_frags)->ip_tos & IPTOS_ECN_MASK;
891	if (ecn == IPTOS_ECN_CE) {
892		if (ecn0 == IPTOS_ECN_NOTECT)
893			goto dropfrag;
894		if (ecn0 != IPTOS_ECN_CE)
895			GETIP(fp->ipq_frags)->ip_tos |= IPTOS_ECN_CE;
896	}
897	if (ecn == IPTOS_ECN_NOTECT && ecn0 != IPTOS_ECN_NOTECT)
898		goto dropfrag;
899
900	/*
901	 * Find a segment which begins after this one does.
902	 */
903	for (p = NULL, q = fp->ipq_frags; q; p = q, q = q->m_nextpkt)
904		if (GETIP(q)->ip_off > ip->ip_off)
905			break;
906
907	/*
908	 * If there is a preceding segment, it may provide some of
909	 * our data already.  If so, drop the data from the incoming
910	 * segment.  If it provides all of our data, drop us, otherwise
911	 * stick new segment in the proper place.
912	 *
913	 * If some of the data is dropped from the the preceding
914	 * segment, then it's checksum is invalidated.
915	 */
916	if (p) {
917		i = GETIP(p)->ip_off + GETIP(p)->ip_len - ip->ip_off;
918		if (i > 0) {
919			if (i >= ip->ip_len)
920				goto dropfrag;
921			m_adj(m, i);
922			m->m_pkthdr.csum_flags = 0;
923			ip->ip_off += i;
924			ip->ip_len -= i;
925		}
926		m->m_nextpkt = p->m_nextpkt;
927		p->m_nextpkt = m;
928	} else {
929		m->m_nextpkt = fp->ipq_frags;
930		fp->ipq_frags = m;
931	}
932
933	/*
934	 * While we overlap succeeding segments trim them or,
935	 * if they are completely covered, dequeue them.
936	 */
937	for (; q != NULL && ip->ip_off + ip->ip_len > GETIP(q)->ip_off;
938	     q = nq) {
939		i = (ip->ip_off + ip->ip_len) - GETIP(q)->ip_off;
940		if (i < GETIP(q)->ip_len) {
941			GETIP(q)->ip_len -= i;
942			GETIP(q)->ip_off += i;
943			m_adj(q, i);
944			q->m_pkthdr.csum_flags = 0;
945			break;
946		}
947		nq = q->m_nextpkt;
948		m->m_nextpkt = nq;
949		ipstat.ips_fragdropped++;
950		fp->ipq_nfrags--;
951		m_freem(q);
952	}
953
954inserted:
955
956	/*
957	 * Check for complete reassembly and perform frag per packet
958	 * limiting.
959	 *
960	 * Frag limiting is performed here so that the nth frag has
961	 * a chance to complete the packet before we drop the packet.
962	 * As a result, n+1 frags are actually allowed per packet, but
963	 * only n will ever be stored. (n = maxfragsperpacket.)
964	 *
965	 */
966	next = 0;
967	for (p = NULL, q = fp->ipq_frags; q; p = q, q = q->m_nextpkt) {
968		if (GETIP(q)->ip_off != next) {
969			if (fp->ipq_nfrags > maxfragsperpacket) {
970				ipstat.ips_fragdropped += fp->ipq_nfrags;
971				ip_freef(head, fp);
972			}
973			goto done;
974		}
975		next += GETIP(q)->ip_len;
976	}
977	/* Make sure the last packet didn't have the IP_MF flag */
978	if (p->m_flags & M_FRAG) {
979		if (fp->ipq_nfrags > maxfragsperpacket) {
980			ipstat.ips_fragdropped += fp->ipq_nfrags;
981			ip_freef(head, fp);
982		}
983		goto done;
984	}
985
986	/*
987	 * Reassembly is complete.  Make sure the packet is a sane size.
988	 */
989	q = fp->ipq_frags;
990	ip = GETIP(q);
991	if (next + (ip->ip_hl << 2) > IP_MAXPACKET) {
992		ipstat.ips_toolong++;
993		ipstat.ips_fragdropped += fp->ipq_nfrags;
994		ip_freef(head, fp);
995		goto done;
996	}
997
998	/*
999	 * Concatenate fragments.
1000	 */
1001	m = q;
1002	t = m->m_next;
1003	m->m_next = 0;
1004	m_cat(m, t);
1005	nq = q->m_nextpkt;
1006	q->m_nextpkt = 0;
1007	for (q = nq; q != NULL; q = nq) {
1008		nq = q->m_nextpkt;
1009		q->m_nextpkt = NULL;
1010		m->m_pkthdr.csum_flags &= q->m_pkthdr.csum_flags;
1011		m->m_pkthdr.csum_data += q->m_pkthdr.csum_data;
1012		m_cat(m, q);
1013	}
1014#ifdef MAC
1015	mac_create_datagram_from_ipq(fp, m);
1016	mac_destroy_ipq(fp);
1017#endif
1018
1019	/*
1020	 * Create header for new ip packet by modifying header of first
1021	 * packet;  dequeue and discard fragment reassembly header.
1022	 * Make header visible.
1023	 */
1024	ip->ip_len = (ip->ip_hl << 2) + next;
1025	ip->ip_src = fp->ipq_src;
1026	ip->ip_dst = fp->ipq_dst;
1027	TAILQ_REMOVE(head, fp, ipq_list);
1028	nipq--;
1029	(void) m_free(dtom(fp));
1030	m->m_len += (ip->ip_hl << 2);
1031	m->m_data -= (ip->ip_hl << 2);
1032	/* some debugging cruft by sklower, below, will go away soon */
1033	if (m->m_flags & M_PKTHDR)	/* XXX this should be done elsewhere */
1034		m_fixhdr(m);
1035	ipstat.ips_reassembled++;
1036	IPQ_UNLOCK();
1037	return (m);
1038
1039dropfrag:
1040	ipstat.ips_fragdropped++;
1041	if (fp != NULL)
1042		fp->ipq_nfrags--;
1043	m_freem(m);
1044done:
1045	IPQ_UNLOCK();
1046	return (NULL);
1047
1048#undef GETIP
1049}
1050
1051/*
1052 * Free a fragment reassembly header and all
1053 * associated datagrams.
1054 */
1055static void
1056ip_freef(fhp, fp)
1057	struct ipqhead *fhp;
1058	struct ipq *fp;
1059{
1060	register struct mbuf *q;
1061
1062	IPQ_LOCK_ASSERT();
1063
1064	while (fp->ipq_frags) {
1065		q = fp->ipq_frags;
1066		fp->ipq_frags = q->m_nextpkt;
1067		m_freem(q);
1068	}
1069	TAILQ_REMOVE(fhp, fp, ipq_list);
1070	(void) m_free(dtom(fp));
1071	nipq--;
1072}
1073
1074/*
1075 * IP timer processing;
1076 * if a timer expires on a reassembly
1077 * queue, discard it.
1078 */
1079void
1080ip_slowtimo()
1081{
1082	register struct ipq *fp;
1083	int s = splnet();
1084	int i;
1085
1086	IPQ_LOCK();
1087	for (i = 0; i < IPREASS_NHASH; i++) {
1088		for(fp = TAILQ_FIRST(&ipq[i]); fp;) {
1089			struct ipq *fpp;
1090
1091			fpp = fp;
1092			fp = TAILQ_NEXT(fp, ipq_list);
1093			if(--fpp->ipq_ttl == 0) {
1094				ipstat.ips_fragtimeout += fpp->ipq_nfrags;
1095				ip_freef(&ipq[i], fpp);
1096			}
1097		}
1098	}
1099	/*
1100	 * If we are over the maximum number of fragments
1101	 * (due to the limit being lowered), drain off
1102	 * enough to get down to the new limit.
1103	 */
1104	if (maxnipq >= 0 && nipq > maxnipq) {
1105		for (i = 0; i < IPREASS_NHASH; i++) {
1106			while (nipq > maxnipq && !TAILQ_EMPTY(&ipq[i])) {
1107				ipstat.ips_fragdropped +=
1108				    TAILQ_FIRST(&ipq[i])->ipq_nfrags;
1109				ip_freef(&ipq[i], TAILQ_FIRST(&ipq[i]));
1110			}
1111		}
1112	}
1113	IPQ_UNLOCK();
1114	splx(s);
1115}
1116
1117/*
1118 * Drain off all datagram fragments.
1119 */
1120void
1121ip_drain()
1122{
1123	int     i;
1124
1125	IPQ_LOCK();
1126	for (i = 0; i < IPREASS_NHASH; i++) {
1127		while(!TAILQ_EMPTY(&ipq[i])) {
1128			ipstat.ips_fragdropped +=
1129			    TAILQ_FIRST(&ipq[i])->ipq_nfrags;
1130			ip_freef(&ipq[i], TAILQ_FIRST(&ipq[i]));
1131		}
1132	}
1133	IPQ_UNLOCK();
1134	in_rtqdrain();
1135}
1136
1137/*
1138 * Do option processing on a datagram,
1139 * possibly discarding it if bad options are encountered,
1140 * or forwarding it if source-routed.
1141 * The pass argument is used when operating in the IPSTEALTH
1142 * mode to tell what options to process:
1143 * [LS]SRR (pass 0) or the others (pass 1).
1144 * The reason for as many as two passes is that when doing IPSTEALTH,
1145 * non-routing options should be processed only if the packet is for us.
1146 * Returns 1 if packet has been forwarded/freed,
1147 * 0 if the packet should be processed further.
1148 */
1149static int
1150ip_dooptions(struct mbuf *m, int pass)
1151{
1152	struct ip *ip = mtod(m, struct ip *);
1153	u_char *cp;
1154	struct in_ifaddr *ia;
1155	int opt, optlen, cnt, off, code, type = ICMP_PARAMPROB, forward = 0;
1156	struct in_addr *sin, dst;
1157	n_time ntime;
1158	struct	sockaddr_in ipaddr = { sizeof(ipaddr), AF_INET };
1159
1160	/* ignore or reject packets with IP options */
1161	if (ip_doopts == 0)
1162		return 0;
1163	else if (ip_doopts == 2) {
1164		type = ICMP_UNREACH;
1165		code = ICMP_UNREACH_FILTER_PROHIB;
1166		goto bad;
1167	}
1168
1169	dst = ip->ip_dst;
1170	cp = (u_char *)(ip + 1);
1171	cnt = (ip->ip_hl << 2) - sizeof (struct ip);
1172	for (; cnt > 0; cnt -= optlen, cp += optlen) {
1173		opt = cp[IPOPT_OPTVAL];
1174		if (opt == IPOPT_EOL)
1175			break;
1176		if (opt == IPOPT_NOP)
1177			optlen = 1;
1178		else {
1179			if (cnt < IPOPT_OLEN + sizeof(*cp)) {
1180				code = &cp[IPOPT_OLEN] - (u_char *)ip;
1181				goto bad;
1182			}
1183			optlen = cp[IPOPT_OLEN];
1184			if (optlen < IPOPT_OLEN + sizeof(*cp) || optlen > cnt) {
1185				code = &cp[IPOPT_OLEN] - (u_char *)ip;
1186				goto bad;
1187			}
1188		}
1189		switch (opt) {
1190
1191		default:
1192			break;
1193
1194		/*
1195		 * Source routing with record.
1196		 * Find interface with current destination address.
1197		 * If none on this machine then drop if strictly routed,
1198		 * or do nothing if loosely routed.
1199		 * Record interface address and bring up next address
1200		 * component.  If strictly routed make sure next
1201		 * address is on directly accessible net.
1202		 */
1203		case IPOPT_LSRR:
1204		case IPOPT_SSRR:
1205#ifdef IPSTEALTH
1206			if (ipstealth && pass > 0)
1207				break;
1208#endif
1209			if (optlen < IPOPT_OFFSET + sizeof(*cp)) {
1210				code = &cp[IPOPT_OLEN] - (u_char *)ip;
1211				goto bad;
1212			}
1213			if ((off = cp[IPOPT_OFFSET]) < IPOPT_MINOFF) {
1214				code = &cp[IPOPT_OFFSET] - (u_char *)ip;
1215				goto bad;
1216			}
1217			ipaddr.sin_addr = ip->ip_dst;
1218			ia = (struct in_ifaddr *)
1219				ifa_ifwithaddr((struct sockaddr *)&ipaddr);
1220			if (ia == NULL) {
1221				if (opt == IPOPT_SSRR) {
1222					type = ICMP_UNREACH;
1223					code = ICMP_UNREACH_SRCFAIL;
1224					goto bad;
1225				}
1226				if (!ip_dosourceroute)
1227					goto nosourcerouting;
1228				/*
1229				 * Loose routing, and not at next destination
1230				 * yet; nothing to do except forward.
1231				 */
1232				break;
1233			}
1234			off--;			/* 0 origin */
1235			if (off > optlen - (int)sizeof(struct in_addr)) {
1236				/*
1237				 * End of source route.  Should be for us.
1238				 */
1239				if (!ip_acceptsourceroute)
1240					goto nosourcerouting;
1241				save_rte(m, cp, ip->ip_src);
1242				break;
1243			}
1244#ifdef IPSTEALTH
1245			if (ipstealth)
1246				goto dropit;
1247#endif
1248			if (!ip_dosourceroute) {
1249				if (ipforwarding) {
1250					char buf[16]; /* aaa.bbb.ccc.ddd\0 */
1251					/*
1252					 * Acting as a router, so generate ICMP
1253					 */
1254nosourcerouting:
1255					strcpy(buf, inet_ntoa(ip->ip_dst));
1256					log(LOG_WARNING,
1257					    "attempted source route from %s to %s\n",
1258					    inet_ntoa(ip->ip_src), buf);
1259					type = ICMP_UNREACH;
1260					code = ICMP_UNREACH_SRCFAIL;
1261					goto bad;
1262				} else {
1263					/*
1264					 * Not acting as a router, so silently drop.
1265					 */
1266#ifdef IPSTEALTH
1267dropit:
1268#endif
1269					ipstat.ips_cantforward++;
1270					m_freem(m);
1271					return (1);
1272				}
1273			}
1274
1275			/*
1276			 * locate outgoing interface
1277			 */
1278			(void)memcpy(&ipaddr.sin_addr, cp + off,
1279			    sizeof(ipaddr.sin_addr));
1280
1281			if (opt == IPOPT_SSRR) {
1282#define	INA	struct in_ifaddr *
1283#define	SA	struct sockaddr *
1284			    if ((ia = (INA)ifa_ifwithdstaddr((SA)&ipaddr)) == NULL)
1285				ia = (INA)ifa_ifwithnet((SA)&ipaddr);
1286			} else
1287				ia = ip_rtaddr(ipaddr.sin_addr);
1288			if (ia == NULL) {
1289				type = ICMP_UNREACH;
1290				code = ICMP_UNREACH_SRCFAIL;
1291				goto bad;
1292			}
1293			ip->ip_dst = ipaddr.sin_addr;
1294			(void)memcpy(cp + off, &(IA_SIN(ia)->sin_addr),
1295			    sizeof(struct in_addr));
1296			cp[IPOPT_OFFSET] += sizeof(struct in_addr);
1297			/*
1298			 * Let ip_intr's mcast routing check handle mcast pkts
1299			 */
1300			forward = !IN_MULTICAST(ntohl(ip->ip_dst.s_addr));
1301			break;
1302
1303		case IPOPT_RR:
1304#ifdef IPSTEALTH
1305			if (ipstealth && pass == 0)
1306				break;
1307#endif
1308			if (optlen < IPOPT_OFFSET + sizeof(*cp)) {
1309				code = &cp[IPOPT_OFFSET] - (u_char *)ip;
1310				goto bad;
1311			}
1312			if ((off = cp[IPOPT_OFFSET]) < IPOPT_MINOFF) {
1313				code = &cp[IPOPT_OFFSET] - (u_char *)ip;
1314				goto bad;
1315			}
1316			/*
1317			 * If no space remains, ignore.
1318			 */
1319			off--;			/* 0 origin */
1320			if (off > optlen - (int)sizeof(struct in_addr))
1321				break;
1322			(void)memcpy(&ipaddr.sin_addr, &ip->ip_dst,
1323			    sizeof(ipaddr.sin_addr));
1324			/*
1325			 * locate outgoing interface; if we're the destination,
1326			 * use the incoming interface (should be same).
1327			 */
1328			if ((ia = (INA)ifa_ifwithaddr((SA)&ipaddr)) == NULL &&
1329			    (ia = ip_rtaddr(ipaddr.sin_addr)) == NULL) {
1330				type = ICMP_UNREACH;
1331				code = ICMP_UNREACH_HOST;
1332				goto bad;
1333			}
1334			(void)memcpy(cp + off, &(IA_SIN(ia)->sin_addr),
1335			    sizeof(struct in_addr));
1336			cp[IPOPT_OFFSET] += sizeof(struct in_addr);
1337			break;
1338
1339		case IPOPT_TS:
1340#ifdef IPSTEALTH
1341			if (ipstealth && pass == 0)
1342				break;
1343#endif
1344			code = cp - (u_char *)ip;
1345			if (optlen < 4 || optlen > 40) {
1346				code = &cp[IPOPT_OLEN] - (u_char *)ip;
1347				goto bad;
1348			}
1349			if ((off = cp[IPOPT_OFFSET]) < 5) {
1350				code = &cp[IPOPT_OLEN] - (u_char *)ip;
1351				goto bad;
1352			}
1353			if (off > optlen - (int)sizeof(int32_t)) {
1354				cp[IPOPT_OFFSET + 1] += (1 << 4);
1355				if ((cp[IPOPT_OFFSET + 1] & 0xf0) == 0) {
1356					code = &cp[IPOPT_OFFSET] - (u_char *)ip;
1357					goto bad;
1358				}
1359				break;
1360			}
1361			off--;				/* 0 origin */
1362			sin = (struct in_addr *)(cp + off);
1363			switch (cp[IPOPT_OFFSET + 1] & 0x0f) {
1364
1365			case IPOPT_TS_TSONLY:
1366				break;
1367
1368			case IPOPT_TS_TSANDADDR:
1369				if (off + sizeof(n_time) +
1370				    sizeof(struct in_addr) > optlen) {
1371					code = &cp[IPOPT_OFFSET] - (u_char *)ip;
1372					goto bad;
1373				}
1374				ipaddr.sin_addr = dst;
1375				ia = (INA)ifaof_ifpforaddr((SA)&ipaddr,
1376							    m->m_pkthdr.rcvif);
1377				if (ia == NULL)
1378					continue;
1379				(void)memcpy(sin, &IA_SIN(ia)->sin_addr,
1380				    sizeof(struct in_addr));
1381				cp[IPOPT_OFFSET] += sizeof(struct in_addr);
1382				off += sizeof(struct in_addr);
1383				break;
1384
1385			case IPOPT_TS_PRESPEC:
1386				if (off + sizeof(n_time) +
1387				    sizeof(struct in_addr) > optlen) {
1388					code = &cp[IPOPT_OFFSET] - (u_char *)ip;
1389					goto bad;
1390				}
1391				(void)memcpy(&ipaddr.sin_addr, sin,
1392				    sizeof(struct in_addr));
1393				if (ifa_ifwithaddr((SA)&ipaddr) == NULL)
1394					continue;
1395				cp[IPOPT_OFFSET] += sizeof(struct in_addr);
1396				off += sizeof(struct in_addr);
1397				break;
1398
1399			default:
1400				code = &cp[IPOPT_OFFSET + 1] - (u_char *)ip;
1401				goto bad;
1402			}
1403			ntime = iptime();
1404			(void)memcpy(cp + off, &ntime, sizeof(n_time));
1405			cp[IPOPT_OFFSET] += sizeof(n_time);
1406		}
1407	}
1408	if (forward && ipforwarding) {
1409		ip_forward(m, 1);
1410		return (1);
1411	}
1412	return (0);
1413bad:
1414	icmp_error(m, type, code, 0, 0);
1415	ipstat.ips_badoptions++;
1416	return (1);
1417}
1418
1419/*
1420 * Given address of next destination (final or next hop),
1421 * return internet address info of interface to be used to get there.
1422 */
1423struct in_ifaddr *
1424ip_rtaddr(dst)
1425	struct in_addr dst;
1426{
1427	struct route sro;
1428	struct sockaddr_in *sin;
1429	struct in_ifaddr *ifa;
1430
1431	bzero(&sro, sizeof(sro));
1432	sin = (struct sockaddr_in *)&sro.ro_dst;
1433	sin->sin_family = AF_INET;
1434	sin->sin_len = sizeof(*sin);
1435	sin->sin_addr = dst;
1436	rtalloc_ign(&sro, RTF_CLONING);
1437
1438	if (sro.ro_rt == NULL)
1439		return ((struct in_ifaddr *)0);
1440
1441	ifa = ifatoia(sro.ro_rt->rt_ifa);
1442	RTFREE(sro.ro_rt);
1443	return ifa;
1444}
1445
1446/*
1447 * Save incoming source route for use in replies,
1448 * to be picked up later by ip_srcroute if the receiver is interested.
1449 */
1450static void
1451save_rte(m, option, dst)
1452	struct mbuf *m;
1453	u_char *option;
1454	struct in_addr dst;
1455{
1456	unsigned olen;
1457	struct ipopt_tag *opts;
1458
1459	opts = (struct ipopt_tag *)m_tag_get(PACKET_TAG_IPOPTIONS,
1460					sizeof(struct ipopt_tag), M_NOWAIT);
1461	if (opts == NULL)
1462		return;
1463
1464	olen = option[IPOPT_OLEN];
1465#ifdef DIAGNOSTIC
1466	if (ipprintfs)
1467		printf("save_rte: olen %d\n", olen);
1468#endif
1469	if (olen > sizeof(opts->ip_srcrt) - (1 + sizeof(dst)))
1470		return;
1471	bcopy(option, opts->ip_srcrt.srcopt, olen);
1472	opts->ip_nhops = (olen - IPOPT_OFFSET - 1) / sizeof(struct in_addr);
1473	opts->ip_srcrt.dst = dst;
1474	m_tag_prepend(m, (struct m_tag *)opts);
1475}
1476
1477/*
1478 * Retrieve incoming source route for use in replies,
1479 * in the same form used by setsockopt.
1480 * The first hop is placed before the options, will be removed later.
1481 */
1482struct mbuf *
1483ip_srcroute(m0)
1484	struct mbuf *m0;
1485{
1486	register struct in_addr *p, *q;
1487	register struct mbuf *m;
1488	struct ipopt_tag *opts;
1489
1490	opts = (struct ipopt_tag *)m_tag_find(m0, PACKET_TAG_IPOPTIONS, NULL);
1491	if (opts == NULL)
1492		return ((struct mbuf *)0);
1493
1494	if (opts->ip_nhops == 0)
1495		return ((struct mbuf *)0);
1496	m = m_get(M_DONTWAIT, MT_HEADER);
1497	if (m == NULL)
1498		return ((struct mbuf *)0);
1499
1500#define OPTSIZ	(sizeof(opts->ip_srcrt.nop) + sizeof(opts->ip_srcrt.srcopt))
1501
1502	/* length is (nhops+1)*sizeof(addr) + sizeof(nop + srcrt header) */
1503	m->m_len = opts->ip_nhops * sizeof(struct in_addr) +
1504	    sizeof(struct in_addr) + OPTSIZ;
1505#ifdef DIAGNOSTIC
1506	if (ipprintfs)
1507		printf("ip_srcroute: nhops %d mlen %d", opts->ip_nhops, m->m_len);
1508#endif
1509
1510	/*
1511	 * First save first hop for return route
1512	 */
1513	p = &(opts->ip_srcrt.route[opts->ip_nhops - 1]);
1514	*(mtod(m, struct in_addr *)) = *p--;
1515#ifdef DIAGNOSTIC
1516	if (ipprintfs)
1517		printf(" hops %lx", (u_long)ntohl(mtod(m, struct in_addr *)->s_addr));
1518#endif
1519
1520	/*
1521	 * Copy option fields and padding (nop) to mbuf.
1522	 */
1523	opts->ip_srcrt.nop = IPOPT_NOP;
1524	opts->ip_srcrt.srcopt[IPOPT_OFFSET] = IPOPT_MINOFF;
1525	(void)memcpy(mtod(m, caddr_t) + sizeof(struct in_addr),
1526	    &(opts->ip_srcrt.nop), OPTSIZ);
1527	q = (struct in_addr *)(mtod(m, caddr_t) +
1528	    sizeof(struct in_addr) + OPTSIZ);
1529#undef OPTSIZ
1530	/*
1531	 * Record return path as an IP source route,
1532	 * reversing the path (pointers are now aligned).
1533	 */
1534	while (p >= opts->ip_srcrt.route) {
1535#ifdef DIAGNOSTIC
1536		if (ipprintfs)
1537			printf(" %lx", (u_long)ntohl(q->s_addr));
1538#endif
1539		*q++ = *p--;
1540	}
1541	/*
1542	 * Last hop goes to final destination.
1543	 */
1544	*q = opts->ip_srcrt.dst;
1545#ifdef DIAGNOSTIC
1546	if (ipprintfs)
1547		printf(" %lx\n", (u_long)ntohl(q->s_addr));
1548#endif
1549	m_tag_delete(m0, (struct m_tag *)opts);
1550	return (m);
1551}
1552
1553/*
1554 * Strip out IP options, at higher
1555 * level protocol in the kernel.
1556 * Second argument is buffer to which options
1557 * will be moved, and return value is their length.
1558 * XXX should be deleted; last arg currently ignored.
1559 */
1560void
1561ip_stripoptions(m, mopt)
1562	register struct mbuf *m;
1563	struct mbuf *mopt;
1564{
1565	register int i;
1566	struct ip *ip = mtod(m, struct ip *);
1567	register caddr_t opts;
1568	int olen;
1569
1570	olen = (ip->ip_hl << 2) - sizeof (struct ip);
1571	opts = (caddr_t)(ip + 1);
1572	i = m->m_len - (sizeof (struct ip) + olen);
1573	bcopy(opts + olen, opts, (unsigned)i);
1574	m->m_len -= olen;
1575	if (m->m_flags & M_PKTHDR)
1576		m->m_pkthdr.len -= olen;
1577	ip->ip_v = IPVERSION;
1578	ip->ip_hl = sizeof(struct ip) >> 2;
1579}
1580
1581u_char inetctlerrmap[PRC_NCMDS] = {
1582	0,		0,		0,		0,
1583	0,		EMSGSIZE,	EHOSTDOWN,	EHOSTUNREACH,
1584	EHOSTUNREACH,	EHOSTUNREACH,	ECONNREFUSED,	ECONNREFUSED,
1585	EMSGSIZE,	EHOSTUNREACH,	0,		0,
1586	0,		0,		EHOSTUNREACH,	0,
1587	ENOPROTOOPT,	ECONNREFUSED
1588};
1589
1590/*
1591 * Forward a packet.  If some error occurs return the sender
1592 * an icmp packet.  Note we can't always generate a meaningful
1593 * icmp message because icmp doesn't have a large enough repertoire
1594 * of codes and types.
1595 *
1596 * If not forwarding, just drop the packet.  This could be confusing
1597 * if ipforwarding was zero but some routing protocol was advancing
1598 * us as a gateway to somewhere.  However, we must let the routing
1599 * protocol deal with that.
1600 *
1601 * The srcrt parameter indicates whether the packet is being forwarded
1602 * via a source route.
1603 */
1604void
1605ip_forward(struct mbuf *m, int srcrt)
1606{
1607	struct ip *ip = mtod(m, struct ip *);
1608	struct in_ifaddr *ia = NULL;
1609	int error, type = 0, code = 0;
1610	struct mbuf *mcopy;
1611	struct in_addr dest;
1612	struct ifnet *destifp, dummyifp;
1613
1614#ifdef DIAGNOSTIC
1615	if (ipprintfs)
1616		printf("forward: src %lx dst %lx ttl %x\n",
1617		    (u_long)ip->ip_src.s_addr, (u_long)ip->ip_dst.s_addr,
1618		    ip->ip_ttl);
1619#endif
1620
1621
1622	if (m->m_flags & (M_BCAST|M_MCAST) || in_canforward(ip->ip_dst) == 0) {
1623		ipstat.ips_cantforward++;
1624		m_freem(m);
1625		return;
1626	}
1627#ifdef IPSTEALTH
1628	if (!ipstealth) {
1629#endif
1630		if (ip->ip_ttl <= IPTTLDEC) {
1631			icmp_error(m, ICMP_TIMXCEED, ICMP_TIMXCEED_INTRANS,
1632			    0, 0);
1633			return;
1634		}
1635#ifdef IPSTEALTH
1636	}
1637#endif
1638
1639	if (!srcrt && (ia = ip_rtaddr(ip->ip_dst)) == NULL) {
1640		icmp_error(m, ICMP_UNREACH, ICMP_UNREACH_HOST, 0, 0);
1641		return;
1642	}
1643
1644	/*
1645	 * Save the IP header and at most 8 bytes of the payload,
1646	 * in case we need to generate an ICMP message to the src.
1647	 *
1648	 * XXX this can be optimized a lot by saving the data in a local
1649	 * buffer on the stack (72 bytes at most), and only allocating the
1650	 * mbuf if really necessary. The vast majority of the packets
1651	 * are forwarded without having to send an ICMP back (either
1652	 * because unnecessary, or because rate limited), so we are
1653	 * really we are wasting a lot of work here.
1654	 *
1655	 * We don't use m_copy() because it might return a reference
1656	 * to a shared cluster. Both this function and ip_output()
1657	 * assume exclusive access to the IP header in `m', so any
1658	 * data in a cluster may change before we reach icmp_error().
1659	 */
1660	MGET(mcopy, M_DONTWAIT, m->m_type);
1661	if (mcopy != NULL && !m_dup_pkthdr(mcopy, m, M_DONTWAIT)) {
1662		/*
1663		 * It's probably ok if the pkthdr dup fails (because
1664		 * the deep copy of the tag chain failed), but for now
1665		 * be conservative and just discard the copy since
1666		 * code below may some day want the tags.
1667		 */
1668		m_free(mcopy);
1669		mcopy = NULL;
1670	}
1671	if (mcopy != NULL) {
1672		mcopy->m_len = imin((ip->ip_hl << 2) + 8,
1673		    (int)ip->ip_len);
1674		mcopy->m_pkthdr.len = mcopy->m_len;
1675		m_copydata(m, 0, mcopy->m_len, mtod(mcopy, caddr_t));
1676	}
1677
1678#ifdef IPSTEALTH
1679	if (!ipstealth) {
1680#endif
1681		ip->ip_ttl -= IPTTLDEC;
1682#ifdef IPSTEALTH
1683	}
1684#endif
1685
1686	/*
1687	 * If forwarding packet using same interface that it came in on,
1688	 * perhaps should send a redirect to sender to shortcut a hop.
1689	 * Only send redirect if source is sending directly to us,
1690	 * and if packet was not source routed (or has any options).
1691	 * Also, don't send redirect if forwarding using a default route
1692	 * or a route modified by a redirect.
1693	 */
1694	dest.s_addr = 0;
1695	if (!srcrt && ipsendredirects && ia->ia_ifp == m->m_pkthdr.rcvif) {
1696		struct sockaddr_in *sin;
1697		struct route ro;
1698		struct rtentry *rt;
1699
1700		bzero(&ro, sizeof(ro));
1701		sin = (struct sockaddr_in *)&ro.ro_dst;
1702		sin->sin_family = AF_INET;
1703		sin->sin_len = sizeof(*sin);
1704		sin->sin_addr = ip->ip_dst;
1705		rtalloc_ign(&ro, RTF_CLONING);
1706
1707		rt = ro.ro_rt;
1708
1709		if (rt && (rt->rt_flags & (RTF_DYNAMIC|RTF_MODIFIED)) == 0 &&
1710		    satosin(rt_key(rt))->sin_addr.s_addr != 0) {
1711#define	RTA(rt)	((struct in_ifaddr *)(rt->rt_ifa))
1712			u_long src = ntohl(ip->ip_src.s_addr);
1713
1714			if (RTA(rt) &&
1715			    (src & RTA(rt)->ia_subnetmask) == RTA(rt)->ia_subnet) {
1716				if (rt->rt_flags & RTF_GATEWAY)
1717					dest.s_addr = satosin(rt->rt_gateway)->sin_addr.s_addr;
1718				else
1719					dest.s_addr = ip->ip_dst.s_addr;
1720				/* Router requirements says to only send host redirects */
1721				type = ICMP_REDIRECT;
1722				code = ICMP_REDIRECT_HOST;
1723#ifdef DIAGNOSTIC
1724				if (ipprintfs)
1725					printf("redirect (%d) to %lx\n", code, (u_long)dest.s_addr);
1726#endif
1727			}
1728		}
1729		if (rt)
1730			RTFREE(rt);
1731	}
1732
1733	error = ip_output(m, (struct mbuf *)0, NULL, IP_FORWARDING, 0, NULL);
1734	if (error)
1735		ipstat.ips_cantforward++;
1736	else {
1737		ipstat.ips_forward++;
1738		if (type)
1739			ipstat.ips_redirectsent++;
1740		else {
1741			if (mcopy)
1742				m_freem(mcopy);
1743			return;
1744		}
1745	}
1746	if (mcopy == NULL)
1747		return;
1748	destifp = NULL;
1749
1750	switch (error) {
1751
1752	case 0:				/* forwarded, but need redirect */
1753		/* type, code set above */
1754		break;
1755
1756	case ENETUNREACH:		/* shouldn't happen, checked above */
1757	case EHOSTUNREACH:
1758	case ENETDOWN:
1759	case EHOSTDOWN:
1760	default:
1761		type = ICMP_UNREACH;
1762		code = ICMP_UNREACH_HOST;
1763		break;
1764
1765	case EMSGSIZE:
1766		type = ICMP_UNREACH;
1767		code = ICMP_UNREACH_NEEDFRAG;
1768#if defined(IPSEC) || defined(FAST_IPSEC)
1769		/*
1770		 * If the packet is routed over IPsec tunnel, tell the
1771		 * originator the tunnel MTU.
1772		 *	tunnel MTU = if MTU - sizeof(IP) - ESP/AH hdrsiz
1773		 * XXX quickhack!!!
1774		 */
1775		{
1776			struct secpolicy *sp = NULL;
1777			int ipsecerror;
1778			int ipsechdr;
1779			struct route *ro;
1780
1781#ifdef IPSEC
1782			sp = ipsec4_getpolicybyaddr(mcopy,
1783						    IPSEC_DIR_OUTBOUND,
1784						    IP_FORWARDING,
1785						    &ipsecerror);
1786#else /* FAST_IPSEC */
1787			sp = ipsec_getpolicybyaddr(mcopy,
1788						   IPSEC_DIR_OUTBOUND,
1789						   IP_FORWARDING,
1790						   &ipsecerror);
1791#endif
1792			if (sp != NULL) {
1793				/* count IPsec header size */
1794				ipsechdr = ipsec4_hdrsiz(mcopy,
1795							 IPSEC_DIR_OUTBOUND,
1796							 NULL);
1797
1798				/*
1799				 * find the correct route for outer IPv4
1800				 * header, compute tunnel MTU.
1801				 *
1802				 * XXX BUG ALERT
1803				 * The "dummyifp" code relies upon the fact
1804				 * that icmp_error() touches only ifp->if_mtu.
1805				 */
1806				/*XXX*/
1807				destifp = NULL;
1808				if (sp->req != NULL
1809				 && sp->req->sav != NULL
1810				 && sp->req->sav->sah != NULL) {
1811					ro = &sp->req->sav->sah->sa_route;
1812					if (ro->ro_rt && ro->ro_rt->rt_ifp) {
1813						dummyifp.if_mtu =
1814						    ro->ro_rt->rt_rmx.rmx_mtu ?
1815						    ro->ro_rt->rt_rmx.rmx_mtu :
1816						    ro->ro_rt->rt_ifp->if_mtu;
1817						dummyifp.if_mtu -= ipsechdr;
1818						destifp = &dummyifp;
1819					}
1820				}
1821
1822#ifdef IPSEC
1823				key_freesp(sp);
1824#else /* FAST_IPSEC */
1825				KEY_FREESP(&sp);
1826#endif
1827				ipstat.ips_cantfrag++;
1828				break;
1829			} else
1830#endif /*IPSEC || FAST_IPSEC*/
1831		/*
1832		 * When doing source routing 'ia' can be NULL.  Fall back
1833		 * to the minimum guaranteed routeable packet size and use
1834		 * the same hack as IPSEC to setup a dummyifp for icmp.
1835		 */
1836		if (ia == NULL) {
1837			dummyifp.if_mtu = IP_MSS;
1838			destifp = &dummyifp;
1839		} else
1840			destifp = ia->ia_ifp;
1841#if defined(IPSEC) || defined(FAST_IPSEC)
1842		}
1843#endif /*IPSEC || FAST_IPSEC*/
1844		ipstat.ips_cantfrag++;
1845		break;
1846
1847	case ENOBUFS:
1848		/*
1849		 * A router should not generate ICMP_SOURCEQUENCH as
1850		 * required in RFC1812 Requirements for IP Version 4 Routers.
1851		 * Source quench could be a big problem under DoS attacks,
1852		 * or if the underlying interface is rate-limited.
1853		 * Those who need source quench packets may re-enable them
1854		 * via the net.inet.ip.sendsourcequench sysctl.
1855		 */
1856		if (ip_sendsourcequench == 0) {
1857			m_freem(mcopy);
1858			return;
1859		} else {
1860			type = ICMP_SOURCEQUENCH;
1861			code = 0;
1862		}
1863		break;
1864
1865	case EACCES:			/* ipfw denied packet */
1866		m_freem(mcopy);
1867		return;
1868	}
1869	icmp_error(mcopy, type, code, dest.s_addr, destifp);
1870}
1871
1872void
1873ip_savecontrol(inp, mp, ip, m)
1874	register struct inpcb *inp;
1875	register struct mbuf **mp;
1876	register struct ip *ip;
1877	register struct mbuf *m;
1878{
1879	if (inp->inp_socket->so_options & (SO_BINTIME | SO_TIMESTAMP)) {
1880		struct bintime bt;
1881
1882		bintime(&bt);
1883		if (inp->inp_socket->so_options & SO_BINTIME) {
1884			*mp = sbcreatecontrol((caddr_t) &bt, sizeof(bt),
1885			SCM_BINTIME, SOL_SOCKET);
1886			if (*mp)
1887				mp = &(*mp)->m_next;
1888		}
1889		if (inp->inp_socket->so_options & SO_TIMESTAMP) {
1890			struct timeval tv;
1891
1892			bintime2timeval(&bt, &tv);
1893			*mp = sbcreatecontrol((caddr_t) &tv, sizeof(tv),
1894				SCM_TIMESTAMP, SOL_SOCKET);
1895			if (*mp)
1896				mp = &(*mp)->m_next;
1897		}
1898	}
1899	if (inp->inp_flags & INP_RECVDSTADDR) {
1900		*mp = sbcreatecontrol((caddr_t) &ip->ip_dst,
1901		    sizeof(struct in_addr), IP_RECVDSTADDR, IPPROTO_IP);
1902		if (*mp)
1903			mp = &(*mp)->m_next;
1904	}
1905	if (inp->inp_flags & INP_RECVTTL) {
1906		*mp = sbcreatecontrol((caddr_t) &ip->ip_ttl,
1907		    sizeof(u_char), IP_RECVTTL, IPPROTO_IP);
1908		if (*mp)
1909			mp = &(*mp)->m_next;
1910	}
1911#ifdef notyet
1912	/* XXX
1913	 * Moving these out of udp_input() made them even more broken
1914	 * than they already were.
1915	 */
1916	/* options were tossed already */
1917	if (inp->inp_flags & INP_RECVOPTS) {
1918		*mp = sbcreatecontrol((caddr_t) opts_deleted_above,
1919		    sizeof(struct in_addr), IP_RECVOPTS, IPPROTO_IP);
1920		if (*mp)
1921			mp = &(*mp)->m_next;
1922	}
1923	/* ip_srcroute doesn't do what we want here, need to fix */
1924	if (inp->inp_flags & INP_RECVRETOPTS) {
1925		*mp = sbcreatecontrol((caddr_t) ip_srcroute(m),
1926		    sizeof(struct in_addr), IP_RECVRETOPTS, IPPROTO_IP);
1927		if (*mp)
1928			mp = &(*mp)->m_next;
1929	}
1930#endif
1931	if (inp->inp_flags & INP_RECVIF) {
1932		struct ifnet *ifp;
1933		struct sdlbuf {
1934			struct sockaddr_dl sdl;
1935			u_char	pad[32];
1936		} sdlbuf;
1937		struct sockaddr_dl *sdp;
1938		struct sockaddr_dl *sdl2 = &sdlbuf.sdl;
1939
1940		if (((ifp = m->m_pkthdr.rcvif))
1941		&& ( ifp->if_index && (ifp->if_index <= if_index))) {
1942			sdp = (struct sockaddr_dl *)
1943			    (ifaddr_byindex(ifp->if_index)->ifa_addr);
1944			/*
1945			 * Change our mind and don't try copy.
1946			 */
1947			if ((sdp->sdl_family != AF_LINK)
1948			|| (sdp->sdl_len > sizeof(sdlbuf))) {
1949				goto makedummy;
1950			}
1951			bcopy(sdp, sdl2, sdp->sdl_len);
1952		} else {
1953makedummy:
1954			sdl2->sdl_len
1955				= offsetof(struct sockaddr_dl, sdl_data[0]);
1956			sdl2->sdl_family = AF_LINK;
1957			sdl2->sdl_index = 0;
1958			sdl2->sdl_nlen = sdl2->sdl_alen = sdl2->sdl_slen = 0;
1959		}
1960		*mp = sbcreatecontrol((caddr_t) sdl2, sdl2->sdl_len,
1961			IP_RECVIF, IPPROTO_IP);
1962		if (*mp)
1963			mp = &(*mp)->m_next;
1964	}
1965}
1966
1967/*
1968 * XXX these routines are called from the upper part of the kernel.
1969 * They need to be locked when we remove Giant.
1970 *
1971 * They could also be moved to ip_mroute.c, since all the RSVP
1972 *  handling is done there already.
1973 */
1974static int ip_rsvp_on;
1975struct socket *ip_rsvpd;
1976int
1977ip_rsvp_init(struct socket *so)
1978{
1979	if (so->so_type != SOCK_RAW ||
1980	    so->so_proto->pr_protocol != IPPROTO_RSVP)
1981		return EOPNOTSUPP;
1982
1983	if (ip_rsvpd != NULL)
1984		return EADDRINUSE;
1985
1986	ip_rsvpd = so;
1987	/*
1988	 * This may seem silly, but we need to be sure we don't over-increment
1989	 * the RSVP counter, in case something slips up.
1990	 */
1991	if (!ip_rsvp_on) {
1992		ip_rsvp_on = 1;
1993		rsvp_on++;
1994	}
1995
1996	return 0;
1997}
1998
1999int
2000ip_rsvp_done(void)
2001{
2002	ip_rsvpd = NULL;
2003	/*
2004	 * This may seem silly, but we need to be sure we don't over-decrement
2005	 * the RSVP counter, in case something slips up.
2006	 */
2007	if (ip_rsvp_on) {
2008		ip_rsvp_on = 0;
2009		rsvp_on--;
2010	}
2011	return 0;
2012}
2013
2014void
2015rsvp_input(struct mbuf *m, int off)	/* XXX must fixup manually */
2016{
2017	if (rsvp_input_p) { /* call the real one if loaded */
2018		rsvp_input_p(m, off);
2019		return;
2020	}
2021
2022	/* Can still get packets with rsvp_on = 0 if there is a local member
2023	 * of the group to which the RSVP packet is addressed.  But in this
2024	 * case we want to throw the packet away.
2025	 */
2026
2027	if (!rsvp_on) {
2028		m_freem(m);
2029		return;
2030	}
2031
2032	if (ip_rsvpd != NULL) {
2033		rip_input(m, off);
2034		return;
2035	}
2036	/* Drop the packet */
2037	m_freem(m);
2038}
2039