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