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