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