ip_input.c revision 1.183
1/*	$NetBSD: ip_input.c,v 1.183 2003/11/17 22:34:16 jonathan Exp $	*/
2
3/*
4 * Copyright (C) 1995, 1996, 1997, and 1998 WIDE Project.
5 * All rights reserved.
6 *
7 * Redistribution and use in source and binary forms, with or without
8 * modification, are permitted provided that the following conditions
9 * are met:
10 * 1. Redistributions of source code must retain the above copyright
11 *    notice, this list of conditions and the following disclaimer.
12 * 2. Redistributions in binary form must reproduce the above copyright
13 *    notice, this list of conditions and the following disclaimer in the
14 *    documentation and/or other materials provided with the distribution.
15 * 3. Neither the name of the project nor the names of its contributors
16 *    may be used to endorse or promote products derived from this software
17 *    without specific prior written permission.
18 *
19 * THIS SOFTWARE IS PROVIDED BY THE PROJECT AND CONTRIBUTORS ``AS IS'' AND
20 * ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
21 * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE
22 * ARE DISCLAIMED.  IN NO EVENT SHALL THE PROJECT OR CONTRIBUTORS BE LIABLE
23 * FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL
24 * DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS
25 * OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION)
26 * HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT
27 * LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY
28 * OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF
29 * SUCH DAMAGE.
30 */
31
32/*-
33 * Copyright (c) 1998 The NetBSD Foundation, Inc.
34 * All rights reserved.
35 *
36 * This code is derived from software contributed to The NetBSD Foundation
37 * by Public Access Networks Corporation ("Panix").  It was developed under
38 * contract to Panix by Eric Haszlakiewicz and Thor Lancelot Simon.
39 *
40 * Redistribution and use in source and binary forms, with or without
41 * modification, are permitted provided that the following conditions
42 * are met:
43 * 1. Redistributions of source code must retain the above copyright
44 *    notice, this list of conditions and the following disclaimer.
45 * 2. Redistributions in binary form must reproduce the above copyright
46 *    notice, this list of conditions and the following disclaimer in the
47 *    documentation and/or other materials provided with the distribution.
48 * 3. All advertising materials mentioning features or use of this software
49 *    must display the following acknowledgement:
50 *	This product includes software developed by the NetBSD
51 *	Foundation, Inc. and its contributors.
52 * 4. Neither the name of The NetBSD Foundation nor the names of its
53 *    contributors may be used to endorse or promote products derived
54 *    from this software without specific prior written permission.
55 *
56 * THIS SOFTWARE IS PROVIDED BY THE NETBSD FOUNDATION, INC. AND CONTRIBUTORS
57 * ``AS IS'' AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED
58 * TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR
59 * PURPOSE ARE DISCLAIMED.  IN NO EVENT SHALL THE FOUNDATION OR CONTRIBUTORS
60 * BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR
61 * CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF
62 * SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS
63 * INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN
64 * CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE)
65 * ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE
66 * POSSIBILITY OF SUCH DAMAGE.
67 */
68
69/*
70 * Copyright (c) 1982, 1986, 1988, 1993
71 *	The Regents of the University of California.  All rights reserved.
72 *
73 * Redistribution and use in source and binary forms, with or without
74 * modification, are permitted provided that the following conditions
75 * are met:
76 * 1. Redistributions of source code must retain the above copyright
77 *    notice, this list of conditions and the following disclaimer.
78 * 2. Redistributions in binary form must reproduce the above copyright
79 *    notice, this list of conditions and the following disclaimer in the
80 *    documentation and/or other materials provided with the distribution.
81 * 3. Neither the name of the University nor the names of its contributors
82 *    may be used to endorse or promote products derived from this software
83 *    without specific prior written permission.
84 *
85 * THIS SOFTWARE IS PROVIDED BY THE REGENTS AND CONTRIBUTORS ``AS IS'' AND
86 * ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
87 * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE
88 * ARE DISCLAIMED.  IN NO EVENT SHALL THE REGENTS OR CONTRIBUTORS BE LIABLE
89 * FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL
90 * DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS
91 * OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION)
92 * HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT
93 * LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY
94 * OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF
95 * SUCH DAMAGE.
96 *
97 *	@(#)ip_input.c	8.2 (Berkeley) 1/4/94
98 */
99
100#include <sys/cdefs.h>
101__KERNEL_RCSID(0, "$NetBSD: ip_input.c,v 1.183 2003/11/17 22:34:16 jonathan Exp $");
102
103#include "opt_gateway.h"
104#include "opt_pfil_hooks.h"
105#include "opt_ipsec.h"
106#include "opt_mrouting.h"
107#include "opt_mbuftrace.h"
108#include "opt_inet_csum.h"
109
110#include <sys/param.h>
111#include <sys/systm.h>
112#include <sys/malloc.h>
113#include <sys/mbuf.h>
114#include <sys/domain.h>
115#include <sys/protosw.h>
116#include <sys/socket.h>
117#include <sys/socketvar.h>
118#include <sys/errno.h>
119#include <sys/time.h>
120#include <sys/kernel.h>
121#include <sys/pool.h>
122#include <sys/sysctl.h>
123
124#include <net/if.h>
125#include <net/if_dl.h>
126#include <net/route.h>
127#include <net/pfil.h>
128
129#include <netinet/in.h>
130#include <netinet/in_systm.h>
131#include <netinet/ip.h>
132#include <netinet/in_pcb.h>
133#include <netinet/in_var.h>
134#include <netinet/ip_var.h>
135#include <netinet/ip_icmp.h>
136/* just for gif_ttl */
137#include <netinet/in_gif.h>
138#include "gif.h"
139#include <net/if_gre.h>
140#include "gre.h"
141
142#ifdef MROUTING
143#include <netinet/ip_mroute.h>
144#endif
145
146#ifdef IPSEC
147#include <netinet6/ipsec.h>
148#include <netkey/key.h>
149#endif
150#ifdef FAST_IPSEC
151#include <netipsec/ipsec.h>
152#include <netipsec/key.h>
153#endif	/* FAST_IPSEC*/
154
155#ifndef	IPFORWARDING
156#ifdef GATEWAY
157#define	IPFORWARDING	1	/* forward IP packets not for us */
158#else /* GATEWAY */
159#define	IPFORWARDING	0	/* don't forward IP packets not for us */
160#endif /* GATEWAY */
161#endif /* IPFORWARDING */
162#ifndef	IPSENDREDIRECTS
163#define	IPSENDREDIRECTS	1
164#endif
165#ifndef IPFORWSRCRT
166#define	IPFORWSRCRT	1	/* forward source-routed packets */
167#endif
168#ifndef IPALLOWSRCRT
169#define	IPALLOWSRCRT	1	/* allow source-routed packets */
170#endif
171#ifndef IPMTUDISC
172#define IPMTUDISC	1
173#endif
174#ifndef IPMTUDISCTIMEOUT
175#define IPMTUDISCTIMEOUT (10 * 60)	/* as per RFC 1191 */
176#endif
177
178/*
179 * Note: DIRECTED_BROADCAST is handled this way so that previous
180 * configuration using this option will Just Work.
181 */
182#ifndef IPDIRECTEDBCAST
183#ifdef DIRECTED_BROADCAST
184#define IPDIRECTEDBCAST	1
185#else
186#define	IPDIRECTEDBCAST	0
187#endif /* DIRECTED_BROADCAST */
188#endif /* IPDIRECTEDBCAST */
189int	ipforwarding = IPFORWARDING;
190int	ipsendredirects = IPSENDREDIRECTS;
191int	ip_defttl = IPDEFTTL;
192int	ip_forwsrcrt = IPFORWSRCRT;
193int	ip_directedbcast = IPDIRECTEDBCAST;
194int	ip_allowsrcrt = IPALLOWSRCRT;
195int	ip_mtudisc = IPMTUDISC;
196int	ip_mtudisc_timeout = IPMTUDISCTIMEOUT;
197#ifdef DIAGNOSTIC
198int	ipprintfs = 0;
199#endif
200/*
201 * XXX - Setting ip_checkinterface mostly implements the receive side of
202 * the Strong ES model described in RFC 1122, but since the routing table
203 * and transmit implementation do not implement the Strong ES model,
204 * setting this to 1 results in an odd hybrid.
205 *
206 * XXX - ip_checkinterface currently must be disabled if you use ipnat
207 * to translate the destination address to another local interface.
208 *
209 * XXX - ip_checkinterface must be disabled if you add IP aliases
210 * to the loopback interface instead of the interface where the
211 * packets for those addresses are received.
212 */
213int	ip_checkinterface = 0;
214
215
216struct rttimer_queue *ip_mtudisc_timeout_q = NULL;
217
218extern	struct domain inetdomain;
219int	ipqmaxlen = IFQ_MAXLEN;
220u_long	in_ifaddrhash;				/* size of hash table - 1 */
221int	in_ifaddrentries;			/* total number of addrs */
222struct in_ifaddrhead in_ifaddrhead;
223struct	in_ifaddrhashhead *in_ifaddrhashtbl;
224u_long	in_multihash;				/* size of hash table - 1 */
225int	in_multientries;			/* total number of addrs */
226struct	in_multihashhead *in_multihashtbl;
227struct	ifqueue ipintrq;
228struct	ipstat	ipstat;
229uint16_t ip_id;
230
231#ifdef PFIL_HOOKS
232struct pfil_head inet_pfil_hook;
233#endif
234
235struct ipqhead ipq;
236int	ipq_locked;
237int	ip_nfragpackets = 0;
238int	ip_maxfragpackets = 200;
239
240static __inline int ipq_lock_try __P((void));
241static __inline void ipq_unlock __P((void));
242
243static __inline int
244ipq_lock_try()
245{
246	int s;
247
248	/*
249	 * Use splvm() -- we're blocking things that would cause
250	 * mbuf allocation.
251	 */
252	s = splvm();
253	if (ipq_locked) {
254		splx(s);
255		return (0);
256	}
257	ipq_locked = 1;
258	splx(s);
259	return (1);
260}
261
262static __inline void
263ipq_unlock()
264{
265	int s;
266
267	s = splvm();
268	ipq_locked = 0;
269	splx(s);
270}
271
272#ifdef DIAGNOSTIC
273#define	IPQ_LOCK()							\
274do {									\
275	if (ipq_lock_try() == 0) {					\
276		printf("%s:%d: ipq already locked\n", __FILE__, __LINE__); \
277		panic("ipq_lock");					\
278	}								\
279} while (/*CONSTCOND*/ 0)
280#define	IPQ_LOCK_CHECK()						\
281do {									\
282	if (ipq_locked == 0) {						\
283		printf("%s:%d: ipq lock not held\n", __FILE__, __LINE__); \
284		panic("ipq lock check");				\
285	}								\
286} while (/*CONSTCOND*/ 0)
287#else
288#define	IPQ_LOCK()		(void) ipq_lock_try()
289#define	IPQ_LOCK_CHECK()	/* nothing */
290#endif
291
292#define	IPQ_UNLOCK()		ipq_unlock()
293
294struct pool inmulti_pool;
295struct pool ipqent_pool;
296
297#ifdef INET_CSUM_COUNTERS
298#include <sys/device.h>
299
300struct evcnt ip_hwcsum_bad = EVCNT_INITIALIZER(EVCNT_TYPE_MISC,
301    NULL, "inet", "hwcsum bad");
302struct evcnt ip_hwcsum_ok = EVCNT_INITIALIZER(EVCNT_TYPE_MISC,
303    NULL, "inet", "hwcsum ok");
304struct evcnt ip_swcsum = EVCNT_INITIALIZER(EVCNT_TYPE_MISC,
305    NULL, "inet", "swcsum");
306
307#define	INET_CSUM_COUNTER_INCR(ev)	(ev)->ev_count++
308
309#else
310
311#define	INET_CSUM_COUNTER_INCR(ev)	/* nothing */
312
313#endif /* INET_CSUM_COUNTERS */
314
315/*
316 * We need to save the IP options in case a protocol wants to respond
317 * to an incoming packet over the same route if the packet got here
318 * using IP source routing.  This allows connection establishment and
319 * maintenance when the remote end is on a network that is not known
320 * to us.
321 */
322int	ip_nhops = 0;
323static	struct ip_srcrt {
324	struct	in_addr dst;			/* final destination */
325	char	nop;				/* one NOP to align */
326	char	srcopt[IPOPT_OFFSET + 1];	/* OPTVAL, OLEN and OFFSET */
327	struct	in_addr route[MAX_IPOPTLEN/sizeof(struct in_addr)];
328} ip_srcrt;
329
330static void save_rte __P((u_char *, struct in_addr));
331
332#ifdef MBUFTRACE
333struct mowner ip_rx_mowner = { "internet", "rx" };
334struct mowner ip_tx_mowner = { "internet", "tx" };
335#endif
336
337/*
338 * IP initialization: fill in IP protocol switch table.
339 * All protocols not implemented in kernel go to raw IP protocol handler.
340 */
341void
342ip_init()
343{
344	struct protosw *pr;
345	int i;
346
347	pool_init(&inmulti_pool, sizeof(struct in_multi), 0, 0, 0, "inmltpl",
348	    NULL);
349	pool_init(&ipqent_pool, sizeof(struct ipqent), 0, 0, 0, "ipqepl",
350	    NULL);
351
352	pr = pffindproto(PF_INET, IPPROTO_RAW, SOCK_RAW);
353	if (pr == 0)
354		panic("ip_init");
355	for (i = 0; i < IPPROTO_MAX; i++)
356		ip_protox[i] = pr - inetsw;
357	for (pr = inetdomain.dom_protosw;
358	    pr < inetdomain.dom_protoswNPROTOSW; pr++)
359		if (pr->pr_domain->dom_family == PF_INET &&
360		    pr->pr_protocol && pr->pr_protocol != IPPROTO_RAW)
361			ip_protox[pr->pr_protocol] = pr - inetsw;
362	LIST_INIT(&ipq);
363	ip_id = time.tv_sec & 0xfffff;
364	ipintrq.ifq_maxlen = ipqmaxlen;
365	TAILQ_INIT(&in_ifaddrhead);
366	in_ifaddrhashtbl = hashinit(IN_IFADDR_HASH_SIZE, HASH_LIST, M_IFADDR,
367	    M_WAITOK, &in_ifaddrhash);
368	in_multihashtbl = hashinit(IN_IFADDR_HASH_SIZE, HASH_LIST, M_IPMADDR,
369	    M_WAITOK, &in_multihash);
370	ip_mtudisc_timeout_q = rt_timer_queue_create(ip_mtudisc_timeout);
371#ifdef GATEWAY
372	ipflow_init();
373#endif
374
375#ifdef PFIL_HOOKS
376	/* Register our Packet Filter hook. */
377	inet_pfil_hook.ph_type = PFIL_TYPE_AF;
378	inet_pfil_hook.ph_af   = AF_INET;
379	i = pfil_head_register(&inet_pfil_hook);
380	if (i != 0)
381		printf("ip_init: WARNING: unable to register pfil hook, "
382		    "error %d\n", i);
383#endif /* PFIL_HOOKS */
384
385#ifdef INET_CSUM_COUNTERS
386	evcnt_attach_static(&ip_hwcsum_bad);
387	evcnt_attach_static(&ip_hwcsum_ok);
388	evcnt_attach_static(&ip_swcsum);
389#endif /* INET_CSUM_COUNTERS */
390
391#ifdef MBUFTRACE
392	MOWNER_ATTACH(&ip_tx_mowner);
393	MOWNER_ATTACH(&ip_rx_mowner);
394#endif /* MBUFTRACE */
395}
396
397struct	sockaddr_in ipaddr = { sizeof(ipaddr), AF_INET };
398struct	route ipforward_rt;
399
400/*
401 * IP software interrupt routine
402 */
403void
404ipintr()
405{
406	int s;
407	struct mbuf *m;
408
409	while (1) {
410		s = splnet();
411		IF_DEQUEUE(&ipintrq, m);
412		splx(s);
413		if (m == 0)
414			return;
415		MCLAIM(m, &ip_rx_mowner);
416		ip_input(m);
417	}
418}
419
420/*
421 * Ip input routine.  Checksum and byte swap header.  If fragmented
422 * try to reassemble.  Process options.  Pass to next level.
423 */
424void
425ip_input(struct mbuf *m)
426{
427	struct ip *ip = NULL;
428	struct ipq *fp;
429	struct in_ifaddr *ia;
430	struct ifaddr *ifa;
431	struct ipqent *ipqe;
432	int hlen = 0, mff, len;
433	int downmatch;
434	int checkif;
435	int srcrt = 0;
436#ifdef FAST_IPSEC
437	struct m_tag *mtag;
438	struct tdb_ident *tdbi;
439	struct secpolicy *sp;
440	int s, error;
441#endif /* FAST_IPSEC */
442
443	MCLAIM(m, &ip_rx_mowner);
444#ifdef	DIAGNOSTIC
445	if ((m->m_flags & M_PKTHDR) == 0)
446		panic("ipintr no HDR");
447#endif
448
449	/*
450	 * If no IP addresses have been set yet but the interfaces
451	 * are receiving, can't do anything with incoming packets yet.
452	 */
453	if (TAILQ_FIRST(&in_ifaddrhead) == 0)
454		goto bad;
455	ipstat.ips_total++;
456	/*
457	 * If the IP header is not aligned, slurp it up into a new
458	 * mbuf with space for link headers, in the event we forward
459	 * it.  Otherwise, if it is aligned, make sure the entire
460	 * base IP header is in the first mbuf of the chain.
461	 */
462	if (IP_HDR_ALIGNED_P(mtod(m, caddr_t)) == 0) {
463		if ((m = m_copyup(m, sizeof(struct ip),
464				  (max_linkhdr + 3) & ~3)) == NULL) {
465			/* XXXJRT new stat, please */
466			ipstat.ips_toosmall++;
467			return;
468		}
469	} else if (__predict_false(m->m_len < sizeof (struct ip))) {
470		if ((m = m_pullup(m, sizeof (struct ip))) == NULL) {
471			ipstat.ips_toosmall++;
472			return;
473		}
474	}
475	ip = mtod(m, struct ip *);
476	if (ip->ip_v != IPVERSION) {
477		ipstat.ips_badvers++;
478		goto bad;
479	}
480	hlen = ip->ip_hl << 2;
481	if (hlen < sizeof(struct ip)) {	/* minimum header length */
482		ipstat.ips_badhlen++;
483		goto bad;
484	}
485	if (hlen > m->m_len) {
486		if ((m = m_pullup(m, hlen)) == 0) {
487			ipstat.ips_badhlen++;
488			return;
489		}
490		ip = mtod(m, struct ip *);
491	}
492
493	/*
494	 * RFC1122: packets with a multicast source address are
495	 * not allowed.
496	 */
497	if (IN_MULTICAST(ip->ip_src.s_addr)) {
498		ipstat.ips_badaddr++;
499		goto bad;
500	}
501
502	/* 127/8 must not appear on wire - RFC1122 */
503	if ((ntohl(ip->ip_dst.s_addr) >> IN_CLASSA_NSHIFT) == IN_LOOPBACKNET ||
504	    (ntohl(ip->ip_src.s_addr) >> IN_CLASSA_NSHIFT) == IN_LOOPBACKNET) {
505		if ((m->m_pkthdr.rcvif->if_flags & IFF_LOOPBACK) == 0) {
506			ipstat.ips_badaddr++;
507			goto bad;
508		}
509	}
510
511	switch (m->m_pkthdr.csum_flags &
512		((m->m_pkthdr.rcvif->if_csum_flags_rx & M_CSUM_IPv4) |
513		 M_CSUM_IPv4_BAD)) {
514	case M_CSUM_IPv4|M_CSUM_IPv4_BAD:
515		INET_CSUM_COUNTER_INCR(&ip_hwcsum_bad);
516		goto badcsum;
517
518	case M_CSUM_IPv4:
519		/* Checksum was okay. */
520		INET_CSUM_COUNTER_INCR(&ip_hwcsum_ok);
521		break;
522
523	default:
524		/* Must compute it ourselves. */
525		INET_CSUM_COUNTER_INCR(&ip_swcsum);
526		if (in_cksum(m, hlen) != 0)
527			goto bad;
528		break;
529	}
530
531	/* Retrieve the packet length. */
532	len = ntohs(ip->ip_len);
533
534	/*
535	 * Check for additional length bogosity
536	 */
537	if (len < hlen) {
538	 	ipstat.ips_badlen++;
539		goto bad;
540	}
541
542	/*
543	 * Check that the amount of data in the buffers
544	 * is as at least much as the IP header would have us expect.
545	 * Trim mbufs if longer than we expect.
546	 * Drop packet if shorter than we expect.
547	 */
548	if (m->m_pkthdr.len < len) {
549		ipstat.ips_tooshort++;
550		goto bad;
551	}
552	if (m->m_pkthdr.len > len) {
553		if (m->m_len == m->m_pkthdr.len) {
554			m->m_len = len;
555			m->m_pkthdr.len = len;
556		} else
557			m_adj(m, len - m->m_pkthdr.len);
558	}
559
560#ifdef IPSEC
561	/* ipflow (IP fast forwarding) is not compatible with IPsec. */
562	m->m_flags &= ~M_CANFASTFWD;
563#else
564	/*
565	 * Assume that we can create a fast-forward IP flow entry
566	 * based on this packet.
567	 */
568	m->m_flags |= M_CANFASTFWD;
569#endif
570
571#ifdef PFIL_HOOKS
572	/*
573	 * Run through list of hooks for input packets.  If there are any
574	 * filters which require that additional packets in the flow are
575	 * not fast-forwarded, they must clear the M_CANFASTFWD flag.
576	 * Note that filters must _never_ set this flag, as another filter
577	 * in the list may have previously cleared it.
578	 */
579	/*
580	 * let ipfilter look at packet on the wire,
581	 * not the decapsulated packet.
582	 */
583#ifdef IPSEC
584	if (!ipsec_getnhist(m))
585#else
586	if (1)
587#endif
588	{
589		struct in_addr odst;
590
591		odst = ip->ip_dst;
592		if (pfil_run_hooks(&inet_pfil_hook, &m, m->m_pkthdr.rcvif,
593		    PFIL_IN) != 0)
594			return;
595		if (m == NULL)
596			return;
597		ip = mtod(m, struct ip *);
598		hlen = ip->ip_hl << 2;
599		srcrt = (odst.s_addr != ip->ip_dst.s_addr);
600	}
601#endif /* PFIL_HOOKS */
602
603#ifdef ALTQ
604	/* XXX Temporary until ALTQ is changed to use a pfil hook */
605	if (altq_input != NULL && (*altq_input)(m, AF_INET) == 0) {
606		/* packet dropped by traffic conditioner */
607		return;
608	}
609#endif
610
611	/*
612	 * Process options and, if not destined for us,
613	 * ship it on.  ip_dooptions returns 1 when an
614	 * error was detected (causing an icmp message
615	 * to be sent and the original packet to be freed).
616	 */
617	ip_nhops = 0;		/* for source routed packets */
618	if (hlen > sizeof (struct ip) && ip_dooptions(m))
619		return;
620
621	/*
622	 * Enable a consistency check between the destination address
623	 * and the arrival interface for a unicast packet (the RFC 1122
624	 * strong ES model) if IP forwarding is disabled and the packet
625	 * is not locally generated.
626	 *
627	 * XXX - Checking also should be disabled if the destination
628	 * address is ipnat'ed to a different interface.
629	 *
630	 * XXX - Checking is incompatible with IP aliases added
631	 * to the loopback interface instead of the interface where
632	 * the packets are received.
633	 *
634	 * XXX - We need to add a per ifaddr flag for this so that
635	 * we get finer grain control.
636	 */
637	checkif = ip_checkinterface && (ipforwarding == 0) &&
638	    (m->m_pkthdr.rcvif != NULL) &&
639	    ((m->m_pkthdr.rcvif->if_flags & IFF_LOOPBACK) == 0);
640
641	/*
642	 * Check our list of addresses, to see if the packet is for us.
643	 *
644	 * Traditional 4.4BSD did not consult IFF_UP at all.
645	 * The behavior here is to treat addresses on !IFF_UP interface
646	 * as not mine.
647	 */
648	downmatch = 0;
649	LIST_FOREACH(ia, &IN_IFADDR_HASH(ip->ip_dst.s_addr), ia_hash) {
650		if (in_hosteq(ia->ia_addr.sin_addr, ip->ip_dst)) {
651			if (checkif && ia->ia_ifp != m->m_pkthdr.rcvif)
652				continue;
653			if ((ia->ia_ifp->if_flags & IFF_UP) != 0)
654				break;
655			else
656				downmatch++;
657		}
658	}
659	if (ia != NULL)
660		goto ours;
661	if (m->m_pkthdr.rcvif->if_flags & IFF_BROADCAST) {
662		TAILQ_FOREACH(ifa, &m->m_pkthdr.rcvif->if_addrlist, ifa_list) {
663			if (ifa->ifa_addr->sa_family != AF_INET)
664				continue;
665			ia = ifatoia(ifa);
666			if (in_hosteq(ip->ip_dst, ia->ia_broadaddr.sin_addr) ||
667			    in_hosteq(ip->ip_dst, ia->ia_netbroadcast) ||
668			    /*
669			     * Look for all-0's host part (old broadcast addr),
670			     * either for subnet or net.
671			     */
672			    ip->ip_dst.s_addr == ia->ia_subnet ||
673			    ip->ip_dst.s_addr == ia->ia_net)
674				goto ours;
675			/*
676			 * An interface with IP address zero accepts
677			 * all packets that arrive on that interface.
678			 */
679			if (in_nullhost(ia->ia_addr.sin_addr))
680				goto ours;
681		}
682	}
683	if (IN_MULTICAST(ip->ip_dst.s_addr)) {
684		struct in_multi *inm;
685#ifdef MROUTING
686		extern struct socket *ip_mrouter;
687
688		if (M_READONLY(m)) {
689			if ((m = m_pullup(m, hlen)) == 0) {
690				ipstat.ips_toosmall++;
691				return;
692			}
693			ip = mtod(m, struct ip *);
694		}
695
696		if (ip_mrouter) {
697			/*
698			 * If we are acting as a multicast router, all
699			 * incoming multicast packets are passed to the
700			 * kernel-level multicast forwarding function.
701			 * The packet is returned (relatively) intact; if
702			 * ip_mforward() returns a non-zero value, the packet
703			 * must be discarded, else it may be accepted below.
704			 *
705			 * (The IP ident field is put in the same byte order
706			 * as expected when ip_mforward() is called from
707			 * ip_output().)
708			 */
709			if (ip_mforward(m, m->m_pkthdr.rcvif) != 0) {
710				ipstat.ips_cantforward++;
711				m_freem(m);
712				return;
713			}
714
715			/*
716			 * The process-level routing demon needs to receive
717			 * all multicast IGMP packets, whether or not this
718			 * host belongs to their destination groups.
719			 */
720			if (ip->ip_p == IPPROTO_IGMP)
721				goto ours;
722			ipstat.ips_forward++;
723		}
724#endif
725		/*
726		 * See if we belong to the destination multicast group on the
727		 * arrival interface.
728		 */
729		IN_LOOKUP_MULTI(ip->ip_dst, m->m_pkthdr.rcvif, inm);
730		if (inm == NULL) {
731			ipstat.ips_cantforward++;
732			m_freem(m);
733			return;
734		}
735		goto ours;
736	}
737	if (ip->ip_dst.s_addr == INADDR_BROADCAST ||
738	    in_nullhost(ip->ip_dst))
739		goto ours;
740
741	/*
742	 * Not for us; forward if possible and desirable.
743	 */
744	if (ipforwarding == 0) {
745		ipstat.ips_cantforward++;
746		m_freem(m);
747	} else {
748		/*
749		 * If ip_dst matched any of my address on !IFF_UP interface,
750		 * and there's no IFF_UP interface that matches ip_dst,
751		 * send icmp unreach.  Forwarding it will result in in-kernel
752		 * forwarding loop till TTL goes to 0.
753		 */
754		if (downmatch) {
755			icmp_error(m, ICMP_UNREACH, ICMP_UNREACH_HOST, 0, 0);
756			ipstat.ips_cantforward++;
757			return;
758		}
759#ifdef IPSEC
760		if (ipsec4_in_reject(m, NULL)) {
761			ipsecstat.in_polvio++;
762			goto bad;
763		}
764#endif
765#ifdef FAST_IPSEC
766		mtag = m_tag_find(m, PACKET_TAG_IPSEC_IN_DONE, NULL);
767		s = splsoftnet();
768		if (mtag != NULL) {
769			tdbi = (struct tdb_ident *)(mtag + 1);
770			sp = ipsec_getpolicy(tdbi, IPSEC_DIR_INBOUND);
771		} else {
772			sp = ipsec_getpolicybyaddr(m, IPSEC_DIR_INBOUND,
773						   IP_FORWARDING, &error);
774		}
775		if (sp == NULL) {	/* NB: can happen if error */
776			splx(s);
777			/*XXX error stat???*/
778			DPRINTF(("ip_input: no SP for forwarding\n"));	/*XXX*/
779			goto bad;
780		}
781
782		/*
783		 * Check security policy against packet attributes.
784		 */
785		error = ipsec_in_reject(sp, m);
786		KEY_FREESP(&sp);
787		splx(s);
788		if (error) {
789			ipstat.ips_cantforward++;
790			goto bad;
791		}
792#endif	/* FAST_IPSEC */
793
794		ip_forward(m, srcrt);
795	}
796	return;
797
798ours:
799	/*
800	 * If offset or IP_MF are set, must reassemble.
801	 * Otherwise, nothing need be done.
802	 * (We could look in the reassembly queue to see
803	 * if the packet was previously fragmented,
804	 * but it's not worth the time; just let them time out.)
805	 */
806	if (ip->ip_off & ~htons(IP_DF|IP_RF)) {
807		if (M_READONLY(m)) {
808			if ((m = m_pullup(m, hlen)) == NULL) {
809				ipstat.ips_toosmall++;
810				goto bad;
811			}
812			ip = mtod(m, struct ip *);
813		}
814
815		/*
816		 * Look for queue of fragments
817		 * of this datagram.
818		 */
819		IPQ_LOCK();
820		LIST_FOREACH(fp, &ipq, ipq_q)
821			if (ip->ip_id == fp->ipq_id &&
822			    in_hosteq(ip->ip_src, fp->ipq_src) &&
823			    in_hosteq(ip->ip_dst, fp->ipq_dst) &&
824			    ip->ip_p == fp->ipq_p)
825				goto found;
826		fp = 0;
827found:
828
829		/*
830		 * Adjust ip_len to not reflect header,
831		 * set ipqe_mff if more fragments are expected,
832		 * convert offset of this to bytes.
833		 */
834		ip->ip_len = htons(ntohs(ip->ip_len) - hlen);
835		mff = (ip->ip_off & htons(IP_MF)) != 0;
836		if (mff) {
837		        /*
838		         * Make sure that fragments have a data length
839			 * that's a non-zero multiple of 8 bytes.
840		         */
841			if (ntohs(ip->ip_len) == 0 ||
842			    (ntohs(ip->ip_len) & 0x7) != 0) {
843				ipstat.ips_badfrags++;
844				IPQ_UNLOCK();
845				goto bad;
846			}
847		}
848		ip->ip_off = htons((ntohs(ip->ip_off) & IP_OFFMASK) << 3);
849
850		/*
851		 * If datagram marked as having more fragments
852		 * or if this is not the first fragment,
853		 * attempt reassembly; if it succeeds, proceed.
854		 */
855		if (mff || ip->ip_off != htons(0)) {
856			ipstat.ips_fragments++;
857			ipqe = pool_get(&ipqent_pool, PR_NOWAIT);
858			if (ipqe == NULL) {
859				ipstat.ips_rcvmemdrop++;
860				IPQ_UNLOCK();
861				goto bad;
862			}
863			ipqe->ipqe_mff = mff;
864			ipqe->ipqe_m = m;
865			ipqe->ipqe_ip = ip;
866			m = ip_reass(ipqe, fp);
867			if (m == 0) {
868				IPQ_UNLOCK();
869				return;
870			}
871			ipstat.ips_reassembled++;
872			ip = mtod(m, struct ip *);
873			hlen = ip->ip_hl << 2;
874			ip->ip_len = htons(ntohs(ip->ip_len) + hlen);
875		} else
876			if (fp)
877				ip_freef(fp);
878		IPQ_UNLOCK();
879	}
880
881#if defined(IPSEC)
882	/*
883	 * enforce IPsec policy checking if we are seeing last header.
884	 * note that we do not visit this with protocols with pcb layer
885	 * code - like udp/tcp/raw ip.
886	 */
887	if ((inetsw[ip_protox[ip->ip_p]].pr_flags & PR_LASTHDR) != 0 &&
888	    ipsec4_in_reject(m, NULL)) {
889		ipsecstat.in_polvio++;
890		goto bad;
891	}
892#endif
893#if FAST_IPSEC
894	/*
895	 * enforce IPsec policy checking if we are seeing last header.
896	 * note that we do not visit this with protocols with pcb layer
897	 * code - like udp/tcp/raw ip.
898	 */
899	if ((inetsw[ip_protox[ip->ip_p]].pr_flags & PR_LASTHDR) != 0) {
900		/*
901		 * Check if the packet has already had IPsec processing
902		 * done.  If so, then just pass it along.  This tag gets
903		 * set during AH, ESP, etc. input handling, before the
904		 * packet is returned to the ip input queue for delivery.
905		 */
906		mtag = m_tag_find(m, PACKET_TAG_IPSEC_IN_DONE, NULL);
907		s = splsoftnet();
908		if (mtag != NULL) {
909			tdbi = (struct tdb_ident *)(mtag + 1);
910			sp = ipsec_getpolicy(tdbi, IPSEC_DIR_INBOUND);
911		} else {
912			sp = ipsec_getpolicybyaddr(m, IPSEC_DIR_INBOUND,
913						   IP_FORWARDING, &error);
914		}
915		if (sp != NULL) {
916			/*
917			 * Check security policy against packet attributes.
918			 */
919			error = ipsec_in_reject(sp, m);
920			KEY_FREESP(&sp);
921		} else {
922			/* XXX error stat??? */
923			error = EINVAL;
924DPRINTF(("ip_input: no SP, packet discarded\n"));/*XXX*/
925			goto bad;
926		}
927		splx(s);
928		if (error)
929			goto bad;
930	}
931#endif /* FAST_IPSEC */
932
933	/*
934	 * Switch out to protocol's input routine.
935	 */
936#if IFA_STATS
937	if (ia && ip)
938		ia->ia_ifa.ifa_data.ifad_inbytes += ntohs(ip->ip_len);
939#endif
940	ipstat.ips_delivered++;
941    {
942	int off = hlen, nh = ip->ip_p;
943
944	(*inetsw[ip_protox[nh]].pr_input)(m, off, nh);
945	return;
946    }
947bad:
948	m_freem(m);
949	return;
950
951badcsum:
952	ipstat.ips_badsum++;
953	m_freem(m);
954}
955
956/*
957 * Take incoming datagram fragment and try to
958 * reassemble it into whole datagram.  If a chain for
959 * reassembly of this datagram already exists, then it
960 * is given as fp; otherwise have to make a chain.
961 */
962struct mbuf *
963ip_reass(ipqe, fp)
964	struct ipqent *ipqe;
965	struct ipq *fp;
966{
967	struct mbuf *m = ipqe->ipqe_m;
968	struct ipqent *nq, *p, *q;
969	struct ip *ip;
970	struct mbuf *t;
971	int hlen = ipqe->ipqe_ip->ip_hl << 2;
972	int i, next;
973
974	IPQ_LOCK_CHECK();
975
976	/*
977	 * Presence of header sizes in mbufs
978	 * would confuse code below.
979	 */
980	m->m_data += hlen;
981	m->m_len -= hlen;
982
983	/*
984	 * If first fragment to arrive, create a reassembly queue.
985	 */
986	if (fp == 0) {
987		/*
988		 * Enforce upper bound on number of fragmented packets
989		 * for which we attempt reassembly;
990		 * If maxfrag is 0, never accept fragments.
991		 * If maxfrag is -1, accept all fragments without limitation.
992		 */
993		if (ip_maxfragpackets < 0)
994			;
995		else if (ip_nfragpackets >= ip_maxfragpackets)
996			goto dropfrag;
997		ip_nfragpackets++;
998		MALLOC(fp, struct ipq *, sizeof (struct ipq),
999		    M_FTABLE, M_NOWAIT);
1000		if (fp == NULL)
1001			goto dropfrag;
1002		LIST_INSERT_HEAD(&ipq, fp, ipq_q);
1003		fp->ipq_ttl = IPFRAGTTL;
1004		fp->ipq_p = ipqe->ipqe_ip->ip_p;
1005		fp->ipq_id = ipqe->ipqe_ip->ip_id;
1006		TAILQ_INIT(&fp->ipq_fragq);
1007		fp->ipq_src = ipqe->ipqe_ip->ip_src;
1008		fp->ipq_dst = ipqe->ipqe_ip->ip_dst;
1009		p = NULL;
1010		goto insert;
1011	}
1012
1013	/*
1014	 * Find a segment which begins after this one does.
1015	 */
1016	for (p = NULL, q = TAILQ_FIRST(&fp->ipq_fragq); q != NULL;
1017	    p = q, q = TAILQ_NEXT(q, ipqe_q))
1018		if (ntohs(q->ipqe_ip->ip_off) > ntohs(ipqe->ipqe_ip->ip_off))
1019			break;
1020
1021	/*
1022	 * If there is a preceding segment, it may provide some of
1023	 * our data already.  If so, drop the data from the incoming
1024	 * segment.  If it provides all of our data, drop us.
1025	 */
1026	if (p != NULL) {
1027		i = ntohs(p->ipqe_ip->ip_off) + ntohs(p->ipqe_ip->ip_len) -
1028		    ntohs(ipqe->ipqe_ip->ip_off);
1029		if (i > 0) {
1030			if (i >= ntohs(ipqe->ipqe_ip->ip_len))
1031				goto dropfrag;
1032			m_adj(ipqe->ipqe_m, i);
1033			ipqe->ipqe_ip->ip_off =
1034			    htons(ntohs(ipqe->ipqe_ip->ip_off) + i);
1035			ipqe->ipqe_ip->ip_len =
1036			    htons(ntohs(ipqe->ipqe_ip->ip_len) - i);
1037		}
1038	}
1039
1040	/*
1041	 * While we overlap succeeding segments trim them or,
1042	 * if they are completely covered, dequeue them.
1043	 */
1044	for (; q != NULL &&
1045	    ntohs(ipqe->ipqe_ip->ip_off) + ntohs(ipqe->ipqe_ip->ip_len) >
1046	    ntohs(q->ipqe_ip->ip_off); q = nq) {
1047		i = (ntohs(ipqe->ipqe_ip->ip_off) +
1048		    ntohs(ipqe->ipqe_ip->ip_len)) - ntohs(q->ipqe_ip->ip_off);
1049		if (i < ntohs(q->ipqe_ip->ip_len)) {
1050			q->ipqe_ip->ip_len =
1051			    htons(ntohs(q->ipqe_ip->ip_len) - i);
1052			q->ipqe_ip->ip_off =
1053			    htons(ntohs(q->ipqe_ip->ip_off) + i);
1054			m_adj(q->ipqe_m, i);
1055			break;
1056		}
1057		nq = TAILQ_NEXT(q, ipqe_q);
1058		m_freem(q->ipqe_m);
1059		TAILQ_REMOVE(&fp->ipq_fragq, q, ipqe_q);
1060		pool_put(&ipqent_pool, q);
1061	}
1062
1063insert:
1064	/*
1065	 * Stick new segment in its place;
1066	 * check for complete reassembly.
1067	 */
1068	if (p == NULL) {
1069		TAILQ_INSERT_HEAD(&fp->ipq_fragq, ipqe, ipqe_q);
1070	} else {
1071		TAILQ_INSERT_AFTER(&fp->ipq_fragq, p, ipqe, ipqe_q);
1072	}
1073	next = 0;
1074	for (p = NULL, q = TAILQ_FIRST(&fp->ipq_fragq); q != NULL;
1075	    p = q, q = TAILQ_NEXT(q, ipqe_q)) {
1076		if (ntohs(q->ipqe_ip->ip_off) != next)
1077			return (0);
1078		next += ntohs(q->ipqe_ip->ip_len);
1079	}
1080	if (p->ipqe_mff)
1081		return (0);
1082
1083	/*
1084	 * Reassembly is complete.  Check for a bogus message size and
1085	 * concatenate fragments.
1086	 */
1087	q = TAILQ_FIRST(&fp->ipq_fragq);
1088	ip = q->ipqe_ip;
1089	if ((next + (ip->ip_hl << 2)) > IP_MAXPACKET) {
1090		ipstat.ips_toolong++;
1091		ip_freef(fp);
1092		return (0);
1093	}
1094	m = q->ipqe_m;
1095	t = m->m_next;
1096	m->m_next = 0;
1097	m_cat(m, t);
1098	nq = TAILQ_NEXT(q, ipqe_q);
1099	pool_put(&ipqent_pool, q);
1100	for (q = nq; q != NULL; q = nq) {
1101		t = q->ipqe_m;
1102		nq = TAILQ_NEXT(q, ipqe_q);
1103		pool_put(&ipqent_pool, q);
1104		m_cat(m, t);
1105	}
1106
1107	/*
1108	 * Create header for new ip packet by
1109	 * modifying header of first packet;
1110	 * dequeue and discard fragment reassembly header.
1111	 * Make header visible.
1112	 */
1113	ip->ip_len = htons(next);
1114	ip->ip_src = fp->ipq_src;
1115	ip->ip_dst = fp->ipq_dst;
1116	LIST_REMOVE(fp, ipq_q);
1117	FREE(fp, M_FTABLE);
1118	ip_nfragpackets--;
1119	m->m_len += (ip->ip_hl << 2);
1120	m->m_data -= (ip->ip_hl << 2);
1121	/* some debugging cruft by sklower, below, will go away soon */
1122	if (m->m_flags & M_PKTHDR) { /* XXX this should be done elsewhere */
1123		int plen = 0;
1124		for (t = m; t; t = t->m_next)
1125			plen += t->m_len;
1126		m->m_pkthdr.len = plen;
1127	}
1128	return (m);
1129
1130dropfrag:
1131	ipstat.ips_fragdropped++;
1132	m_freem(m);
1133	pool_put(&ipqent_pool, ipqe);
1134	return (0);
1135}
1136
1137/*
1138 * Free a fragment reassembly header and all
1139 * associated datagrams.
1140 */
1141void
1142ip_freef(fp)
1143	struct ipq *fp;
1144{
1145	struct ipqent *q, *p;
1146
1147	IPQ_LOCK_CHECK();
1148
1149	for (q = TAILQ_FIRST(&fp->ipq_fragq); q != NULL; q = p) {
1150		p = TAILQ_NEXT(q, ipqe_q);
1151		m_freem(q->ipqe_m);
1152		TAILQ_REMOVE(&fp->ipq_fragq, q, ipqe_q);
1153		pool_put(&ipqent_pool, q);
1154	}
1155	LIST_REMOVE(fp, ipq_q);
1156	FREE(fp, M_FTABLE);
1157	ip_nfragpackets--;
1158}
1159
1160/*
1161 * IP timer processing;
1162 * if a timer expires on a reassembly
1163 * queue, discard it.
1164 */
1165void
1166ip_slowtimo()
1167{
1168	struct ipq *fp, *nfp;
1169	int s = splsoftnet();
1170
1171	IPQ_LOCK();
1172	for (fp = LIST_FIRST(&ipq); fp != NULL; fp = nfp) {
1173		nfp = LIST_NEXT(fp, ipq_q);
1174		if (--fp->ipq_ttl == 0) {
1175			ipstat.ips_fragtimeout++;
1176			ip_freef(fp);
1177		}
1178	}
1179	/*
1180	 * If we are over the maximum number of fragments
1181	 * (due to the limit being lowered), drain off
1182	 * enough to get down to the new limit.
1183	 */
1184	if (ip_maxfragpackets < 0)
1185		;
1186	else {
1187		while (ip_nfragpackets > ip_maxfragpackets && LIST_FIRST(&ipq))
1188			ip_freef(LIST_FIRST(&ipq));
1189	}
1190	IPQ_UNLOCK();
1191#ifdef GATEWAY
1192	ipflow_slowtimo();
1193#endif
1194	splx(s);
1195}
1196
1197/*
1198 * Drain off all datagram fragments.
1199 */
1200void
1201ip_drain()
1202{
1203
1204	/*
1205	 * We may be called from a device's interrupt context.  If
1206	 * the ipq is already busy, just bail out now.
1207	 */
1208	if (ipq_lock_try() == 0)
1209		return;
1210
1211	while (LIST_FIRST(&ipq) != NULL) {
1212		ipstat.ips_fragdropped++;
1213		ip_freef(LIST_FIRST(&ipq));
1214	}
1215
1216	IPQ_UNLOCK();
1217}
1218
1219/*
1220 * Do option processing on a datagram,
1221 * possibly discarding it if bad options are encountered,
1222 * or forwarding it if source-routed.
1223 * Returns 1 if packet has been forwarded/freed,
1224 * 0 if the packet should be processed further.
1225 */
1226int
1227ip_dooptions(m)
1228	struct mbuf *m;
1229{
1230	struct ip *ip = mtod(m, struct ip *);
1231	u_char *cp, *cp0;
1232	struct ip_timestamp *ipt;
1233	struct in_ifaddr *ia;
1234	int opt, optlen, cnt, off, code, type = ICMP_PARAMPROB, forward = 0;
1235	struct in_addr dst;
1236	n_time ntime;
1237
1238	dst = ip->ip_dst;
1239	cp = (u_char *)(ip + 1);
1240	cnt = (ip->ip_hl << 2) - sizeof (struct ip);
1241	for (; cnt > 0; cnt -= optlen, cp += optlen) {
1242		opt = cp[IPOPT_OPTVAL];
1243		if (opt == IPOPT_EOL)
1244			break;
1245		if (opt == IPOPT_NOP)
1246			optlen = 1;
1247		else {
1248			if (cnt < IPOPT_OLEN + sizeof(*cp)) {
1249				code = &cp[IPOPT_OLEN] - (u_char *)ip;
1250				goto bad;
1251			}
1252			optlen = cp[IPOPT_OLEN];
1253			if (optlen < IPOPT_OLEN + sizeof(*cp) || optlen > cnt) {
1254				code = &cp[IPOPT_OLEN] - (u_char *)ip;
1255				goto bad;
1256			}
1257		}
1258		switch (opt) {
1259
1260		default:
1261			break;
1262
1263		/*
1264		 * Source routing with record.
1265		 * Find interface with current destination address.
1266		 * If none on this machine then drop if strictly routed,
1267		 * or do nothing if loosely routed.
1268		 * Record interface address and bring up next address
1269		 * component.  If strictly routed make sure next
1270		 * address is on directly accessible net.
1271		 */
1272		case IPOPT_LSRR:
1273		case IPOPT_SSRR:
1274			if (ip_allowsrcrt == 0) {
1275				type = ICMP_UNREACH;
1276				code = ICMP_UNREACH_NET_PROHIB;
1277				goto bad;
1278			}
1279			if (optlen < IPOPT_OFFSET + sizeof(*cp)) {
1280				code = &cp[IPOPT_OLEN] - (u_char *)ip;
1281				goto bad;
1282			}
1283			if ((off = cp[IPOPT_OFFSET]) < IPOPT_MINOFF) {
1284				code = &cp[IPOPT_OFFSET] - (u_char *)ip;
1285				goto bad;
1286			}
1287			ipaddr.sin_addr = ip->ip_dst;
1288			ia = ifatoia(ifa_ifwithaddr(sintosa(&ipaddr)));
1289			if (ia == 0) {
1290				if (opt == IPOPT_SSRR) {
1291					type = ICMP_UNREACH;
1292					code = ICMP_UNREACH_SRCFAIL;
1293					goto bad;
1294				}
1295				/*
1296				 * Loose routing, and not at next destination
1297				 * yet; nothing to do except forward.
1298				 */
1299				break;
1300			}
1301			off--;			/* 0 origin */
1302			if ((off + sizeof(struct in_addr)) > optlen) {
1303				/*
1304				 * End of source route.  Should be for us.
1305				 */
1306				save_rte(cp, ip->ip_src);
1307				break;
1308			}
1309			/*
1310			 * locate outgoing interface
1311			 */
1312			bcopy((caddr_t)(cp + off), (caddr_t)&ipaddr.sin_addr,
1313			    sizeof(ipaddr.sin_addr));
1314			if (opt == IPOPT_SSRR)
1315				ia = ifatoia(ifa_ifwithaddr(sintosa(&ipaddr)));
1316			else
1317				ia = ip_rtaddr(ipaddr.sin_addr);
1318			if (ia == 0) {
1319				type = ICMP_UNREACH;
1320				code = ICMP_UNREACH_SRCFAIL;
1321				goto bad;
1322			}
1323			ip->ip_dst = ipaddr.sin_addr;
1324			bcopy((caddr_t)&ia->ia_addr.sin_addr,
1325			    (caddr_t)(cp + off), sizeof(struct in_addr));
1326			cp[IPOPT_OFFSET] += sizeof(struct in_addr);
1327			/*
1328			 * Let ip_intr's mcast routing check handle mcast pkts
1329			 */
1330			forward = !IN_MULTICAST(ip->ip_dst.s_addr);
1331			break;
1332
1333		case IPOPT_RR:
1334			if (optlen < IPOPT_OFFSET + sizeof(*cp)) {
1335				code = &cp[IPOPT_OLEN] - (u_char *)ip;
1336				goto bad;
1337			}
1338			if ((off = cp[IPOPT_OFFSET]) < IPOPT_MINOFF) {
1339				code = &cp[IPOPT_OFFSET] - (u_char *)ip;
1340				goto bad;
1341			}
1342			/*
1343			 * If no space remains, ignore.
1344			 */
1345			off--;			/* 0 origin */
1346			if ((off + sizeof(struct in_addr)) > optlen)
1347				break;
1348			bcopy((caddr_t)(&ip->ip_dst), (caddr_t)&ipaddr.sin_addr,
1349			    sizeof(ipaddr.sin_addr));
1350			/*
1351			 * locate outgoing interface; if we're the destination,
1352			 * use the incoming interface (should be same).
1353			 */
1354			if ((ia = ifatoia(ifa_ifwithaddr(sintosa(&ipaddr))))
1355			    == NULL &&
1356			    (ia = ip_rtaddr(ipaddr.sin_addr)) == NULL) {
1357				type = ICMP_UNREACH;
1358				code = ICMP_UNREACH_HOST;
1359				goto bad;
1360			}
1361			bcopy((caddr_t)&ia->ia_addr.sin_addr,
1362			    (caddr_t)(cp + off), sizeof(struct in_addr));
1363			cp[IPOPT_OFFSET] += sizeof(struct in_addr);
1364			break;
1365
1366		case IPOPT_TS:
1367			code = cp - (u_char *)ip;
1368			ipt = (struct ip_timestamp *)cp;
1369			if (ipt->ipt_len < 4 || ipt->ipt_len > 40) {
1370				code = (u_char *)&ipt->ipt_len - (u_char *)ip;
1371				goto bad;
1372			}
1373			if (ipt->ipt_ptr < 5) {
1374				code = (u_char *)&ipt->ipt_ptr - (u_char *)ip;
1375				goto bad;
1376			}
1377			if (ipt->ipt_ptr > ipt->ipt_len - sizeof (int32_t)) {
1378				if (++ipt->ipt_oflw == 0) {
1379					code = (u_char *)&ipt->ipt_ptr -
1380					    (u_char *)ip;
1381					goto bad;
1382				}
1383				break;
1384			}
1385			cp0 = (cp + ipt->ipt_ptr - 1);
1386			switch (ipt->ipt_flg) {
1387
1388			case IPOPT_TS_TSONLY:
1389				break;
1390
1391			case IPOPT_TS_TSANDADDR:
1392				if (ipt->ipt_ptr - 1 + sizeof(n_time) +
1393				    sizeof(struct in_addr) > ipt->ipt_len) {
1394					code = (u_char *)&ipt->ipt_ptr -
1395					    (u_char *)ip;
1396					goto bad;
1397				}
1398				ipaddr.sin_addr = dst;
1399				ia = ifatoia(ifaof_ifpforaddr(sintosa(&ipaddr),
1400				    m->m_pkthdr.rcvif));
1401				if (ia == 0)
1402					continue;
1403				bcopy(&ia->ia_addr.sin_addr,
1404				    cp0, sizeof(struct in_addr));
1405				ipt->ipt_ptr += sizeof(struct in_addr);
1406				break;
1407
1408			case IPOPT_TS_PRESPEC:
1409				if (ipt->ipt_ptr - 1 + sizeof(n_time) +
1410				    sizeof(struct in_addr) > ipt->ipt_len) {
1411					code = (u_char *)&ipt->ipt_ptr -
1412					    (u_char *)ip;
1413					goto bad;
1414				}
1415				bcopy(cp0, &ipaddr.sin_addr,
1416				    sizeof(struct in_addr));
1417				if (ifatoia(ifa_ifwithaddr(sintosa(&ipaddr)))
1418				    == NULL)
1419					continue;
1420				ipt->ipt_ptr += sizeof(struct in_addr);
1421				break;
1422
1423			default:
1424				/* XXX can't take &ipt->ipt_flg */
1425				code = (u_char *)&ipt->ipt_ptr -
1426				    (u_char *)ip + 1;
1427				goto bad;
1428			}
1429			ntime = iptime();
1430			cp0 = (u_char *) &ntime; /* XXX grumble, GCC... */
1431			bcopy(cp0, (caddr_t)cp + ipt->ipt_ptr - 1,
1432			    sizeof(n_time));
1433			ipt->ipt_ptr += sizeof(n_time);
1434		}
1435	}
1436	if (forward) {
1437		if (ip_forwsrcrt == 0) {
1438			type = ICMP_UNREACH;
1439			code = ICMP_UNREACH_SRCFAIL;
1440			goto bad;
1441		}
1442		ip_forward(m, 1);
1443		return (1);
1444	}
1445	return (0);
1446bad:
1447	icmp_error(m, type, code, 0, 0);
1448	ipstat.ips_badoptions++;
1449	return (1);
1450}
1451
1452/*
1453 * Given address of next destination (final or next hop),
1454 * return internet address info of interface to be used to get there.
1455 */
1456struct in_ifaddr *
1457ip_rtaddr(dst)
1458	 struct in_addr dst;
1459{
1460	struct sockaddr_in *sin;
1461
1462	sin = satosin(&ipforward_rt.ro_dst);
1463
1464	if (ipforward_rt.ro_rt == 0 || !in_hosteq(dst, sin->sin_addr)) {
1465		if (ipforward_rt.ro_rt) {
1466			RTFREE(ipforward_rt.ro_rt);
1467			ipforward_rt.ro_rt = 0;
1468		}
1469		sin->sin_family = AF_INET;
1470		sin->sin_len = sizeof(*sin);
1471		sin->sin_addr = dst;
1472
1473		rtalloc(&ipforward_rt);
1474	}
1475	if (ipforward_rt.ro_rt == 0)
1476		return ((struct in_ifaddr *)0);
1477	return (ifatoia(ipforward_rt.ro_rt->rt_ifa));
1478}
1479
1480/*
1481 * Save incoming source route for use in replies,
1482 * to be picked up later by ip_srcroute if the receiver is interested.
1483 */
1484void
1485save_rte(option, dst)
1486	u_char *option;
1487	struct in_addr dst;
1488{
1489	unsigned olen;
1490
1491	olen = option[IPOPT_OLEN];
1492#ifdef DIAGNOSTIC
1493	if (ipprintfs)
1494		printf("save_rte: olen %d\n", olen);
1495#endif /* 0 */
1496	if (olen > sizeof(ip_srcrt) - (1 + sizeof(dst)))
1497		return;
1498	bcopy((caddr_t)option, (caddr_t)ip_srcrt.srcopt, olen);
1499	ip_nhops = (olen - IPOPT_OFFSET - 1) / sizeof(struct in_addr);
1500	ip_srcrt.dst = dst;
1501}
1502
1503/*
1504 * Retrieve incoming source route for use in replies,
1505 * in the same form used by setsockopt.
1506 * The first hop is placed before the options, will be removed later.
1507 */
1508struct mbuf *
1509ip_srcroute()
1510{
1511	struct in_addr *p, *q;
1512	struct mbuf *m;
1513
1514	if (ip_nhops == 0)
1515		return ((struct mbuf *)0);
1516	m = m_get(M_DONTWAIT, MT_SOOPTS);
1517	if (m == 0)
1518		return ((struct mbuf *)0);
1519
1520	MCLAIM(m, &inetdomain.dom_mowner);
1521#define OPTSIZ	(sizeof(ip_srcrt.nop) + sizeof(ip_srcrt.srcopt))
1522
1523	/* length is (nhops+1)*sizeof(addr) + sizeof(nop + srcrt header) */
1524	m->m_len = ip_nhops * sizeof(struct in_addr) + sizeof(struct in_addr) +
1525	    OPTSIZ;
1526#ifdef DIAGNOSTIC
1527	if (ipprintfs)
1528		printf("ip_srcroute: nhops %d mlen %d", ip_nhops, m->m_len);
1529#endif
1530
1531	/*
1532	 * First save first hop for return route
1533	 */
1534	p = &ip_srcrt.route[ip_nhops - 1];
1535	*(mtod(m, struct in_addr *)) = *p--;
1536#ifdef DIAGNOSTIC
1537	if (ipprintfs)
1538		printf(" hops %x", ntohl(mtod(m, struct in_addr *)->s_addr));
1539#endif
1540
1541	/*
1542	 * Copy option fields and padding (nop) to mbuf.
1543	 */
1544	ip_srcrt.nop = IPOPT_NOP;
1545	ip_srcrt.srcopt[IPOPT_OFFSET] = IPOPT_MINOFF;
1546	bcopy((caddr_t)&ip_srcrt.nop,
1547	    mtod(m, caddr_t) + sizeof(struct in_addr), OPTSIZ);
1548	q = (struct in_addr *)(mtod(m, caddr_t) +
1549	    sizeof(struct in_addr) + OPTSIZ);
1550#undef OPTSIZ
1551	/*
1552	 * Record return path as an IP source route,
1553	 * reversing the path (pointers are now aligned).
1554	 */
1555	while (p >= ip_srcrt.route) {
1556#ifdef DIAGNOSTIC
1557		if (ipprintfs)
1558			printf(" %x", ntohl(q->s_addr));
1559#endif
1560		*q++ = *p--;
1561	}
1562	/*
1563	 * Last hop goes to final destination.
1564	 */
1565	*q = ip_srcrt.dst;
1566#ifdef DIAGNOSTIC
1567	if (ipprintfs)
1568		printf(" %x\n", ntohl(q->s_addr));
1569#endif
1570	return (m);
1571}
1572
1573/*
1574 * Strip out IP options, at higher
1575 * level protocol in the kernel.
1576 * Second argument is buffer to which options
1577 * will be moved, and return value is their length.
1578 * XXX should be deleted; last arg currently ignored.
1579 */
1580void
1581ip_stripoptions(m, mopt)
1582	struct mbuf *m;
1583	struct mbuf *mopt;
1584{
1585	int i;
1586	struct ip *ip = mtod(m, struct ip *);
1587	caddr_t opts;
1588	int olen;
1589
1590	olen = (ip->ip_hl << 2) - sizeof (struct ip);
1591	opts = (caddr_t)(ip + 1);
1592	i = m->m_len - (sizeof (struct ip) + olen);
1593	bcopy(opts  + olen, opts, (unsigned)i);
1594	m->m_len -= olen;
1595	if (m->m_flags & M_PKTHDR)
1596		m->m_pkthdr.len -= olen;
1597	ip->ip_len = htons(ntohs(ip->ip_len) - olen);
1598	ip->ip_hl = sizeof (struct ip) >> 2;
1599}
1600
1601const int inetctlerrmap[PRC_NCMDS] = {
1602	0,		0,		0,		0,
1603	0,		EMSGSIZE,	EHOSTDOWN,	EHOSTUNREACH,
1604	EHOSTUNREACH,	EHOSTUNREACH,	ECONNREFUSED,	ECONNREFUSED,
1605	EMSGSIZE,	EHOSTUNREACH,	0,		0,
1606	0,		0,		0,		0,
1607	ENOPROTOOPT
1608};
1609
1610/*
1611 * Forward a packet.  If some error occurs return the sender
1612 * an icmp packet.  Note we can't always generate a meaningful
1613 * icmp message because icmp doesn't have a large enough repertoire
1614 * of codes and types.
1615 *
1616 * If not forwarding, just drop the packet.  This could be confusing
1617 * if ipforwarding was zero but some routing protocol was advancing
1618 * us as a gateway to somewhere.  However, we must let the routing
1619 * protocol deal with that.
1620 *
1621 * The srcrt parameter indicates whether the packet is being forwarded
1622 * via a source route.
1623 */
1624void
1625ip_forward(m, srcrt)
1626	struct mbuf *m;
1627	int srcrt;
1628{
1629	struct ip *ip = mtod(m, struct ip *);
1630	struct sockaddr_in *sin;
1631	struct rtentry *rt;
1632	int error, type = 0, code = 0;
1633	struct mbuf *mcopy;
1634	n_long dest;
1635	struct ifnet *destifp;
1636#if defined(IPSEC) || defined(FAST_IPSEC)
1637	struct ifnet dummyifp;
1638#endif
1639
1640	/*
1641	 * We are now in the output path.
1642	 */
1643	MCLAIM(m, &ip_tx_mowner);
1644
1645	/*
1646	 * Clear any in-bound checksum flags for this packet.
1647	 */
1648	m->m_pkthdr.csum_flags = 0;
1649
1650	dest = 0;
1651#ifdef DIAGNOSTIC
1652	if (ipprintfs)
1653		printf("forward: src %2.2x dst %2.2x ttl %x\n",
1654		    ntohl(ip->ip_src.s_addr),
1655		    ntohl(ip->ip_dst.s_addr), ip->ip_ttl);
1656#endif
1657	if (m->m_flags & (M_BCAST|M_MCAST) || in_canforward(ip->ip_dst) == 0) {
1658		ipstat.ips_cantforward++;
1659		m_freem(m);
1660		return;
1661	}
1662	if (ip->ip_ttl <= IPTTLDEC) {
1663		icmp_error(m, ICMP_TIMXCEED, ICMP_TIMXCEED_INTRANS, dest, 0);
1664		return;
1665	}
1666	ip->ip_ttl -= IPTTLDEC;
1667
1668	sin = satosin(&ipforward_rt.ro_dst);
1669	if ((rt = ipforward_rt.ro_rt) == 0 ||
1670	    !in_hosteq(ip->ip_dst, sin->sin_addr)) {
1671		if (ipforward_rt.ro_rt) {
1672			RTFREE(ipforward_rt.ro_rt);
1673			ipforward_rt.ro_rt = 0;
1674		}
1675		sin->sin_family = AF_INET;
1676		sin->sin_len = sizeof(struct sockaddr_in);
1677		sin->sin_addr = ip->ip_dst;
1678
1679		rtalloc(&ipforward_rt);
1680		if (ipforward_rt.ro_rt == 0) {
1681			icmp_error(m, ICMP_UNREACH, ICMP_UNREACH_HOST, dest, 0);
1682			return;
1683		}
1684		rt = ipforward_rt.ro_rt;
1685	}
1686
1687	/*
1688	 * Save at most 68 bytes of the packet in case
1689	 * we need to generate an ICMP message to the src.
1690	 * Pullup to avoid sharing mbuf cluster between m and mcopy.
1691	 */
1692	mcopy = m_copym(m, 0, imin(ntohs(ip->ip_len), 68), M_DONTWAIT);
1693	if (mcopy)
1694		mcopy = m_pullup(mcopy, ip->ip_hl << 2);
1695
1696	/*
1697	 * If forwarding packet using same interface that it came in on,
1698	 * perhaps should send a redirect to sender to shortcut a hop.
1699	 * Only send redirect if source is sending directly to us,
1700	 * and if packet was not source routed (or has any options).
1701	 * Also, don't send redirect if forwarding using a default route
1702	 * or a route modified by a redirect.
1703	 */
1704	if (rt->rt_ifp == m->m_pkthdr.rcvif &&
1705	    (rt->rt_flags & (RTF_DYNAMIC|RTF_MODIFIED)) == 0 &&
1706	    !in_nullhost(satosin(rt_key(rt))->sin_addr) &&
1707	    ipsendredirects && !srcrt) {
1708		if (rt->rt_ifa &&
1709		    (ip->ip_src.s_addr & ifatoia(rt->rt_ifa)->ia_subnetmask) ==
1710		    ifatoia(rt->rt_ifa)->ia_subnet) {
1711			if (rt->rt_flags & RTF_GATEWAY)
1712				dest = satosin(rt->rt_gateway)->sin_addr.s_addr;
1713			else
1714				dest = ip->ip_dst.s_addr;
1715			/*
1716			 * Router requirements says to only send host
1717			 * redirects.
1718			 */
1719			type = ICMP_REDIRECT;
1720			code = ICMP_REDIRECT_HOST;
1721#ifdef DIAGNOSTIC
1722			if (ipprintfs)
1723				printf("redirect (%d) to %x\n", code,
1724				    (u_int32_t)dest);
1725#endif
1726		}
1727	}
1728
1729	error = ip_output(m, (struct mbuf *)0, &ipforward_rt,
1730	    (IP_FORWARDING | (ip_directedbcast ? IP_ALLOWBROADCAST : 0)),
1731	    (struct ip_moptions *)NULL, (struct socket *)NULL);
1732
1733	if (error)
1734		ipstat.ips_cantforward++;
1735	else {
1736		ipstat.ips_forward++;
1737		if (type)
1738			ipstat.ips_redirectsent++;
1739		else {
1740			if (mcopy) {
1741#ifdef GATEWAY
1742				if (mcopy->m_flags & M_CANFASTFWD)
1743					ipflow_create(&ipforward_rt, mcopy);
1744#endif
1745				m_freem(mcopy);
1746			}
1747			return;
1748		}
1749	}
1750	if (mcopy == NULL)
1751		return;
1752	destifp = NULL;
1753
1754	switch (error) {
1755
1756	case 0:				/* forwarded, but need redirect */
1757		/* type, code set above */
1758		break;
1759
1760	case ENETUNREACH:		/* shouldn't happen, checked above */
1761	case EHOSTUNREACH:
1762	case ENETDOWN:
1763	case EHOSTDOWN:
1764	default:
1765		type = ICMP_UNREACH;
1766		code = ICMP_UNREACH_HOST;
1767		break;
1768
1769	case EMSGSIZE:
1770		type = ICMP_UNREACH;
1771		code = ICMP_UNREACH_NEEDFRAG;
1772#if !defined(IPSEC) && !defined(FAST_IPSEC)
1773		if (ipforward_rt.ro_rt)
1774			destifp = ipforward_rt.ro_rt->rt_ifp;
1775#else
1776		/*
1777		 * If the packet is routed over IPsec tunnel, tell the
1778		 * originator the tunnel MTU.
1779		 *	tunnel MTU = if MTU - sizeof(IP) - ESP/AH hdrsiz
1780		 * XXX quickhack!!!
1781		 */
1782		if (ipforward_rt.ro_rt) {
1783			struct secpolicy *sp;
1784			int ipsecerror;
1785			size_t ipsechdr;
1786			struct route *ro;
1787
1788			sp = ipsec4_getpolicybyaddr(mcopy,
1789			    IPSEC_DIR_OUTBOUND, IP_FORWARDING,
1790			    &ipsecerror);
1791
1792			if (sp == NULL)
1793				destifp = ipforward_rt.ro_rt->rt_ifp;
1794			else {
1795				/* count IPsec header size */
1796				ipsechdr = ipsec4_hdrsiz(mcopy,
1797				    IPSEC_DIR_OUTBOUND, NULL);
1798
1799				/*
1800				 * find the correct route for outer IPv4
1801				 * header, compute tunnel MTU.
1802				 *
1803				 * XXX BUG ALERT
1804				 * The "dummyifp" code relies upon the fact
1805				 * that icmp_error() touches only ifp->if_mtu.
1806				 */
1807				/*XXX*/
1808				destifp = NULL;
1809				if (sp->req != NULL
1810				 && sp->req->sav != NULL
1811				 && sp->req->sav->sah != NULL) {
1812					ro = &sp->req->sav->sah->sa_route;
1813					if (ro->ro_rt && ro->ro_rt->rt_ifp) {
1814						dummyifp.if_mtu =
1815						    ro->ro_rt->rt_rmx.rmx_mtu ?
1816						    ro->ro_rt->rt_rmx.rmx_mtu :
1817						    ro->ro_rt->rt_ifp->if_mtu;
1818						dummyifp.if_mtu -= ipsechdr;
1819						destifp = &dummyifp;
1820					}
1821				}
1822
1823#ifdef	IPSEC
1824				key_freesp(sp);
1825#else
1826				KEY_FREESP(&sp);
1827#endif
1828			}
1829		}
1830#endif /*IPSEC*/
1831		ipstat.ips_cantfrag++;
1832		break;
1833
1834	case ENOBUFS:
1835#if 1
1836		/*
1837		 * a router should not generate ICMP_SOURCEQUENCH as
1838		 * required in RFC1812 Requirements for IP Version 4 Routers.
1839		 * source quench could be a big problem under DoS attacks,
1840		 * or if the underlying interface is rate-limited.
1841		 */
1842		if (mcopy)
1843			m_freem(mcopy);
1844		return;
1845#else
1846		type = ICMP_SOURCEQUENCH;
1847		code = 0;
1848		break;
1849#endif
1850	}
1851	icmp_error(mcopy, type, code, dest, destifp);
1852}
1853
1854void
1855ip_savecontrol(inp, mp, ip, m)
1856	struct inpcb *inp;
1857	struct mbuf **mp;
1858	struct ip *ip;
1859	struct mbuf *m;
1860{
1861
1862	if (inp->inp_socket->so_options & SO_TIMESTAMP) {
1863		struct timeval tv;
1864
1865		microtime(&tv);
1866		*mp = sbcreatecontrol((caddr_t) &tv, sizeof(tv),
1867		    SCM_TIMESTAMP, SOL_SOCKET);
1868		if (*mp)
1869			mp = &(*mp)->m_next;
1870	}
1871	if (inp->inp_flags & INP_RECVDSTADDR) {
1872		*mp = sbcreatecontrol((caddr_t) &ip->ip_dst,
1873		    sizeof(struct in_addr), IP_RECVDSTADDR, IPPROTO_IP);
1874		if (*mp)
1875			mp = &(*mp)->m_next;
1876	}
1877#ifdef notyet
1878	/*
1879	 * XXX
1880	 * Moving these out of udp_input() made them even more broken
1881	 * than they already were.
1882	 *	- fenner@parc.xerox.com
1883	 */
1884	/* options were tossed already */
1885	if (inp->inp_flags & INP_RECVOPTS) {
1886		*mp = sbcreatecontrol((caddr_t) opts_deleted_above,
1887		    sizeof(struct in_addr), IP_RECVOPTS, IPPROTO_IP);
1888		if (*mp)
1889			mp = &(*mp)->m_next;
1890	}
1891	/* ip_srcroute doesn't do what we want here, need to fix */
1892	if (inp->inp_flags & INP_RECVRETOPTS) {
1893		*mp = sbcreatecontrol((caddr_t) ip_srcroute(),
1894		    sizeof(struct in_addr), IP_RECVRETOPTS, IPPROTO_IP);
1895		if (*mp)
1896			mp = &(*mp)->m_next;
1897	}
1898#endif
1899	if (inp->inp_flags & INP_RECVIF) {
1900		struct sockaddr_dl sdl;
1901
1902		sdl.sdl_len = offsetof(struct sockaddr_dl, sdl_data[0]);
1903		sdl.sdl_family = AF_LINK;
1904		sdl.sdl_index = m->m_pkthdr.rcvif ?
1905		    m->m_pkthdr.rcvif->if_index : 0;
1906		sdl.sdl_nlen = sdl.sdl_alen = sdl.sdl_slen = 0;
1907		*mp = sbcreatecontrol((caddr_t) &sdl, sdl.sdl_len,
1908		    IP_RECVIF, IPPROTO_IP);
1909		if (*mp)
1910			mp = &(*mp)->m_next;
1911	}
1912}
1913
1914int
1915ip_sysctl(name, namelen, oldp, oldlenp, newp, newlen)
1916	int *name;
1917	u_int namelen;
1918	void *oldp;
1919	size_t *oldlenp;
1920	void *newp;
1921	size_t newlen;
1922{
1923	extern int subnetsarelocal, hostzeroisbroadcast;
1924
1925	int error, old;
1926
1927	/* All sysctl names (except ifq.*) at this level are terminal. */
1928	if ((namelen != 1) && !(namelen == 2 && name[0] == IPCTL_IFQ))
1929		return (ENOTDIR);
1930
1931	switch (name[0]) {
1932	case IPCTL_FORWARDING:
1933		return (sysctl_int(oldp, oldlenp, newp, newlen, &ipforwarding));
1934	case IPCTL_SENDREDIRECTS:
1935		return (sysctl_int(oldp, oldlenp, newp, newlen,
1936			&ipsendredirects));
1937	case IPCTL_DEFTTL:
1938		return (sysctl_int(oldp, oldlenp, newp, newlen, &ip_defttl));
1939#ifdef notyet
1940	case IPCTL_DEFMTU:
1941		return (sysctl_int(oldp, oldlenp, newp, newlen, &ip_mtu));
1942#endif
1943	case IPCTL_FORWSRCRT:
1944		/* Don't allow this to change in a secure environment.  */
1945		if (securelevel > 0)
1946			return (sysctl_rdint(oldp, oldlenp, newp,
1947			    ip_forwsrcrt));
1948		else
1949			return (sysctl_int(oldp, oldlenp, newp, newlen,
1950			    &ip_forwsrcrt));
1951	case IPCTL_DIRECTEDBCAST:
1952		return (sysctl_int(oldp, oldlenp, newp, newlen,
1953		    &ip_directedbcast));
1954	case IPCTL_ALLOWSRCRT:
1955		return (sysctl_int(oldp, oldlenp, newp, newlen,
1956		    &ip_allowsrcrt));
1957	case IPCTL_SUBNETSARELOCAL:
1958		return (sysctl_int(oldp, oldlenp, newp, newlen,
1959		    &subnetsarelocal));
1960	case IPCTL_MTUDISC:
1961		error = sysctl_int(oldp, oldlenp, newp, newlen,
1962		    &ip_mtudisc);
1963		if (error == 0 && ip_mtudisc == 0)
1964			rt_timer_queue_remove_all(ip_mtudisc_timeout_q, TRUE);
1965		return error;
1966	case IPCTL_ANONPORTMIN:
1967		old = anonportmin;
1968		error = sysctl_int(oldp, oldlenp, newp, newlen, &anonportmin);
1969		if (anonportmin >= anonportmax || anonportmin < 0
1970		    || anonportmin > 65535
1971#ifndef IPNOPRIVPORTS
1972		    || anonportmin < IPPORT_RESERVED
1973#endif
1974		    ) {
1975			anonportmin = old;
1976			return (EINVAL);
1977		}
1978		return (error);
1979	case IPCTL_ANONPORTMAX:
1980		old = anonportmax;
1981		error = sysctl_int(oldp, oldlenp, newp, newlen, &anonportmax);
1982		if (anonportmin >= anonportmax || anonportmax < 0
1983		    || anonportmax > 65535
1984#ifndef IPNOPRIVPORTS
1985		    || anonportmax < IPPORT_RESERVED
1986#endif
1987		    ) {
1988			anonportmax = old;
1989			return (EINVAL);
1990		}
1991		return (error);
1992	case IPCTL_MTUDISCTIMEOUT:
1993		old = ip_mtudisc_timeout;
1994		error = sysctl_int(oldp, oldlenp, newp, newlen,
1995		   &ip_mtudisc_timeout);
1996		if (ip_mtudisc_timeout < 0) {
1997			ip_mtudisc_timeout = old;
1998			return (EINVAL);
1999		}
2000		if (error == 0)
2001			rt_timer_queue_change(ip_mtudisc_timeout_q,
2002					      ip_mtudisc_timeout);
2003		return (error);
2004#ifdef GATEWAY
2005	case IPCTL_MAXFLOWS:
2006	    {
2007		int s;
2008
2009		error = sysctl_int(oldp, oldlenp, newp, newlen,
2010		   &ip_maxflows);
2011		s = splsoftnet();
2012		ipflow_reap(0);
2013		splx(s);
2014		return (error);
2015	    }
2016#endif
2017	case IPCTL_HOSTZEROBROADCAST:
2018		return (sysctl_int(oldp, oldlenp, newp, newlen,
2019		    &hostzeroisbroadcast));
2020#if NGIF > 0
2021	case IPCTL_GIF_TTL:
2022		return (sysctl_int(oldp, oldlenp, newp, newlen,
2023				  &ip_gif_ttl));
2024#endif
2025
2026#if NGRE > 0
2027	case IPCTL_GRE_TTL:
2028		return (sysctl_int(oldp, oldlenp, newp, newlen,
2029				  &ip_gre_ttl));
2030#endif
2031
2032#ifndef IPNOPRIVPORTS
2033	case IPCTL_LOWPORTMIN:
2034		old = lowportmin;
2035		error = sysctl_int(oldp, oldlenp, newp, newlen, &lowportmin);
2036		if (lowportmin >= lowportmax
2037		    || lowportmin > IPPORT_RESERVEDMAX
2038		    || lowportmin < IPPORT_RESERVEDMIN
2039		    ) {
2040			lowportmin = old;
2041			return (EINVAL);
2042		}
2043		return (error);
2044	case IPCTL_LOWPORTMAX:
2045		old = lowportmax;
2046		error = sysctl_int(oldp, oldlenp, newp, newlen, &lowportmax);
2047		if (lowportmin >= lowportmax
2048		    || lowportmax > IPPORT_RESERVEDMAX
2049		    || lowportmax < IPPORT_RESERVEDMIN
2050		    ) {
2051			lowportmax = old;
2052			return (EINVAL);
2053		}
2054		return (error);
2055#endif
2056
2057	case IPCTL_MAXFRAGPACKETS:
2058		return (sysctl_int(oldp, oldlenp, newp, newlen,
2059		    &ip_maxfragpackets));
2060
2061	case IPCTL_CHECKINTERFACE:
2062		return (sysctl_int(oldp, oldlenp, newp, newlen,
2063		    &ip_checkinterface));
2064
2065	case IPCTL_IFQ:
2066		return (sysctl_ifq(name + 1, namelen - 1, oldp, oldlenp,
2067		    newp, newlen, &ipintrq));
2068
2069	default:
2070		return (EOPNOTSUPP);
2071	}
2072	/* NOTREACHED */
2073}
2074