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