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