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