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