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