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