xref: /netbsd-src/sys/netinet/ip_input.c (revision 3cec974c61d7fac0a37c0377723a33214a458c8b)
1 /*	$NetBSD: ip_input.c,v 1.130 2001/03/02 04:26:10 itojun Exp $	*/
2 
3 /*
4  * Copyright (C) 1995, 1996, 1997, and 1998 WIDE Project.
5  * All rights reserved.
6  *
7  * Redistribution and use in source and binary forms, with or without
8  * modification, are permitted provided that the following conditions
9  * are met:
10  * 1. Redistributions of source code must retain the above copyright
11  *    notice, this list of conditions and the following disclaimer.
12  * 2. Redistributions in binary form must reproduce the above copyright
13  *    notice, this list of conditions and the following disclaimer in the
14  *    documentation and/or other materials provided with the distribution.
15  * 3. Neither the name of the project nor the names of its contributors
16  *    may be used to endorse or promote products derived from this software
17  *    without specific prior written permission.
18  *
19  * THIS SOFTWARE IS PROVIDED BY THE PROJECT AND CONTRIBUTORS ``AS IS'' AND
20  * ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
21  * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE
22  * ARE DISCLAIMED.  IN NO EVENT SHALL THE PROJECT OR CONTRIBUTORS BE LIABLE
23  * FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL
24  * DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS
25  * OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION)
26  * HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT
27  * LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY
28  * OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF
29  * SUCH DAMAGE.
30  */
31 
32 /*-
33  * Copyright (c) 1998 The NetBSD Foundation, Inc.
34  * All rights reserved.
35  *
36  * This code is derived from software contributed to The NetBSD Foundation
37  * by Public Access Networks Corporation ("Panix").  It was developed under
38  * contract to Panix by Eric Haszlakiewicz and Thor Lancelot Simon.
39  *
40  * Redistribution and use in source and binary forms, with or without
41  * modification, are permitted provided that the following conditions
42  * are met:
43  * 1. Redistributions of source code must retain the above copyright
44  *    notice, this list of conditions and the following disclaimer.
45  * 2. Redistributions in binary form must reproduce the above copyright
46  *    notice, this list of conditions and the following disclaimer in the
47  *    documentation and/or other materials provided with the distribution.
48  * 3. All advertising materials mentioning features or use of this software
49  *    must display the following acknowledgement:
50  *	This product includes software developed by the NetBSD
51  *	Foundation, Inc. and its contributors.
52  * 4. Neither the name of The NetBSD Foundation nor the names of its
53  *    contributors may be used to endorse or promote products derived
54  *    from this software without specific prior written permission.
55  *
56  * THIS SOFTWARE IS PROVIDED BY THE NETBSD FOUNDATION, INC. AND CONTRIBUTORS
57  * ``AS IS'' AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED
58  * TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR
59  * PURPOSE ARE DISCLAIMED.  IN NO EVENT SHALL THE FOUNDATION OR CONTRIBUTORS
60  * BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR
61  * CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF
62  * SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS
63  * INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN
64  * CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE)
65  * ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE
66  * POSSIBILITY OF SUCH DAMAGE.
67  */
68 
69 /*
70  * Copyright (c) 1982, 1986, 1988, 1993
71  *	The Regents of the University of California.  All rights reserved.
72  *
73  * Redistribution and use in source and binary forms, with or without
74  * modification, are permitted provided that the following conditions
75  * are met:
76  * 1. Redistributions of source code must retain the above copyright
77  *    notice, this list of conditions and the following disclaimer.
78  * 2. Redistributions in binary form must reproduce the above copyright
79  *    notice, this list of conditions and the following disclaimer in the
80  *    documentation and/or other materials provided with the distribution.
81  * 3. All advertising materials mentioning features or use of this software
82  *    must display the following acknowledgement:
83  *	This product includes software developed by the University of
84  *	California, Berkeley and its contributors.
85  * 4. Neither the name of the University nor the names of its contributors
86  *    may be used to endorse or promote products derived from this software
87  *    without specific prior written permission.
88  *
89  * THIS SOFTWARE IS PROVIDED BY THE REGENTS AND CONTRIBUTORS ``AS IS'' AND
90  * ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
91  * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE
92  * ARE DISCLAIMED.  IN NO EVENT SHALL THE REGENTS OR CONTRIBUTORS BE LIABLE
93  * FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL
94  * DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS
95  * OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION)
96  * HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT
97  * LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY
98  * OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF
99  * SUCH DAMAGE.
100  *
101  *	@(#)ip_input.c	8.2 (Berkeley) 1/4/94
102  */
103 
104 #include "opt_gateway.h"
105 #include "opt_pfil_hooks.h"
106 #include "opt_ipsec.h"
107 #include "opt_mrouting.h"
108 
109 #include <sys/param.h>
110 #include <sys/systm.h>
111 #include <sys/malloc.h>
112 #include <sys/mbuf.h>
113 #include <sys/domain.h>
114 #include <sys/protosw.h>
115 #include <sys/socket.h>
116 #include <sys/socketvar.h>
117 #include <sys/errno.h>
118 #include <sys/time.h>
119 #include <sys/kernel.h>
120 #include <sys/proc.h>
121 #include <sys/pool.h>
122 
123 #include <uvm/uvm_extern.h>
124 
125 #include <sys/sysctl.h>
126 
127 #include <net/if.h>
128 #include <net/if_dl.h>
129 #include <net/route.h>
130 #include <net/pfil.h>
131 
132 #include <netinet/in.h>
133 #include <netinet/in_systm.h>
134 #include <netinet/ip.h>
135 #include <netinet/in_pcb.h>
136 #include <netinet/in_var.h>
137 #include <netinet/ip_var.h>
138 #include <netinet/ip_icmp.h>
139 /* just for gif_ttl */
140 #include <netinet/in_gif.h>
141 #include "gif.h"
142 
143 #ifdef MROUTING
144 #include <netinet/ip_mroute.h>
145 #endif
146 
147 #ifdef IPSEC
148 #include <netinet6/ipsec.h>
149 #include <netkey/key.h>
150 #endif
151 
152 #ifndef	IPFORWARDING
153 #ifdef GATEWAY
154 #define	IPFORWARDING	1	/* forward IP packets not for us */
155 #else /* GATEWAY */
156 #define	IPFORWARDING	0	/* don't forward IP packets not for us */
157 #endif /* GATEWAY */
158 #endif /* IPFORWARDING */
159 #ifndef	IPSENDREDIRECTS
160 #define	IPSENDREDIRECTS	1
161 #endif
162 #ifndef IPFORWSRCRT
163 #define	IPFORWSRCRT	1	/* forward source-routed packets */
164 #endif
165 #ifndef IPALLOWSRCRT
166 #define	IPALLOWSRCRT	1	/* allow source-routed packets */
167 #endif
168 #ifndef IPMTUDISC
169 #define IPMTUDISC	0
170 #endif
171 #ifndef IPMTUDISCTIMEOUT
172 #define IPMTUDISCTIMEOUT (10 * 60)	/* as per RFC 1191 */
173 #endif
174 
175 /*
176  * Note: DIRECTED_BROADCAST is handled this way so that previous
177  * configuration using this option will Just Work.
178  */
179 #ifndef IPDIRECTEDBCAST
180 #ifdef DIRECTED_BROADCAST
181 #define IPDIRECTEDBCAST	1
182 #else
183 #define	IPDIRECTEDBCAST	0
184 #endif /* DIRECTED_BROADCAST */
185 #endif /* IPDIRECTEDBCAST */
186 int	ipforwarding = IPFORWARDING;
187 int	ipsendredirects = IPSENDREDIRECTS;
188 int	ip_defttl = IPDEFTTL;
189 int	ip_forwsrcrt = IPFORWSRCRT;
190 int	ip_directedbcast = IPDIRECTEDBCAST;
191 int	ip_allowsrcrt = IPALLOWSRCRT;
192 int	ip_mtudisc = IPMTUDISC;
193 u_int	ip_mtudisc_timeout = IPMTUDISCTIMEOUT;
194 #ifdef DIAGNOSTIC
195 int	ipprintfs = 0;
196 #endif
197 
198 struct rttimer_queue *ip_mtudisc_timeout_q = NULL;
199 
200 extern	struct domain inetdomain;
201 int	ipqmaxlen = IFQ_MAXLEN;
202 struct	in_ifaddrhead in_ifaddr;
203 struct	in_ifaddrhashhead *in_ifaddrhashtbl;
204 struct	ifqueue ipintrq;
205 struct	ipstat	ipstat;
206 u_int16_t	ip_id;
207 
208 #ifdef PFIL_HOOKS
209 struct pfil_head inet_pfil_hook;
210 #endif
211 
212 struct ipqhead ipq;
213 int	ipq_locked;
214 
215 static __inline int ipq_lock_try __P((void));
216 static __inline void ipq_unlock __P((void));
217 
218 static __inline int
219 ipq_lock_try()
220 {
221 	int s;
222 
223 	s = splimp();
224 	if (ipq_locked) {
225 		splx(s);
226 		return (0);
227 	}
228 	ipq_locked = 1;
229 	splx(s);
230 	return (1);
231 }
232 
233 static __inline void
234 ipq_unlock()
235 {
236 	int s;
237 
238 	s = splimp();
239 	ipq_locked = 0;
240 	splx(s);
241 }
242 
243 #ifdef DIAGNOSTIC
244 #define	IPQ_LOCK()							\
245 do {									\
246 	if (ipq_lock_try() == 0) {					\
247 		printf("%s:%d: ipq already locked\n", __FILE__, __LINE__); \
248 		panic("ipq_lock");					\
249 	}								\
250 } while (0)
251 #define	IPQ_LOCK_CHECK()						\
252 do {									\
253 	if (ipq_locked == 0) {						\
254 		printf("%s:%d: ipq lock not held\n", __FILE__, __LINE__); \
255 		panic("ipq lock check");				\
256 	}								\
257 } while (0)
258 #else
259 #define	IPQ_LOCK()		(void) ipq_lock_try()
260 #define	IPQ_LOCK_CHECK()	/* nothing */
261 #endif
262 
263 #define	IPQ_UNLOCK()		ipq_unlock()
264 
265 struct pool ipqent_pool;
266 
267 /*
268  * We need to save the IP options in case a protocol wants to respond
269  * to an incoming packet over the same route if the packet got here
270  * using IP source routing.  This allows connection establishment and
271  * maintenance when the remote end is on a network that is not known
272  * to us.
273  */
274 int	ip_nhops = 0;
275 static	struct ip_srcrt {
276 	struct	in_addr dst;			/* final destination */
277 	char	nop;				/* one NOP to align */
278 	char	srcopt[IPOPT_OFFSET + 1];	/* OPTVAL, OLEN and OFFSET */
279 	struct	in_addr route[MAX_IPOPTLEN/sizeof(struct in_addr)];
280 } ip_srcrt;
281 
282 static void save_rte __P((u_char *, struct in_addr));
283 
284 /*
285  * IP initialization: fill in IP protocol switch table.
286  * All protocols not implemented in kernel go to raw IP protocol handler.
287  */
288 void
289 ip_init()
290 {
291 	struct protosw *pr;
292 	int i;
293 
294 	pool_init(&ipqent_pool, sizeof(struct ipqent), 0, 0, 0, "ipqepl",
295 	    0, NULL, NULL, M_IPQ);
296 
297 	pr = pffindproto(PF_INET, IPPROTO_RAW, SOCK_RAW);
298 	if (pr == 0)
299 		panic("ip_init");
300 	for (i = 0; i < IPPROTO_MAX; i++)
301 		ip_protox[i] = pr - inetsw;
302 	for (pr = inetdomain.dom_protosw;
303 	    pr < inetdomain.dom_protoswNPROTOSW; pr++)
304 		if (pr->pr_domain->dom_family == PF_INET &&
305 		    pr->pr_protocol && pr->pr_protocol != IPPROTO_RAW)
306 			ip_protox[pr->pr_protocol] = pr - inetsw;
307 	LIST_INIT(&ipq);
308 	ip_id = time.tv_sec & 0xffff;
309 	ipintrq.ifq_maxlen = ipqmaxlen;
310 	TAILQ_INIT(&in_ifaddr);
311 	in_ifaddrhashtbl = hashinit(IN_IFADDR_HASH_SIZE, HASH_LIST, M_IFADDR,
312 	    M_WAITOK, &in_ifaddrhash);
313 	if (ip_mtudisc != 0)
314 		ip_mtudisc_timeout_q =
315 		    rt_timer_queue_create(ip_mtudisc_timeout);
316 #ifdef GATEWAY
317 	ipflow_init();
318 #endif
319 
320 #ifdef PFIL_HOOKS
321 	/* Register our Packet Filter hook. */
322 	inet_pfil_hook.ph_type = PFIL_TYPE_AF;
323 	inet_pfil_hook.ph_af   = AF_INET;
324 	i = pfil_head_register(&inet_pfil_hook);
325 	if (i != 0)
326 		printf("ip_init: WARNING: unable to register pfil hook, "
327 		    "error %d\n", i);
328 #endif /* PFIL_HOOKS */
329 }
330 
331 struct	sockaddr_in ipaddr = { sizeof(ipaddr), AF_INET };
332 struct	route ipforward_rt;
333 
334 /*
335  * IP software interrupt routine
336  */
337 void
338 ipintr()
339 {
340 	int s;
341 	struct mbuf *m;
342 
343 	while (1) {
344 		s = splimp();
345 		IF_DEQUEUE(&ipintrq, m);
346 		splx(s);
347 		if (m == 0)
348 			return;
349 		ip_input(m);
350 	}
351 }
352 
353 /*
354  * Ip input routine.  Checksum and byte swap header.  If fragmented
355  * try to reassemble.  Process options.  Pass to next level.
356  */
357 void
358 ip_input(struct mbuf *m)
359 {
360 	struct ip *ip = NULL;
361 	struct ipq *fp;
362 	struct in_ifaddr *ia;
363 	struct ifaddr *ifa;
364 	struct ipqent *ipqe;
365 	int hlen = 0, mff, len;
366 	int downmatch;
367 
368 #ifdef	DIAGNOSTIC
369 	if ((m->m_flags & M_PKTHDR) == 0)
370 		panic("ipintr no HDR");
371 #endif
372 #ifdef IPSEC
373 	/*
374 	 * should the inner packet be considered authentic?
375 	 * see comment in ah4_input().
376 	 */
377 	if (m) {
378 		m->m_flags &= ~M_AUTHIPHDR;
379 		m->m_flags &= ~M_AUTHIPDGM;
380 	}
381 #endif
382 	/*
383 	 * If no IP addresses have been set yet but the interfaces
384 	 * are receiving, can't do anything with incoming packets yet.
385 	 */
386 	if (in_ifaddr.tqh_first == 0)
387 		goto bad;
388 	ipstat.ips_total++;
389 	if (m->m_len < sizeof (struct ip) &&
390 	    (m = m_pullup(m, sizeof (struct ip))) == 0) {
391 		ipstat.ips_toosmall++;
392 		return;
393 	}
394 	ip = mtod(m, struct ip *);
395 	if (ip->ip_v != IPVERSION) {
396 		ipstat.ips_badvers++;
397 		goto bad;
398 	}
399 	hlen = ip->ip_hl << 2;
400 	if (hlen < sizeof(struct ip)) {	/* minimum header length */
401 		ipstat.ips_badhlen++;
402 		goto bad;
403 	}
404 	if (hlen > m->m_len) {
405 		if ((m = m_pullup(m, hlen)) == 0) {
406 			ipstat.ips_badhlen++;
407 			return;
408 		}
409 		ip = mtod(m, struct ip *);
410 	}
411 
412 	/*
413 	 * RFC1122: packets with a multicast source address are
414 	 * not allowed.
415 	 */
416 	if (IN_MULTICAST(ip->ip_src.s_addr)) {
417 		ipstat.ips_badaddr++;
418 		goto bad;
419 	}
420 
421 	/* 127/8 must not appear on wire - RFC1122 */
422 	if ((ntohl(ip->ip_dst.s_addr) >> IN_CLASSA_NSHIFT) == IN_LOOPBACKNET ||
423 	    (ntohl(ip->ip_src.s_addr) >> IN_CLASSA_NSHIFT) == IN_LOOPBACKNET) {
424 		if ((m->m_pkthdr.rcvif->if_flags & IFF_LOOPBACK) == 0) {
425 			ipstat.ips_badaddr++;
426 			goto bad;
427 		}
428 	}
429 
430 	if (in_cksum(m, hlen) != 0) {
431 		ipstat.ips_badsum++;
432 		goto bad;
433 	}
434 
435 	/* Retrieve the packet length. */
436 	len = ntohs(ip->ip_len);
437 
438 	/*
439 	 * Check for additional length bogosity
440 	 */
441 	if (len < hlen) {
442 	 	ipstat.ips_badlen++;
443 		goto bad;
444 	}
445 
446 	/*
447 	 * Check that the amount of data in the buffers
448 	 * is as at least much as the IP header would have us expect.
449 	 * Trim mbufs if longer than we expect.
450 	 * Drop packet if shorter than we expect.
451 	 */
452 	if (m->m_pkthdr.len < len) {
453 		ipstat.ips_tooshort++;
454 		goto bad;
455 	}
456 	if (m->m_pkthdr.len > len) {
457 		if (m->m_len == m->m_pkthdr.len) {
458 			m->m_len = len;
459 			m->m_pkthdr.len = len;
460 		} else
461 			m_adj(m, len - m->m_pkthdr.len);
462 	}
463 
464 #ifdef IPSEC
465 	/* ipflow (IP fast fowarding) is not compatible with IPsec. */
466 	m->m_flags &= ~M_CANFASTFWD;
467 #else
468 	/*
469 	 * Assume that we can create a fast-forward IP flow entry
470 	 * based on this packet.
471 	 */
472 	m->m_flags |= M_CANFASTFWD;
473 #endif
474 
475 #ifdef PFIL_HOOKS
476 	/*
477 	 * Run through list of hooks for input packets.  If there are any
478 	 * filters which require that additional packets in the flow are
479 	 * not fast-forwarded, they must clear the M_CANFASTFWD flag.
480 	 * Note that filters must _never_ set this flag, as another filter
481 	 * in the list may have previously cleared it.
482 	 */
483 	/*
484 	 * let ipfilter look at packet on the wire,
485 	 * not the decapsulated packet.
486 	 */
487 #ifdef IPSEC
488 	if (!ipsec_gethist(m, NULL))
489 #else
490 	if (1)
491 #endif
492 	{
493 		if (pfil_run_hooks(&inet_pfil_hook, &m, m->m_pkthdr.rcvif,
494 				   PFIL_IN) != 0)
495 		return;
496 		if (m == NULL)
497 			return;
498 		ip = mtod(m, struct ip *);
499 	}
500 #endif /* PFIL_HOOKS */
501 
502 #ifdef ALTQ
503 	/* XXX Temporary until ALTQ is changed to use a pfil hook */
504 	if (altq_input != NULL && (*altq_input)(m, AF_INET) == 0) {
505 		/* packet dropped by traffic conditioner */
506 		return;
507 	}
508 #endif
509 
510 	/*
511 	 * Convert fields to host representation.
512 	 */
513 	NTOHS(ip->ip_len);
514 	NTOHS(ip->ip_off);
515 
516 	/*
517 	 * Process options and, if not destined for us,
518 	 * ship it on.  ip_dooptions returns 1 when an
519 	 * error was detected (causing an icmp message
520 	 * to be sent and the original packet to be freed).
521 	 */
522 	ip_nhops = 0;		/* for source routed packets */
523 	if (hlen > sizeof (struct ip) && ip_dooptions(m))
524 		return;
525 
526 	/*
527 	 * Check our list of addresses, to see if the packet is for us.
528 	 *
529 	 * Traditional 4.4BSD did not consult IFF_UP at all.
530 	 * The behavior here is to treat addresses on !IFF_UP interface
531 	 * as not mine.
532 	 */
533 	downmatch = 0;
534 	for (ia = IN_IFADDR_HASH(ip->ip_dst.s_addr).lh_first;
535 	     ia != NULL;
536 	     ia = ia->ia_hash.le_next) {
537 		if (in_hosteq(ia->ia_addr.sin_addr, ip->ip_dst)) {
538 			if ((ia->ia_ifp->if_flags & IFF_UP) != 0)
539 				break;
540 			else
541 				downmatch++;
542 		}
543 	}
544 	if (ia != NULL)
545 		goto ours;
546 	if (m->m_pkthdr.rcvif->if_flags & IFF_BROADCAST) {
547 		for (ifa = m->m_pkthdr.rcvif->if_addrlist.tqh_first;
548 		    ifa != NULL; ifa = ifa->ifa_list.tqe_next) {
549 			if (ifa->ifa_addr->sa_family != AF_INET) continue;
550 			ia = ifatoia(ifa);
551 			if (in_hosteq(ip->ip_dst, ia->ia_broadaddr.sin_addr) ||
552 			    in_hosteq(ip->ip_dst, ia->ia_netbroadcast) ||
553 			    /*
554 			     * Look for all-0's host part (old broadcast addr),
555 			     * either for subnet or net.
556 			     */
557 			    ip->ip_dst.s_addr == ia->ia_subnet ||
558 			    ip->ip_dst.s_addr == ia->ia_net)
559 				goto ours;
560 			/*
561 			 * An interface with IP address zero accepts
562 			 * all packets that arrive on that interface.
563 			 */
564 			if (in_nullhost(ia->ia_addr.sin_addr))
565 				goto ours;
566 		}
567 	}
568 	if (IN_MULTICAST(ip->ip_dst.s_addr)) {
569 		struct in_multi *inm;
570 #ifdef MROUTING
571 		extern struct socket *ip_mrouter;
572 
573 		if (m->m_flags & M_EXT) {
574 			if ((m = m_pullup(m, hlen)) == 0) {
575 				ipstat.ips_toosmall++;
576 				return;
577 			}
578 			ip = mtod(m, struct ip *);
579 		}
580 
581 		if (ip_mrouter) {
582 			/*
583 			 * If we are acting as a multicast router, all
584 			 * incoming multicast packets are passed to the
585 			 * kernel-level multicast forwarding function.
586 			 * The packet is returned (relatively) intact; if
587 			 * ip_mforward() returns a non-zero value, the packet
588 			 * must be discarded, else it may be accepted below.
589 			 *
590 			 * (The IP ident field is put in the same byte order
591 			 * as expected when ip_mforward() is called from
592 			 * ip_output().)
593 			 */
594 			if (ip_mforward(m, m->m_pkthdr.rcvif) != 0) {
595 				ipstat.ips_cantforward++;
596 				m_freem(m);
597 				return;
598 			}
599 
600 			/*
601 			 * The process-level routing demon needs to receive
602 			 * all multicast IGMP packets, whether or not this
603 			 * host belongs to their destination groups.
604 			 */
605 			if (ip->ip_p == IPPROTO_IGMP)
606 				goto ours;
607 			ipstat.ips_forward++;
608 		}
609 #endif
610 		/*
611 		 * See if we belong to the destination multicast group on the
612 		 * arrival interface.
613 		 */
614 		IN_LOOKUP_MULTI(ip->ip_dst, m->m_pkthdr.rcvif, inm);
615 		if (inm == NULL) {
616 			ipstat.ips_cantforward++;
617 			m_freem(m);
618 			return;
619 		}
620 		goto ours;
621 	}
622 	if (ip->ip_dst.s_addr == INADDR_BROADCAST ||
623 	    in_nullhost(ip->ip_dst))
624 		goto ours;
625 
626 	/*
627 	 * Not for us; forward if possible and desirable.
628 	 */
629 	if (ipforwarding == 0) {
630 		ipstat.ips_cantforward++;
631 		m_freem(m);
632 	} else {
633 		/*
634 		 * If ip_dst matched any of my address on !IFF_UP interface,
635 		 * and there's no IFF_UP interface that matches ip_dst,
636 		 * send icmp unreach.  Forwarding it will result in in-kernel
637 		 * forwarding loop till TTL goes to 0.
638 		 */
639 		if (downmatch) {
640 			icmp_error(m, ICMP_UNREACH, ICMP_UNREACH_HOST, 0, 0);
641 			ipstat.ips_cantforward++;
642 			return;
643 		}
644 		ip_forward(m, 0);
645 	}
646 	return;
647 
648 ours:
649 	/*
650 	 * If offset or IP_MF are set, must reassemble.
651 	 * Otherwise, nothing need be done.
652 	 * (We could look in the reassembly queue to see
653 	 * if the packet was previously fragmented,
654 	 * but it's not worth the time; just let them time out.)
655 	 */
656 	if (ip->ip_off & ~(IP_DF|IP_RF)) {
657 		/*
658 		 * Look for queue of fragments
659 		 * of this datagram.
660 		 */
661 		IPQ_LOCK();
662 		for (fp = ipq.lh_first; fp != NULL; fp = fp->ipq_q.le_next)
663 			if (ip->ip_id == fp->ipq_id &&
664 			    in_hosteq(ip->ip_src, fp->ipq_src) &&
665 			    in_hosteq(ip->ip_dst, fp->ipq_dst) &&
666 			    ip->ip_p == fp->ipq_p)
667 				goto found;
668 		fp = 0;
669 found:
670 
671 		/*
672 		 * Adjust ip_len to not reflect header,
673 		 * set ipqe_mff if more fragments are expected,
674 		 * convert offset of this to bytes.
675 		 */
676 		ip->ip_len -= hlen;
677 		mff = (ip->ip_off & IP_MF) != 0;
678 		if (mff) {
679 		        /*
680 		         * Make sure that fragments have a data length
681 			 * that's a non-zero multiple of 8 bytes.
682 		         */
683 			if (ip->ip_len == 0 || (ip->ip_len & 0x7) != 0) {
684 				ipstat.ips_badfrags++;
685 				IPQ_UNLOCK();
686 				goto bad;
687 			}
688 		}
689 		ip->ip_off <<= 3;
690 
691 		/*
692 		 * If datagram marked as having more fragments
693 		 * or if this is not the first fragment,
694 		 * attempt reassembly; if it succeeds, proceed.
695 		 */
696 		if (mff || ip->ip_off) {
697 			ipstat.ips_fragments++;
698 			ipqe = pool_get(&ipqent_pool, PR_NOWAIT);
699 			if (ipqe == NULL) {
700 				ipstat.ips_rcvmemdrop++;
701 				IPQ_UNLOCK();
702 				goto bad;
703 			}
704 			ipqe->ipqe_mff = mff;
705 			ipqe->ipqe_m = m;
706 			ipqe->ipqe_ip = ip;
707 			m = ip_reass(ipqe, fp);
708 			if (m == 0) {
709 				IPQ_UNLOCK();
710 				return;
711 			}
712 			ipstat.ips_reassembled++;
713 			ip = mtod(m, struct ip *);
714 			hlen = ip->ip_hl << 2;
715 			ip->ip_len += hlen;
716 		} else
717 			if (fp)
718 				ip_freef(fp);
719 		IPQ_UNLOCK();
720 	}
721 
722 #ifdef IPSEC
723 	/*
724 	 * enforce IPsec policy checking if we are seeing last header.
725 	 * note that we do not visit this with protocols with pcb layer
726 	 * code - like udp/tcp/raw ip.
727 	 */
728 	if ((inetsw[ip_protox[ip->ip_p]].pr_flags & PR_LASTHDR) != 0 &&
729 	    ipsec4_in_reject(m, NULL)) {
730 		ipsecstat.in_polvio++;
731 		goto bad;
732 	}
733 #endif
734 
735 	/*
736 	 * Switch out to protocol's input routine.
737 	 */
738 #if IFA_STATS
739 	if (ia && ip)
740 		ia->ia_ifa.ifa_data.ifad_inbytes += ip->ip_len;
741 #endif
742 	ipstat.ips_delivered++;
743     {
744 	int off = hlen, nh = ip->ip_p;
745 
746 	(*inetsw[ip_protox[nh]].pr_input)(m, off, nh);
747 	return;
748     }
749 bad:
750 	m_freem(m);
751 }
752 
753 /*
754  * Take incoming datagram fragment and try to
755  * reassemble it into whole datagram.  If a chain for
756  * reassembly of this datagram already exists, then it
757  * is given as fp; otherwise have to make a chain.
758  */
759 struct mbuf *
760 ip_reass(ipqe, fp)
761 	struct ipqent *ipqe;
762 	struct ipq *fp;
763 {
764 	struct mbuf *m = ipqe->ipqe_m;
765 	struct ipqent *nq, *p, *q;
766 	struct ip *ip;
767 	struct mbuf *t;
768 	int hlen = ipqe->ipqe_ip->ip_hl << 2;
769 	int i, next;
770 
771 	IPQ_LOCK_CHECK();
772 
773 	/*
774 	 * Presence of header sizes in mbufs
775 	 * would confuse code below.
776 	 */
777 	m->m_data += hlen;
778 	m->m_len -= hlen;
779 
780 	/*
781 	 * If first fragment to arrive, create a reassembly queue.
782 	 */
783 	if (fp == 0) {
784 		MALLOC(fp, struct ipq *, sizeof (struct ipq),
785 		    M_FTABLE, M_NOWAIT);
786 		if (fp == NULL)
787 			goto dropfrag;
788 		LIST_INSERT_HEAD(&ipq, fp, ipq_q);
789 		fp->ipq_ttl = IPFRAGTTL;
790 		fp->ipq_p = ipqe->ipqe_ip->ip_p;
791 		fp->ipq_id = ipqe->ipqe_ip->ip_id;
792 		LIST_INIT(&fp->ipq_fragq);
793 		fp->ipq_src = ipqe->ipqe_ip->ip_src;
794 		fp->ipq_dst = ipqe->ipqe_ip->ip_dst;
795 		p = NULL;
796 		goto insert;
797 	}
798 
799 	/*
800 	 * Find a segment which begins after this one does.
801 	 */
802 	for (p = NULL, q = fp->ipq_fragq.lh_first; q != NULL;
803 	    p = q, q = q->ipqe_q.le_next)
804 		if (q->ipqe_ip->ip_off > ipqe->ipqe_ip->ip_off)
805 			break;
806 
807 	/*
808 	 * If there is a preceding segment, it may provide some of
809 	 * our data already.  If so, drop the data from the incoming
810 	 * segment.  If it provides all of our data, drop us.
811 	 */
812 	if (p != NULL) {
813 		i = p->ipqe_ip->ip_off + p->ipqe_ip->ip_len -
814 		    ipqe->ipqe_ip->ip_off;
815 		if (i > 0) {
816 			if (i >= ipqe->ipqe_ip->ip_len)
817 				goto dropfrag;
818 			m_adj(ipqe->ipqe_m, i);
819 			ipqe->ipqe_ip->ip_off += i;
820 			ipqe->ipqe_ip->ip_len -= i;
821 		}
822 	}
823 
824 	/*
825 	 * While we overlap succeeding segments trim them or,
826 	 * if they are completely covered, dequeue them.
827 	 */
828 	for (; q != NULL && ipqe->ipqe_ip->ip_off + ipqe->ipqe_ip->ip_len >
829 	    q->ipqe_ip->ip_off; q = nq) {
830 		i = (ipqe->ipqe_ip->ip_off + ipqe->ipqe_ip->ip_len) -
831 		    q->ipqe_ip->ip_off;
832 		if (i < q->ipqe_ip->ip_len) {
833 			q->ipqe_ip->ip_len -= i;
834 			q->ipqe_ip->ip_off += i;
835 			m_adj(q->ipqe_m, i);
836 			break;
837 		}
838 		nq = q->ipqe_q.le_next;
839 		m_freem(q->ipqe_m);
840 		LIST_REMOVE(q, ipqe_q);
841 		pool_put(&ipqent_pool, q);
842 	}
843 
844 insert:
845 	/*
846 	 * Stick new segment in its place;
847 	 * check for complete reassembly.
848 	 */
849 	if (p == NULL) {
850 		LIST_INSERT_HEAD(&fp->ipq_fragq, ipqe, ipqe_q);
851 	} else {
852 		LIST_INSERT_AFTER(p, ipqe, ipqe_q);
853 	}
854 	next = 0;
855 	for (p = NULL, q = fp->ipq_fragq.lh_first; q != NULL;
856 	    p = q, q = q->ipqe_q.le_next) {
857 		if (q->ipqe_ip->ip_off != next)
858 			return (0);
859 		next += q->ipqe_ip->ip_len;
860 	}
861 	if (p->ipqe_mff)
862 		return (0);
863 
864 	/*
865 	 * Reassembly is complete.  Check for a bogus message size and
866 	 * concatenate fragments.
867 	 */
868 	q = fp->ipq_fragq.lh_first;
869 	ip = q->ipqe_ip;
870 	if ((next + (ip->ip_hl << 2)) > IP_MAXPACKET) {
871 		ipstat.ips_toolong++;
872 		ip_freef(fp);
873 		return (0);
874 	}
875 	m = q->ipqe_m;
876 	t = m->m_next;
877 	m->m_next = 0;
878 	m_cat(m, t);
879 	nq = q->ipqe_q.le_next;
880 	pool_put(&ipqent_pool, q);
881 	for (q = nq; q != NULL; q = nq) {
882 		t = q->ipqe_m;
883 		nq = q->ipqe_q.le_next;
884 		pool_put(&ipqent_pool, q);
885 		m_cat(m, t);
886 	}
887 
888 	/*
889 	 * Create header for new ip packet by
890 	 * modifying header of first packet;
891 	 * dequeue and discard fragment reassembly header.
892 	 * Make header visible.
893 	 */
894 	ip->ip_len = next;
895 	ip->ip_src = fp->ipq_src;
896 	ip->ip_dst = fp->ipq_dst;
897 	LIST_REMOVE(fp, ipq_q);
898 	FREE(fp, M_FTABLE);
899 	m->m_len += (ip->ip_hl << 2);
900 	m->m_data -= (ip->ip_hl << 2);
901 	/* some debugging cruft by sklower, below, will go away soon */
902 	if (m->m_flags & M_PKTHDR) { /* XXX this should be done elsewhere */
903 		int plen = 0;
904 		for (t = m; t; t = t->m_next)
905 			plen += t->m_len;
906 		m->m_pkthdr.len = plen;
907 	}
908 	return (m);
909 
910 dropfrag:
911 	ipstat.ips_fragdropped++;
912 	m_freem(m);
913 	pool_put(&ipqent_pool, ipqe);
914 	return (0);
915 }
916 
917 /*
918  * Free a fragment reassembly header and all
919  * associated datagrams.
920  */
921 void
922 ip_freef(fp)
923 	struct ipq *fp;
924 {
925 	struct ipqent *q, *p;
926 
927 	IPQ_LOCK_CHECK();
928 
929 	for (q = fp->ipq_fragq.lh_first; q != NULL; q = p) {
930 		p = q->ipqe_q.le_next;
931 		m_freem(q->ipqe_m);
932 		LIST_REMOVE(q, ipqe_q);
933 		pool_put(&ipqent_pool, q);
934 	}
935 	LIST_REMOVE(fp, ipq_q);
936 	FREE(fp, M_FTABLE);
937 }
938 
939 /*
940  * IP timer processing;
941  * if a timer expires on a reassembly
942  * queue, discard it.
943  */
944 void
945 ip_slowtimo()
946 {
947 	struct ipq *fp, *nfp;
948 	int s = splsoftnet();
949 
950 	IPQ_LOCK();
951 	for (fp = ipq.lh_first; fp != NULL; fp = nfp) {
952 		nfp = fp->ipq_q.le_next;
953 		if (--fp->ipq_ttl == 0) {
954 			ipstat.ips_fragtimeout++;
955 			ip_freef(fp);
956 		}
957 	}
958 	IPQ_UNLOCK();
959 #ifdef GATEWAY
960 	ipflow_slowtimo();
961 #endif
962 	splx(s);
963 }
964 
965 /*
966  * Drain off all datagram fragments.
967  */
968 void
969 ip_drain()
970 {
971 
972 	/*
973 	 * We may be called from a device's interrupt context.  If
974 	 * the ipq is already busy, just bail out now.
975 	 */
976 	if (ipq_lock_try() == 0)
977 		return;
978 
979 	while (ipq.lh_first != NULL) {
980 		ipstat.ips_fragdropped++;
981 		ip_freef(ipq.lh_first);
982 	}
983 
984 	IPQ_UNLOCK();
985 }
986 
987 /*
988  * Do option processing on a datagram,
989  * possibly discarding it if bad options are encountered,
990  * or forwarding it if source-routed.
991  * Returns 1 if packet has been forwarded/freed,
992  * 0 if the packet should be processed further.
993  */
994 int
995 ip_dooptions(m)
996 	struct mbuf *m;
997 {
998 	struct ip *ip = mtod(m, struct ip *);
999 	u_char *cp, *cp0;
1000 	struct ip_timestamp *ipt;
1001 	struct in_ifaddr *ia;
1002 	int opt, optlen, cnt, off, code, type = ICMP_PARAMPROB, forward = 0;
1003 	struct in_addr dst;
1004 	n_time ntime;
1005 
1006 	dst = ip->ip_dst;
1007 	cp = (u_char *)(ip + 1);
1008 	cnt = (ip->ip_hl << 2) - sizeof (struct ip);
1009 	for (; cnt > 0; cnt -= optlen, cp += optlen) {
1010 		opt = cp[IPOPT_OPTVAL];
1011 		if (opt == IPOPT_EOL)
1012 			break;
1013 		if (opt == IPOPT_NOP)
1014 			optlen = 1;
1015 		else {
1016 			if (cnt < IPOPT_OLEN + sizeof(*cp)) {
1017 				code = &cp[IPOPT_OLEN] - (u_char *)ip;
1018 				goto bad;
1019 			}
1020 			optlen = cp[IPOPT_OLEN];
1021 			if (optlen < IPOPT_OLEN + sizeof(*cp) || optlen > cnt) {
1022 				code = &cp[IPOPT_OLEN] - (u_char *)ip;
1023 				goto bad;
1024 			}
1025 		}
1026 		switch (opt) {
1027 
1028 		default:
1029 			break;
1030 
1031 		/*
1032 		 * Source routing with record.
1033 		 * Find interface with current destination address.
1034 		 * If none on this machine then drop if strictly routed,
1035 		 * or do nothing if loosely routed.
1036 		 * Record interface address and bring up next address
1037 		 * component.  If strictly routed make sure next
1038 		 * address is on directly accessible net.
1039 		 */
1040 		case IPOPT_LSRR:
1041 		case IPOPT_SSRR:
1042 			if (ip_allowsrcrt == 0) {
1043 				type = ICMP_UNREACH;
1044 				code = ICMP_UNREACH_NET_PROHIB;
1045 				goto bad;
1046 			}
1047 			if (optlen < IPOPT_OFFSET + sizeof(*cp)) {
1048 				code = &cp[IPOPT_OLEN] - (u_char *)ip;
1049 				goto bad;
1050 			}
1051 			if ((off = cp[IPOPT_OFFSET]) < IPOPT_MINOFF) {
1052 				code = &cp[IPOPT_OFFSET] - (u_char *)ip;
1053 				goto bad;
1054 			}
1055 			ipaddr.sin_addr = ip->ip_dst;
1056 			ia = ifatoia(ifa_ifwithaddr(sintosa(&ipaddr)));
1057 			if (ia == 0) {
1058 				if (opt == IPOPT_SSRR) {
1059 					type = ICMP_UNREACH;
1060 					code = ICMP_UNREACH_SRCFAIL;
1061 					goto bad;
1062 				}
1063 				/*
1064 				 * Loose routing, and not at next destination
1065 				 * yet; nothing to do except forward.
1066 				 */
1067 				break;
1068 			}
1069 			off--;			/* 0 origin */
1070 			if ((off + sizeof(struct in_addr)) > optlen) {
1071 				/*
1072 				 * End of source route.  Should be for us.
1073 				 */
1074 				save_rte(cp, ip->ip_src);
1075 				break;
1076 			}
1077 			/*
1078 			 * locate outgoing interface
1079 			 */
1080 			bcopy((caddr_t)(cp + off), (caddr_t)&ipaddr.sin_addr,
1081 			    sizeof(ipaddr.sin_addr));
1082 			if (opt == IPOPT_SSRR)
1083 				ia = ifatoia(ifa_ifwithaddr(sintosa(&ipaddr)));
1084 			else
1085 				ia = ip_rtaddr(ipaddr.sin_addr);
1086 			if (ia == 0) {
1087 				type = ICMP_UNREACH;
1088 				code = ICMP_UNREACH_SRCFAIL;
1089 				goto bad;
1090 			}
1091 			ip->ip_dst = ipaddr.sin_addr;
1092 			bcopy((caddr_t)&ia->ia_addr.sin_addr,
1093 			    (caddr_t)(cp + off), sizeof(struct in_addr));
1094 			cp[IPOPT_OFFSET] += sizeof(struct in_addr);
1095 			/*
1096 			 * Let ip_intr's mcast routing check handle mcast pkts
1097 			 */
1098 			forward = !IN_MULTICAST(ip->ip_dst.s_addr);
1099 			break;
1100 
1101 		case IPOPT_RR:
1102 			if (optlen < IPOPT_OFFSET + sizeof(*cp)) {
1103 				code = &cp[IPOPT_OLEN] - (u_char *)ip;
1104 				goto bad;
1105 			}
1106 			if ((off = cp[IPOPT_OFFSET]) < IPOPT_MINOFF) {
1107 				code = &cp[IPOPT_OFFSET] - (u_char *)ip;
1108 				goto bad;
1109 			}
1110 			/*
1111 			 * If no space remains, ignore.
1112 			 */
1113 			off--;			/* 0 origin */
1114 			if ((off + sizeof(struct in_addr)) > optlen)
1115 				break;
1116 			bcopy((caddr_t)(&ip->ip_dst), (caddr_t)&ipaddr.sin_addr,
1117 			    sizeof(ipaddr.sin_addr));
1118 			/*
1119 			 * locate outgoing interface; if we're the destination,
1120 			 * use the incoming interface (should be same).
1121 			 */
1122 			if ((ia = ifatoia(ifa_ifwithaddr(sintosa(&ipaddr))))
1123 			    == NULL &&
1124 			    (ia = ip_rtaddr(ipaddr.sin_addr)) == NULL) {
1125 				type = ICMP_UNREACH;
1126 				code = ICMP_UNREACH_HOST;
1127 				goto bad;
1128 			}
1129 			bcopy((caddr_t)&ia->ia_addr.sin_addr,
1130 			    (caddr_t)(cp + off), sizeof(struct in_addr));
1131 			cp[IPOPT_OFFSET] += sizeof(struct in_addr);
1132 			break;
1133 
1134 		case IPOPT_TS:
1135 			code = cp - (u_char *)ip;
1136 			ipt = (struct ip_timestamp *)cp;
1137 			if (ipt->ipt_len < 4 || ipt->ipt_len > 40) {
1138 				code = (u_char *)&ipt->ipt_len - (u_char *)ip;
1139 				goto bad;
1140 			}
1141 			if (ipt->ipt_ptr < 5) {
1142 				code = (u_char *)&ipt->ipt_ptr - (u_char *)ip;
1143 				goto bad;
1144 			}
1145 			if (ipt->ipt_ptr > ipt->ipt_len - sizeof (int32_t)) {
1146 				if (++ipt->ipt_oflw == 0) {
1147 					code = (u_char *)&ipt->ipt_ptr -
1148 					    (u_char *)ip;
1149 					goto bad;
1150 				}
1151 				break;
1152 			}
1153 			cp0 = (cp + ipt->ipt_ptr - 1);
1154 			switch (ipt->ipt_flg) {
1155 
1156 			case IPOPT_TS_TSONLY:
1157 				break;
1158 
1159 			case IPOPT_TS_TSANDADDR:
1160 				if (ipt->ipt_ptr - 1 + sizeof(n_time) +
1161 				    sizeof(struct in_addr) > ipt->ipt_len) {
1162 					code = (u_char *)&ipt->ipt_ptr -
1163 					    (u_char *)ip;
1164 					goto bad;
1165 				}
1166 				ipaddr.sin_addr = dst;
1167 				ia = ifatoia(ifaof_ifpforaddr(sintosa(&ipaddr),
1168 				    m->m_pkthdr.rcvif));
1169 				if (ia == 0)
1170 					continue;
1171 				bcopy(&ia->ia_addr.sin_addr,
1172 				    cp0, sizeof(struct in_addr));
1173 				ipt->ipt_ptr += sizeof(struct in_addr);
1174 				break;
1175 
1176 			case IPOPT_TS_PRESPEC:
1177 				if (ipt->ipt_ptr - 1 + sizeof(n_time) +
1178 				    sizeof(struct in_addr) > ipt->ipt_len) {
1179 					code = (u_char *)&ipt->ipt_ptr -
1180 					    (u_char *)ip;
1181 					goto bad;
1182 				}
1183 				bcopy(cp0, &ipaddr.sin_addr,
1184 				    sizeof(struct in_addr));
1185 				if (ifatoia(ifa_ifwithaddr(sintosa(&ipaddr)))
1186 				    == NULL)
1187 					continue;
1188 				ipt->ipt_ptr += sizeof(struct in_addr);
1189 				break;
1190 
1191 			default:
1192 				/* XXX can't take &ipt->ipt_flg */
1193 				code = (u_char *)&ipt->ipt_ptr -
1194 				    (u_char *)ip + 1;
1195 				goto bad;
1196 			}
1197 			ntime = iptime();
1198 			cp0 = (u_char *) &ntime; /* XXX grumble, GCC... */
1199 			bcopy(cp0, (caddr_t)cp + ipt->ipt_ptr - 1,
1200 			    sizeof(n_time));
1201 			ipt->ipt_ptr += sizeof(n_time);
1202 		}
1203 	}
1204 	if (forward) {
1205 		if (ip_forwsrcrt == 0) {
1206 			type = ICMP_UNREACH;
1207 			code = ICMP_UNREACH_SRCFAIL;
1208 			goto bad;
1209 		}
1210 		ip_forward(m, 1);
1211 		return (1);
1212 	}
1213 	return (0);
1214 bad:
1215 	icmp_error(m, type, code, 0, 0);
1216 	ipstat.ips_badoptions++;
1217 	return (1);
1218 }
1219 
1220 /*
1221  * Given address of next destination (final or next hop),
1222  * return internet address info of interface to be used to get there.
1223  */
1224 struct in_ifaddr *
1225 ip_rtaddr(dst)
1226 	 struct in_addr dst;
1227 {
1228 	struct sockaddr_in *sin;
1229 
1230 	sin = satosin(&ipforward_rt.ro_dst);
1231 
1232 	if (ipforward_rt.ro_rt == 0 || !in_hosteq(dst, sin->sin_addr)) {
1233 		if (ipforward_rt.ro_rt) {
1234 			RTFREE(ipforward_rt.ro_rt);
1235 			ipforward_rt.ro_rt = 0;
1236 		}
1237 		sin->sin_family = AF_INET;
1238 		sin->sin_len = sizeof(*sin);
1239 		sin->sin_addr = dst;
1240 
1241 		rtalloc(&ipforward_rt);
1242 	}
1243 	if (ipforward_rt.ro_rt == 0)
1244 		return ((struct in_ifaddr *)0);
1245 	return (ifatoia(ipforward_rt.ro_rt->rt_ifa));
1246 }
1247 
1248 /*
1249  * Save incoming source route for use in replies,
1250  * to be picked up later by ip_srcroute if the receiver is interested.
1251  */
1252 void
1253 save_rte(option, dst)
1254 	u_char *option;
1255 	struct in_addr dst;
1256 {
1257 	unsigned olen;
1258 
1259 	olen = option[IPOPT_OLEN];
1260 #ifdef DIAGNOSTIC
1261 	if (ipprintfs)
1262 		printf("save_rte: olen %d\n", olen);
1263 #endif /* 0 */
1264 	if (olen > sizeof(ip_srcrt) - (1 + sizeof(dst)))
1265 		return;
1266 	bcopy((caddr_t)option, (caddr_t)ip_srcrt.srcopt, olen);
1267 	ip_nhops = (olen - IPOPT_OFFSET - 1) / sizeof(struct in_addr);
1268 	ip_srcrt.dst = dst;
1269 }
1270 
1271 /*
1272  * Retrieve incoming source route for use in replies,
1273  * in the same form used by setsockopt.
1274  * The first hop is placed before the options, will be removed later.
1275  */
1276 struct mbuf *
1277 ip_srcroute()
1278 {
1279 	struct in_addr *p, *q;
1280 	struct mbuf *m;
1281 
1282 	if (ip_nhops == 0)
1283 		return ((struct mbuf *)0);
1284 	m = m_get(M_DONTWAIT, MT_SOOPTS);
1285 	if (m == 0)
1286 		return ((struct mbuf *)0);
1287 
1288 #define OPTSIZ	(sizeof(ip_srcrt.nop) + sizeof(ip_srcrt.srcopt))
1289 
1290 	/* length is (nhops+1)*sizeof(addr) + sizeof(nop + srcrt header) */
1291 	m->m_len = ip_nhops * sizeof(struct in_addr) + sizeof(struct in_addr) +
1292 	    OPTSIZ;
1293 #ifdef DIAGNOSTIC
1294 	if (ipprintfs)
1295 		printf("ip_srcroute: nhops %d mlen %d", ip_nhops, m->m_len);
1296 #endif
1297 
1298 	/*
1299 	 * First save first hop for return route
1300 	 */
1301 	p = &ip_srcrt.route[ip_nhops - 1];
1302 	*(mtod(m, struct in_addr *)) = *p--;
1303 #ifdef DIAGNOSTIC
1304 	if (ipprintfs)
1305 		printf(" hops %x", ntohl(mtod(m, struct in_addr *)->s_addr));
1306 #endif
1307 
1308 	/*
1309 	 * Copy option fields and padding (nop) to mbuf.
1310 	 */
1311 	ip_srcrt.nop = IPOPT_NOP;
1312 	ip_srcrt.srcopt[IPOPT_OFFSET] = IPOPT_MINOFF;
1313 	bcopy((caddr_t)&ip_srcrt.nop,
1314 	    mtod(m, caddr_t) + sizeof(struct in_addr), OPTSIZ);
1315 	q = (struct in_addr *)(mtod(m, caddr_t) +
1316 	    sizeof(struct in_addr) + OPTSIZ);
1317 #undef OPTSIZ
1318 	/*
1319 	 * Record return path as an IP source route,
1320 	 * reversing the path (pointers are now aligned).
1321 	 */
1322 	while (p >= ip_srcrt.route) {
1323 #ifdef DIAGNOSTIC
1324 		if (ipprintfs)
1325 			printf(" %x", ntohl(q->s_addr));
1326 #endif
1327 		*q++ = *p--;
1328 	}
1329 	/*
1330 	 * Last hop goes to final destination.
1331 	 */
1332 	*q = ip_srcrt.dst;
1333 #ifdef DIAGNOSTIC
1334 	if (ipprintfs)
1335 		printf(" %x\n", ntohl(q->s_addr));
1336 #endif
1337 	return (m);
1338 }
1339 
1340 /*
1341  * Strip out IP options, at higher
1342  * level protocol in the kernel.
1343  * Second argument is buffer to which options
1344  * will be moved, and return value is their length.
1345  * XXX should be deleted; last arg currently ignored.
1346  */
1347 void
1348 ip_stripoptions(m, mopt)
1349 	struct mbuf *m;
1350 	struct mbuf *mopt;
1351 {
1352 	int i;
1353 	struct ip *ip = mtod(m, struct ip *);
1354 	caddr_t opts;
1355 	int olen;
1356 
1357 	olen = (ip->ip_hl << 2) - sizeof (struct ip);
1358 	opts = (caddr_t)(ip + 1);
1359 	i = m->m_len - (sizeof (struct ip) + olen);
1360 	bcopy(opts  + olen, opts, (unsigned)i);
1361 	m->m_len -= olen;
1362 	if (m->m_flags & M_PKTHDR)
1363 		m->m_pkthdr.len -= olen;
1364 	ip->ip_len -= olen;
1365 	ip->ip_hl = sizeof (struct ip) >> 2;
1366 }
1367 
1368 int inetctlerrmap[PRC_NCMDS] = {
1369 	0,		0,		0,		0,
1370 	0,		EMSGSIZE,	EHOSTDOWN,	EHOSTUNREACH,
1371 	EHOSTUNREACH,	EHOSTUNREACH,	ECONNREFUSED,	ECONNREFUSED,
1372 	EMSGSIZE,	EHOSTUNREACH,	0,		0,
1373 	0,		0,		0,		0,
1374 	ENOPROTOOPT
1375 };
1376 
1377 /*
1378  * Forward a packet.  If some error occurs return the sender
1379  * an icmp packet.  Note we can't always generate a meaningful
1380  * icmp message because icmp doesn't have a large enough repertoire
1381  * of codes and types.
1382  *
1383  * If not forwarding, just drop the packet.  This could be confusing
1384  * if ipforwarding was zero but some routing protocol was advancing
1385  * us as a gateway to somewhere.  However, we must let the routing
1386  * protocol deal with that.
1387  *
1388  * The srcrt parameter indicates whether the packet is being forwarded
1389  * via a source route.
1390  */
1391 void
1392 ip_forward(m, srcrt)
1393 	struct mbuf *m;
1394 	int srcrt;
1395 {
1396 	struct ip *ip = mtod(m, struct ip *);
1397 	struct sockaddr_in *sin;
1398 	struct rtentry *rt;
1399 	int error, type = 0, code = 0;
1400 	struct mbuf *mcopy;
1401 	n_long dest;
1402 	struct ifnet *destifp;
1403 #ifdef IPSEC
1404 	struct ifnet dummyifp;
1405 #endif
1406 
1407 	dest = 0;
1408 #ifdef DIAGNOSTIC
1409 	if (ipprintfs)
1410 		printf("forward: src %2.2x dst %2.2x ttl %x\n",
1411 		    ntohl(ip->ip_src.s_addr),
1412 		    ntohl(ip->ip_dst.s_addr), ip->ip_ttl);
1413 #endif
1414 	if (m->m_flags & (M_BCAST|M_MCAST) || in_canforward(ip->ip_dst) == 0) {
1415 		ipstat.ips_cantforward++;
1416 		m_freem(m);
1417 		return;
1418 	}
1419 	if (ip->ip_ttl <= IPTTLDEC) {
1420 		icmp_error(m, ICMP_TIMXCEED, ICMP_TIMXCEED_INTRANS, dest, 0);
1421 		return;
1422 	}
1423 	ip->ip_ttl -= IPTTLDEC;
1424 
1425 	sin = satosin(&ipforward_rt.ro_dst);
1426 	if ((rt = ipforward_rt.ro_rt) == 0 ||
1427 	    !in_hosteq(ip->ip_dst, sin->sin_addr)) {
1428 		if (ipforward_rt.ro_rt) {
1429 			RTFREE(ipforward_rt.ro_rt);
1430 			ipforward_rt.ro_rt = 0;
1431 		}
1432 		sin->sin_family = AF_INET;
1433 		sin->sin_len = sizeof(struct sockaddr_in);
1434 		sin->sin_addr = ip->ip_dst;
1435 
1436 		rtalloc(&ipforward_rt);
1437 		if (ipforward_rt.ro_rt == 0) {
1438 			icmp_error(m, ICMP_UNREACH, ICMP_UNREACH_HOST, dest, 0);
1439 			return;
1440 		}
1441 		rt = ipforward_rt.ro_rt;
1442 	}
1443 
1444 	/*
1445 	 * Save at most 68 bytes of the packet in case
1446 	 * we need to generate an ICMP message to the src.
1447 	 * Pullup to avoid sharing mbuf cluster between m and mcopy.
1448 	 */
1449 	mcopy = m_copym(m, 0, imin((int)ip->ip_len, 68), M_DONTWAIT);
1450 	if (mcopy)
1451 		mcopy = m_pullup(mcopy, ip->ip_hl << 2);
1452 
1453 	/*
1454 	 * If forwarding packet using same interface that it came in on,
1455 	 * perhaps should send a redirect to sender to shortcut a hop.
1456 	 * Only send redirect if source is sending directly to us,
1457 	 * and if packet was not source routed (or has any options).
1458 	 * Also, don't send redirect if forwarding using a default route
1459 	 * or a route modified by a redirect.
1460 	 */
1461 	if (rt->rt_ifp == m->m_pkthdr.rcvif &&
1462 	    (rt->rt_flags & (RTF_DYNAMIC|RTF_MODIFIED)) == 0 &&
1463 	    !in_nullhost(satosin(rt_key(rt))->sin_addr) &&
1464 	    ipsendredirects && !srcrt) {
1465 		if (rt->rt_ifa &&
1466 		    (ip->ip_src.s_addr & ifatoia(rt->rt_ifa)->ia_subnetmask) ==
1467 		    ifatoia(rt->rt_ifa)->ia_subnet) {
1468 			if (rt->rt_flags & RTF_GATEWAY)
1469 				dest = satosin(rt->rt_gateway)->sin_addr.s_addr;
1470 			else
1471 				dest = ip->ip_dst.s_addr;
1472 			/*
1473 			 * Router requirements says to only send host
1474 			 * redirects.
1475 			 */
1476 			type = ICMP_REDIRECT;
1477 			code = ICMP_REDIRECT_HOST;
1478 #ifdef DIAGNOSTIC
1479 			if (ipprintfs)
1480 				printf("redirect (%d) to %x\n", code,
1481 				    (u_int32_t)dest);
1482 #endif
1483 		}
1484 	}
1485 
1486 #ifdef IPSEC
1487 	/* Don't lookup socket in forwading case */
1488 	(void)ipsec_setsocket(m, NULL);
1489 #endif
1490 	error = ip_output(m, (struct mbuf *)0, &ipforward_rt,
1491 	    (IP_FORWARDING | (ip_directedbcast ? IP_ALLOWBROADCAST : 0)), 0);
1492 	if (error)
1493 		ipstat.ips_cantforward++;
1494 	else {
1495 		ipstat.ips_forward++;
1496 		if (type)
1497 			ipstat.ips_redirectsent++;
1498 		else {
1499 			if (mcopy) {
1500 #ifdef GATEWAY
1501 				if (mcopy->m_flags & M_CANFASTFWD)
1502 					ipflow_create(&ipforward_rt, mcopy);
1503 #endif
1504 				m_freem(mcopy);
1505 			}
1506 			return;
1507 		}
1508 	}
1509 	if (mcopy == NULL)
1510 		return;
1511 	destifp = NULL;
1512 
1513 	switch (error) {
1514 
1515 	case 0:				/* forwarded, but need redirect */
1516 		/* type, code set above */
1517 		break;
1518 
1519 	case ENETUNREACH:		/* shouldn't happen, checked above */
1520 	case EHOSTUNREACH:
1521 	case ENETDOWN:
1522 	case EHOSTDOWN:
1523 	default:
1524 		type = ICMP_UNREACH;
1525 		code = ICMP_UNREACH_HOST;
1526 		break;
1527 
1528 	case EMSGSIZE:
1529 		type = ICMP_UNREACH;
1530 		code = ICMP_UNREACH_NEEDFRAG;
1531 #ifndef IPSEC
1532 		if (ipforward_rt.ro_rt)
1533 			destifp = ipforward_rt.ro_rt->rt_ifp;
1534 #else
1535 		/*
1536 		 * If the packet is routed over IPsec tunnel, tell the
1537 		 * originator the tunnel MTU.
1538 		 *	tunnel MTU = if MTU - sizeof(IP) - ESP/AH hdrsiz
1539 		 * XXX quickhack!!!
1540 		 */
1541 		if (ipforward_rt.ro_rt) {
1542 			struct secpolicy *sp;
1543 			int ipsecerror;
1544 			size_t ipsechdr;
1545 			struct route *ro;
1546 
1547 			sp = ipsec4_getpolicybyaddr(mcopy,
1548 			                            IPSEC_DIR_OUTBOUND,
1549 			                            IP_FORWARDING,
1550 			                            &ipsecerror);
1551 
1552 			if (sp == NULL)
1553 				destifp = ipforward_rt.ro_rt->rt_ifp;
1554 			else {
1555 				/* count IPsec header size */
1556 				ipsechdr = ipsec4_hdrsiz(mcopy,
1557 				                         IPSEC_DIR_OUTBOUND,
1558 				                         NULL);
1559 
1560 				/*
1561 				 * find the correct route for outer IPv4
1562 				 * header, compute tunnel MTU.
1563 				 *
1564 				 * XXX BUG ALERT
1565 				 * The "dummyifp" code relies upon the fact
1566 				 * that icmp_error() touches only ifp->if_mtu.
1567 				 */
1568 				/*XXX*/
1569 				destifp = NULL;
1570 				if (sp->req != NULL
1571 				 && sp->req->sav != NULL
1572 				 && sp->req->sav->sah != NULL) {
1573 					ro = &sp->req->sav->sah->sa_route;
1574 					if (ro->ro_rt && ro->ro_rt->rt_ifp) {
1575 						dummyifp.if_mtu =
1576 						    ro->ro_rt->rt_ifp->if_mtu;
1577 						dummyifp.if_mtu -= ipsechdr;
1578 						destifp = &dummyifp;
1579 					}
1580 				}
1581 
1582 				key_freesp(sp);
1583 			}
1584 		}
1585 #endif /*IPSEC*/
1586 		ipstat.ips_cantfrag++;
1587 		break;
1588 
1589 	case ENOBUFS:
1590 		type = ICMP_SOURCEQUENCH;
1591 		code = 0;
1592 		break;
1593 	}
1594 	icmp_error(mcopy, type, code, dest, destifp);
1595 }
1596 
1597 void
1598 ip_savecontrol(inp, mp, ip, m)
1599 	struct inpcb *inp;
1600 	struct mbuf **mp;
1601 	struct ip *ip;
1602 	struct mbuf *m;
1603 {
1604 
1605 	if (inp->inp_socket->so_options & SO_TIMESTAMP) {
1606 		struct timeval tv;
1607 
1608 		microtime(&tv);
1609 		*mp = sbcreatecontrol((caddr_t) &tv, sizeof(tv),
1610 		    SCM_TIMESTAMP, SOL_SOCKET);
1611 		if (*mp)
1612 			mp = &(*mp)->m_next;
1613 	}
1614 	if (inp->inp_flags & INP_RECVDSTADDR) {
1615 		*mp = sbcreatecontrol((caddr_t) &ip->ip_dst,
1616 		    sizeof(struct in_addr), IP_RECVDSTADDR, IPPROTO_IP);
1617 		if (*mp)
1618 			mp = &(*mp)->m_next;
1619 	}
1620 #ifdef notyet
1621 	/*
1622 	 * XXX
1623 	 * Moving these out of udp_input() made them even more broken
1624 	 * than they already were.
1625 	 *	- fenner@parc.xerox.com
1626 	 */
1627 	/* options were tossed already */
1628 	if (inp->inp_flags & INP_RECVOPTS) {
1629 		*mp = sbcreatecontrol((caddr_t) opts_deleted_above,
1630 		    sizeof(struct in_addr), IP_RECVOPTS, IPPROTO_IP);
1631 		if (*mp)
1632 			mp = &(*mp)->m_next;
1633 	}
1634 	/* ip_srcroute doesn't do what we want here, need to fix */
1635 	if (inp->inp_flags & INP_RECVRETOPTS) {
1636 		*mp = sbcreatecontrol((caddr_t) ip_srcroute(),
1637 		    sizeof(struct in_addr), IP_RECVRETOPTS, IPPROTO_IP);
1638 		if (*mp)
1639 			mp = &(*mp)->m_next;
1640 	}
1641 #endif
1642 	if (inp->inp_flags & INP_RECVIF) {
1643 		struct sockaddr_dl sdl;
1644 
1645 		sdl.sdl_len = offsetof(struct sockaddr_dl, sdl_data[0]);
1646 		sdl.sdl_family = AF_LINK;
1647 		sdl.sdl_index = m->m_pkthdr.rcvif ?
1648 		    m->m_pkthdr.rcvif->if_index : 0;
1649 		sdl.sdl_nlen = sdl.sdl_alen = sdl.sdl_slen = 0;
1650 		*mp = sbcreatecontrol((caddr_t) &sdl, sdl.sdl_len,
1651 		    IP_RECVIF, IPPROTO_IP);
1652 		if (*mp)
1653 			mp = &(*mp)->m_next;
1654 	}
1655 }
1656 
1657 int
1658 ip_sysctl(name, namelen, oldp, oldlenp, newp, newlen)
1659 	int *name;
1660 	u_int namelen;
1661 	void *oldp;
1662 	size_t *oldlenp;
1663 	void *newp;
1664 	size_t newlen;
1665 {
1666 	extern int subnetsarelocal, hostzeroisbroadcast;
1667 
1668 	int error, old;
1669 
1670 	/* All sysctl names at this level are terminal. */
1671 	if (namelen != 1)
1672 		return (ENOTDIR);
1673 
1674 	switch (name[0]) {
1675 	case IPCTL_FORWARDING:
1676 		return (sysctl_int(oldp, oldlenp, newp, newlen, &ipforwarding));
1677 	case IPCTL_SENDREDIRECTS:
1678 		return (sysctl_int(oldp, oldlenp, newp, newlen,
1679 			&ipsendredirects));
1680 	case IPCTL_DEFTTL:
1681 		return (sysctl_int(oldp, oldlenp, newp, newlen, &ip_defttl));
1682 #ifdef notyet
1683 	case IPCTL_DEFMTU:
1684 		return (sysctl_int(oldp, oldlenp, newp, newlen, &ip_mtu));
1685 #endif
1686 	case IPCTL_FORWSRCRT:
1687 		/* Don't allow this to change in a secure environment.  */
1688 		if (securelevel > 0)
1689 			return (sysctl_rdint(oldp, oldlenp, newp,
1690 			    ip_forwsrcrt));
1691 		else
1692 			return (sysctl_int(oldp, oldlenp, newp, newlen,
1693 			    &ip_forwsrcrt));
1694 	case IPCTL_DIRECTEDBCAST:
1695 		return (sysctl_int(oldp, oldlenp, newp, newlen,
1696 		    &ip_directedbcast));
1697 	case IPCTL_ALLOWSRCRT:
1698 		return (sysctl_int(oldp, oldlenp, newp, newlen,
1699 		    &ip_allowsrcrt));
1700 	case IPCTL_SUBNETSARELOCAL:
1701 		return (sysctl_int(oldp, oldlenp, newp, newlen,
1702 		    &subnetsarelocal));
1703 	case IPCTL_MTUDISC:
1704 		error = sysctl_int(oldp, oldlenp, newp, newlen,
1705 		    &ip_mtudisc);
1706 		if (ip_mtudisc != 0 && ip_mtudisc_timeout_q == NULL) {
1707 			ip_mtudisc_timeout_q =
1708 			    rt_timer_queue_create(ip_mtudisc_timeout);
1709 		} else if (ip_mtudisc == 0 && ip_mtudisc_timeout_q != NULL) {
1710 			rt_timer_queue_destroy(ip_mtudisc_timeout_q, TRUE);
1711 			ip_mtudisc_timeout_q = NULL;
1712 		}
1713 		return error;
1714 	case IPCTL_ANONPORTMIN:
1715 		old = anonportmin;
1716 		error = sysctl_int(oldp, oldlenp, newp, newlen, &anonportmin);
1717 		if (anonportmin >= anonportmax || anonportmin < 0
1718 		    || anonportmin > 65535
1719 #ifndef IPNOPRIVPORTS
1720 		    || anonportmin < IPPORT_RESERVED
1721 #endif
1722 		    ) {
1723 			anonportmin = old;
1724 			return (EINVAL);
1725 		}
1726 		return (error);
1727 	case IPCTL_ANONPORTMAX:
1728 		old = anonportmax;
1729 		error = sysctl_int(oldp, oldlenp, newp, newlen, &anonportmax);
1730 		if (anonportmin >= anonportmax || anonportmax < 0
1731 		    || anonportmax > 65535
1732 #ifndef IPNOPRIVPORTS
1733 		    || anonportmax < IPPORT_RESERVED
1734 #endif
1735 		    ) {
1736 			anonportmax = old;
1737 			return (EINVAL);
1738 		}
1739 		return (error);
1740 	case IPCTL_MTUDISCTIMEOUT:
1741 		error = sysctl_int(oldp, oldlenp, newp, newlen,
1742 		   &ip_mtudisc_timeout);
1743 		if (ip_mtudisc_timeout_q != NULL)
1744 			rt_timer_queue_change(ip_mtudisc_timeout_q,
1745 					      ip_mtudisc_timeout);
1746 		return (error);
1747 #ifdef GATEWAY
1748 	case IPCTL_MAXFLOWS:
1749 	    {
1750 		int s;
1751 
1752 		error = sysctl_int(oldp, oldlenp, newp, newlen,
1753 		   &ip_maxflows);
1754 		s = splsoftnet();
1755 		ipflow_reap(0);
1756 		splx(s);
1757 		return (error);
1758 	    }
1759 #endif
1760 	case IPCTL_HOSTZEROBROADCAST:
1761 		return (sysctl_int(oldp, oldlenp, newp, newlen,
1762 		    &hostzeroisbroadcast));
1763 #if NGIF > 0
1764 	case IPCTL_GIF_TTL:
1765 		return(sysctl_int(oldp, oldlenp, newp, newlen,
1766 				  &ip_gif_ttl));
1767 #endif
1768 
1769 #ifndef IPNOPRIVPORTS
1770 	case IPCTL_LOWPORTMIN:
1771 		old = lowportmin;
1772 		error = sysctl_int(oldp, oldlenp, newp, newlen, &lowportmin);
1773 		if (lowportmin >= lowportmax
1774 		    || lowportmin > IPPORT_RESERVEDMAX
1775 		    || lowportmin < IPPORT_RESERVEDMIN
1776 		    ) {
1777 			lowportmin = old;
1778 			return (EINVAL);
1779 		}
1780 		return (error);
1781 	case IPCTL_LOWPORTMAX:
1782 		old = lowportmax;
1783 		error = sysctl_int(oldp, oldlenp, newp, newlen, &lowportmax);
1784 		if (lowportmin >= lowportmax
1785 		    || lowportmax > IPPORT_RESERVEDMAX
1786 		    || lowportmax < IPPORT_RESERVEDMIN
1787 		    ) {
1788 			lowportmax = old;
1789 			return (EINVAL);
1790 		}
1791 		return (error);
1792 #endif
1793 
1794 	default:
1795 		return (EOPNOTSUPP);
1796 	}
1797 	/* NOTREACHED */
1798 }
1799