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