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