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