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