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