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