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