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