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