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