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