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