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