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