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