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