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