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