ip_input.c revision 7090
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.17 1995/02/14 23:04:52 wollman Exp $
35 */
36
37#include <sys/param.h>
38#include <sys/systm.h>
39#include <sys/malloc.h>
40#include <sys/mbuf.h>
41#include <sys/domain.h>
42#include <sys/protosw.h>
43#include <sys/socket.h>
44#include <sys/errno.h>
45#include <sys/time.h>
46#include <sys/kernel.h>
47#include <vm/vm.h>
48#include <sys/sysctl.h>
49
50#include <net/if.h>
51#include <net/route.h>
52
53#include <netinet/in.h>
54#include <netinet/in_systm.h>
55#include <netinet/in_var.h>
56#include <netinet/ip.h>
57#include <netinet/in_pcb.h>
58#include <netinet/in_var.h>
59#include <netinet/ip_var.h>
60#include <netinet/ip_icmp.h>
61
62#include <netinet/ip_fw.h>
63
64#include <sys/socketvar.h>
65struct socket *ip_rsvpd;
66
67#ifndef	IPFORWARDING
68#ifdef GATEWAY
69#define	IPFORWARDING	1	/* forward IP packets not for us */
70#else /* GATEWAY */
71#define	IPFORWARDING	0	/* don't forward IP packets not for us */
72#endif /* GATEWAY */
73#endif /* IPFORWARDING */
74#ifndef	IPSENDREDIRECTS
75#define	IPSENDREDIRECTS	1
76#endif
77int	ipforwarding = IPFORWARDING;
78int	ipsendredirects = IPSENDREDIRECTS;
79int	ip_defttl = IPDEFTTL;
80#ifdef DIAGNOSTIC
81int	ipprintfs = 0;
82#endif
83
84extern	struct domain inetdomain;
85extern	struct protosw inetsw[];
86u_char	ip_protox[IPPROTO_MAX];
87int	ipqmaxlen = IFQ_MAXLEN;
88struct	in_ifaddr *in_ifaddr;			/* first inet address */
89struct	ifqueue ipintrq;
90
91struct ipstat ipstat;
92struct ipq ipq;
93
94/*
95 * We need to save the IP options in case a protocol wants to respond
96 * to an incoming packet over the same route if the packet got here
97 * using IP source routing.  This allows connection establishment and
98 * maintenance when the remote end is on a network that is not known
99 * to us.
100 */
101int	ip_nhops = 0;
102static	struct ip_srcrt {
103	struct	in_addr dst;			/* final destination */
104	char	nop;				/* one NOP to align */
105	char	srcopt[IPOPT_OFFSET + 1];	/* OPTVAL, OLEN and OFFSET */
106	struct	in_addr route[MAX_IPOPTLEN/sizeof(struct in_addr)];
107} ip_srcrt;
108
109#ifdef GATEWAY
110extern	int if_index;
111u_long	*ip_ifmatrix;
112#endif
113
114static void save_rte __P((u_char *, struct in_addr));
115/*
116 * IP initialization: fill in IP protocol switch table.
117 * All protocols not implemented in kernel go to raw IP protocol handler.
118 */
119void
120ip_init()
121{
122	register struct protosw *pr;
123	register int i;
124
125	pr = pffindproto(PF_INET, IPPROTO_RAW, SOCK_RAW);
126	if (pr == 0)
127		panic("ip_init");
128	for (i = 0; i < IPPROTO_MAX; i++)
129		ip_protox[i] = pr - inetsw;
130	for (pr = inetdomain.dom_protosw;
131	    pr < inetdomain.dom_protoswNPROTOSW; pr++)
132		if (pr->pr_domain->dom_family == PF_INET &&
133		    pr->pr_protocol && pr->pr_protocol != IPPROTO_RAW)
134			ip_protox[pr->pr_protocol] = pr - inetsw;
135	ipq.next = ipq.prev = &ipq;
136	ip_id = time.tv_sec & 0xffff;
137	ipintrq.ifq_maxlen = ipqmaxlen;
138#ifdef GATEWAY
139	i = (if_index + 1) * (if_index + 1) * sizeof (u_long);
140	ip_ifmatrix = (u_long *) malloc(i, M_RTABLE, M_WAITOK);
141	bzero((char *)ip_ifmatrix, i);
142#endif
143}
144
145struct	sockaddr_in ipaddr = { sizeof(ipaddr), AF_INET };
146struct	route ipforward_rt;
147
148/*
149 * Ip input routine.  Checksum and byte swap header.  If fragmented
150 * try to reassemble.  Process options.  Pass to next level.
151 */
152void
153ipintr()
154{
155	register struct ip *ip;
156	register struct mbuf *m;
157	register struct ipq *fp;
158	register struct in_ifaddr *ia;
159	int hlen, s;
160
161next:
162	/*
163	 * Get next datagram off input queue and get IP header
164	 * in first mbuf.
165	 */
166	s = splimp();
167	IF_DEQUEUE(&ipintrq, m);
168	splx(s);
169	if (m == 0)
170		return;
171#ifdef	DIAGNOSTIC
172	if ((m->m_flags & M_PKTHDR) == 0)
173		panic("ipintr no HDR");
174#endif
175	/*
176	 * If no IP addresses have been set yet but the interfaces
177	 * are receiving, can't do anything with incoming packets yet.
178	 */
179	if (in_ifaddr == NULL)
180		goto bad;
181	ipstat.ips_total++;
182	if (m->m_len < sizeof (struct ip) &&
183	    (m = m_pullup(m, sizeof (struct ip))) == 0) {
184		ipstat.ips_toosmall++;
185		goto next;
186	}
187	ip = mtod(m, struct ip *);
188	if (ip->ip_v != IPVERSION) {
189		ipstat.ips_badvers++;
190		goto bad;
191	}
192	hlen = ip->ip_hl << 2;
193	if (hlen < sizeof(struct ip)) {	/* minimum header length */
194		ipstat.ips_badhlen++;
195		goto bad;
196	}
197	if (hlen > m->m_len) {
198		if ((m = m_pullup(m, hlen)) == 0) {
199			ipstat.ips_badhlen++;
200			goto next;
201		}
202		ip = mtod(m, struct ip *);
203	}
204	ip->ip_sum = in_cksum(m, hlen);
205	if (ip->ip_sum) {
206		ipstat.ips_badsum++;
207		goto bad;
208	}
209
210	/*
211	 * Convert fields to host representation.
212	 */
213	NTOHS(ip->ip_len);
214	if (ip->ip_len < hlen) {
215		ipstat.ips_badlen++;
216		goto bad;
217	}
218	NTOHS(ip->ip_id);
219	NTOHS(ip->ip_off);
220
221	/*
222	 * Check that the amount of data in the buffers
223	 * is as at least much as the IP header would have us expect.
224	 * Trim mbufs if longer than we expect.
225	 * Drop packet if shorter than we expect.
226	 */
227	if (m->m_pkthdr.len < ip->ip_len) {
228		ipstat.ips_tooshort++;
229		goto bad;
230	}
231	if (m->m_pkthdr.len > ip->ip_len) {
232		if (m->m_len == m->m_pkthdr.len) {
233			m->m_len = ip->ip_len;
234			m->m_pkthdr.len = ip->ip_len;
235		} else
236			m_adj(m, ip->ip_len - m->m_pkthdr.len);
237	}
238	/*
239	 * IpHack's section.
240	 * Right now when no processing on packet has done
241	 * and it is still fresh out of network we do our black
242	 * deals with it.
243	 * - Firewall: deny/allow
244	 * - Wrap: fake packet's addr/port <unimpl.>
245	 * - Encapsulate: put it in another IP and send out. <unimp.>
246 	 */
247
248        if (ip_fw_chk_ptr!=NULL)
249               if (!(*ip_fw_chk_ptr)(ip,m->m_pkthdr.rcvif,ip_fw_chain) ) {
250                       goto bad;
251               }
252
253	/*
254	 * Process options and, if not destined for us,
255	 * ship it on.  ip_dooptions returns 1 when an
256	 * error was detected (causing an icmp message
257	 * to be sent and the original packet to be freed).
258	 */
259	ip_nhops = 0;		/* for source routed packets */
260	if (hlen > sizeof (struct ip) && ip_dooptions(m))
261		goto next;
262
263        /* greedy RSVP, snatches any PATH packet of the RSVP protocol and no
264         * matter if it is destined to another node, or whether it is
265         * a multicast one, RSVP wants it! and prevents it from being forwarded
266         * anywhere else. Also checks if the rsvp daemon is running before
267	 * grabbing the packet.
268         */
269	if (ip_rsvpd != NULL && ip->ip_p==IPPROTO_RSVP)
270		goto ours;
271
272	/*
273	 * Check our list of addresses, to see if the packet is for us.
274	 */
275	for (ia = in_ifaddr; ia; ia = ia->ia_next) {
276#define	satosin(sa)	((struct sockaddr_in *)(sa))
277
278		if (IA_SIN(ia)->sin_addr.s_addr == ip->ip_dst.s_addr)
279			goto ours;
280		if (
281#ifdef	DIRECTED_BROADCAST
282		    ia->ia_ifp == m->m_pkthdr.rcvif &&
283#endif
284		    (ia->ia_ifp->if_flags & IFF_BROADCAST)) {
285			u_long t;
286
287			if (satosin(&ia->ia_broadaddr)->sin_addr.s_addr ==
288			    ip->ip_dst.s_addr)
289				goto ours;
290			if (ip->ip_dst.s_addr == ia->ia_netbroadcast.s_addr)
291				goto ours;
292			/*
293			 * Look for all-0's host part (old broadcast addr),
294			 * either for subnet or net.
295			 */
296			t = ntohl(ip->ip_dst.s_addr);
297			if (t == ia->ia_subnet)
298				goto ours;
299			if (t == ia->ia_net)
300				goto ours;
301		}
302	}
303	if (IN_MULTICAST(ntohl(ip->ip_dst.s_addr))) {
304		struct in_multi *inm;
305		if (ip_mrouter) {
306			/*
307			 * If we are acting as a multicast router, all
308			 * incoming multicast packets are passed to the
309			 * kernel-level multicast forwarding function.
310			 * The packet is returned (relatively) intact; if
311			 * ip_mforward() returns a non-zero value, the packet
312			 * must be discarded, else it may be accepted below.
313			 *
314			 * (The IP ident field is put in the same byte order
315			 * as expected when ip_mforward() is called from
316			 * ip_output().)
317			 */
318			ip->ip_id = htons(ip->ip_id);
319			if (ip_mforward(ip, m->m_pkthdr.rcvif, m, 0) != 0) {
320				ipstat.ips_cantforward++;
321				m_freem(m);
322				goto next;
323			}
324			ip->ip_id = ntohs(ip->ip_id);
325
326			/*
327			 * The process-level routing demon needs to receive
328			 * all multicast IGMP packets, whether or not this
329			 * host belongs to their destination groups.
330			 */
331			if (ip->ip_p == IPPROTO_IGMP)
332				goto ours;
333			ipstat.ips_forward++;
334		}
335		/*
336		 * See if we belong to the destination multicast group on the
337		 * arrival interface.
338		 */
339		IN_LOOKUP_MULTI(ip->ip_dst, m->m_pkthdr.rcvif, inm);
340		if (inm == NULL) {
341			ipstat.ips_cantforward++;
342			m_freem(m);
343			goto next;
344		}
345		goto ours;
346	}
347	if (ip->ip_dst.s_addr == (u_long)INADDR_BROADCAST)
348		goto ours;
349	if (ip->ip_dst.s_addr == INADDR_ANY)
350		goto ours;
351
352	/*
353	 * Not for us; forward if possible and desirable.
354	 */
355	if (ipforwarding == 0) {
356		ipstat.ips_cantforward++;
357		m_freem(m);
358	} else
359		ip_forward(m, 0);
360	goto next;
361
362ours:
363
364		/*
365		 * If packet came to us we count it...
366		 * This way we count all incoming packets which has
367		 * not been forwarded...
368		 * Do not convert ip_len to host byte order when
369		 * counting,ppl already made it for us before..
370		 */
371	if (ip_acct_cnt_ptr!=NULL)
372		(*ip_acct_cnt_ptr)(ip,m->m_pkthdr.rcvif,ip_acct_chain,0);
373
374	/*
375	 * If offset or IP_MF are set, must reassemble.
376	 * Otherwise, nothing need be done.
377	 * (We could look in the reassembly queue to see
378	 * if the packet was previously fragmented,
379	 * but it's not worth the time; just let them time out.)
380	 */
381	if (ip->ip_off &~ IP_DF) {
382		if (m->m_flags & M_EXT) {		/* XXX */
383			if ((m = m_pullup(m, sizeof (struct ip))) == 0) {
384				ipstat.ips_toosmall++;
385				goto next;
386			}
387			ip = mtod(m, struct ip *);
388		}
389		/*
390		 * Look for queue of fragments
391		 * of this datagram.
392		 */
393		for (fp = ipq.next; fp != &ipq; fp = fp->next)
394			if (ip->ip_id == fp->ipq_id &&
395			    ip->ip_src.s_addr == fp->ipq_src.s_addr &&
396			    ip->ip_dst.s_addr == fp->ipq_dst.s_addr &&
397			    ip->ip_p == fp->ipq_p)
398				goto found;
399		fp = 0;
400found:
401
402		/*
403		 * Adjust ip_len to not reflect header,
404		 * set ip_mff if more fragments are expected,
405		 * convert offset of this to bytes.
406		 */
407		ip->ip_len -= hlen;
408		((struct ipasfrag *)ip)->ipf_mff &= ~1;
409		if (ip->ip_off & IP_MF)
410			((struct ipasfrag *)ip)->ipf_mff |= 1;
411		ip->ip_off <<= 3;
412
413		/*
414		 * If datagram marked as having more fragments
415		 * or if this is not the first fragment,
416		 * attempt reassembly; if it succeeds, proceed.
417		 */
418		if (((struct ipasfrag *)ip)->ipf_mff & 1 || ip->ip_off) {
419			ipstat.ips_fragments++;
420			ip = ip_reass((struct ipasfrag *)ip, fp);
421			if (ip == 0)
422				goto next;
423			ipstat.ips_reassembled++;
424			m = dtom(ip);
425		} else
426			if (fp)
427				ip_freef(fp);
428	} else
429		ip->ip_len -= hlen;
430
431	/*
432	 * Switch out to protocol's input routine.
433	 */
434	ipstat.ips_delivered++;
435	(*inetsw[ip_protox[ip->ip_p]].pr_input)(m, hlen);
436	goto next;
437bad:
438	m_freem(m);
439	goto next;
440}
441
442/*
443 * Take incoming datagram fragment and try to
444 * reassemble it into whole datagram.  If a chain for
445 * reassembly of this datagram already exists, then it
446 * is given as fp; otherwise have to make a chain.
447 */
448struct ip *
449ip_reass(ip, fp)
450	register struct ipasfrag *ip;
451	register struct ipq *fp;
452{
453	register struct mbuf *m = dtom(ip);
454	register struct ipasfrag *q;
455	struct mbuf *t;
456	int hlen = ip->ip_hl << 2;
457	int i, next;
458
459	/*
460	 * Presence of header sizes in mbufs
461	 * would confuse code below.
462	 */
463	m->m_data += hlen;
464	m->m_len -= hlen;
465
466	/*
467	 * If first fragment to arrive, create a reassembly queue.
468	 */
469	if (fp == 0) {
470		if ((t = m_get(M_DONTWAIT, MT_FTABLE)) == NULL)
471			goto dropfrag;
472		fp = mtod(t, struct ipq *);
473		insque(fp, &ipq);
474		fp->ipq_ttl = IPFRAGTTL;
475		fp->ipq_p = ip->ip_p;
476		fp->ipq_id = ip->ip_id;
477		fp->ipq_next = fp->ipq_prev = (struct ipasfrag *)fp;
478		fp->ipq_src = ((struct ip *)ip)->ip_src;
479		fp->ipq_dst = ((struct ip *)ip)->ip_dst;
480		q = (struct ipasfrag *)fp;
481		goto insert;
482	}
483
484	/*
485	 * Find a segment which begins after this one does.
486	 */
487	for (q = fp->ipq_next; q != (struct ipasfrag *)fp; q = q->ipf_next)
488		if (q->ip_off > ip->ip_off)
489			break;
490
491	/*
492	 * If there is a preceding segment, it may provide some of
493	 * our data already.  If so, drop the data from the incoming
494	 * segment.  If it provides all of our data, drop us.
495	 */
496	if (q->ipf_prev != (struct ipasfrag *)fp) {
497		i = q->ipf_prev->ip_off + q->ipf_prev->ip_len - ip->ip_off;
498		if (i > 0) {
499			if (i >= ip->ip_len)
500				goto dropfrag;
501			m_adj(dtom(ip), i);
502			ip->ip_off += i;
503			ip->ip_len -= i;
504		}
505	}
506
507	/*
508	 * While we overlap succeeding segments trim them or,
509	 * if they are completely covered, dequeue them.
510	 */
511	while (q != (struct ipasfrag *)fp && ip->ip_off + ip->ip_len > q->ip_off) {
512		i = (ip->ip_off + ip->ip_len) - q->ip_off;
513		if (i < q->ip_len) {
514			q->ip_len -= i;
515			q->ip_off += i;
516			m_adj(dtom(q), i);
517			break;
518		}
519		q = q->ipf_next;
520		m_freem(dtom(q->ipf_prev));
521		ip_deq(q->ipf_prev);
522	}
523
524insert:
525	/*
526	 * Stick new segment in its place;
527	 * check for complete reassembly.
528	 */
529	ip_enq(ip, q->ipf_prev);
530	next = 0;
531	for (q = fp->ipq_next; q != (struct ipasfrag *)fp; q = q->ipf_next) {
532		if (q->ip_off != next)
533			return (0);
534		next += q->ip_len;
535	}
536	if (q->ipf_prev->ipf_mff & 1)
537		return (0);
538
539	/*
540	 * Reassembly is complete; concatenate fragments.
541	 */
542	q = fp->ipq_next;
543	m = dtom(q);
544	t = m->m_next;
545	m->m_next = 0;
546	m_cat(m, t);
547	q = q->ipf_next;
548	while (q != (struct ipasfrag *)fp) {
549		t = dtom(q);
550		q = q->ipf_next;
551		m_cat(m, t);
552	}
553
554	/*
555	 * Create header for new ip packet by
556	 * modifying header of first packet;
557	 * dequeue and discard fragment reassembly header.
558	 * Make header visible.
559	 */
560	ip = fp->ipq_next;
561	ip->ip_len = next;
562	ip->ipf_mff &= ~1;
563	((struct ip *)ip)->ip_src = fp->ipq_src;
564	((struct ip *)ip)->ip_dst = fp->ipq_dst;
565	remque(fp);
566	(void) m_free(dtom(fp));
567	m = dtom(ip);
568	m->m_len += (ip->ip_hl << 2);
569	m->m_data -= (ip->ip_hl << 2);
570	/* some debugging cruft by sklower, below, will go away soon */
571	if (m->m_flags & M_PKTHDR) { /* XXX this should be done elsewhere */
572		register int plen = 0;
573		for (t = m; m; m = m->m_next)
574			plen += m->m_len;
575		t->m_pkthdr.len = plen;
576	}
577	return ((struct ip *)ip);
578
579dropfrag:
580	ipstat.ips_fragdropped++;
581	m_freem(m);
582	return (0);
583}
584
585/*
586 * Free a fragment reassembly header and all
587 * associated datagrams.
588 */
589void
590ip_freef(fp)
591	struct ipq *fp;
592{
593	register struct ipasfrag *q, *p;
594
595	for (q = fp->ipq_next; q != (struct ipasfrag *)fp; q = p) {
596		p = q->ipf_next;
597		ip_deq(q);
598		m_freem(dtom(q));
599	}
600	remque(fp);
601	(void) m_free(dtom(fp));
602}
603
604/*
605 * Put an ip fragment on a reassembly chain.
606 * Like insque, but pointers in middle of structure.
607 */
608void
609ip_enq(p, prev)
610	register struct ipasfrag *p, *prev;
611{
612
613	p->ipf_prev = prev;
614	p->ipf_next = prev->ipf_next;
615	prev->ipf_next->ipf_prev = p;
616	prev->ipf_next = p;
617}
618
619/*
620 * To ip_enq as remque is to insque.
621 */
622void
623ip_deq(p)
624	register struct ipasfrag *p;
625{
626
627	p->ipf_prev->ipf_next = p->ipf_next;
628	p->ipf_next->ipf_prev = p->ipf_prev;
629}
630
631/*
632 * IP timer processing;
633 * if a timer expires on a reassembly
634 * queue, discard it.
635 */
636void
637ip_slowtimo()
638{
639	register struct ipq *fp;
640	int s = splnet();
641
642	fp = ipq.next;
643	if (fp == 0) {
644		splx(s);
645		return;
646	}
647	while (fp != &ipq) {
648		--fp->ipq_ttl;
649		fp = fp->next;
650		if (fp->prev->ipq_ttl == 0) {
651			ipstat.ips_fragtimeout++;
652			ip_freef(fp->prev);
653		}
654	}
655	splx(s);
656}
657
658/*
659 * Drain off all datagram fragments.
660 */
661void
662ip_drain()
663{
664
665	while (ipq.next != &ipq) {
666		ipstat.ips_fragdropped++;
667		ip_freef(ipq.next);
668	}
669}
670
671/*
672 * Do option processing on a datagram,
673 * possibly discarding it if bad options are encountered,
674 * or forwarding it if source-routed.
675 * Returns 1 if packet has been forwarded/freed,
676 * 0 if the packet should be processed further.
677 */
678int
679ip_dooptions(m)
680	struct mbuf *m;
681{
682	register struct ip *ip = mtod(m, struct ip *);
683	register u_char *cp;
684	register struct ip_timestamp *ipt;
685	register struct in_ifaddr *ia;
686	int opt, optlen, cnt, off, code, type = ICMP_PARAMPROB, forward = 0;
687	struct in_addr *sin, dst;
688	n_time ntime;
689
690	dst = ip->ip_dst;
691	cp = (u_char *)(ip + 1);
692	cnt = (ip->ip_hl << 2) - sizeof (struct ip);
693	for (; cnt > 0; cnt -= optlen, cp += optlen) {
694		opt = cp[IPOPT_OPTVAL];
695		if (opt == IPOPT_EOL)
696			break;
697		if (opt == IPOPT_NOP)
698			optlen = 1;
699		else {
700			optlen = cp[IPOPT_OLEN];
701			if (optlen <= 0 || optlen > cnt) {
702				code = &cp[IPOPT_OLEN] - (u_char *)ip;
703				goto bad;
704			}
705		}
706		switch (opt) {
707
708		default:
709			break;
710
711		/*
712		 * Source routing with record.
713		 * Find interface with current destination address.
714		 * If none on this machine then drop if strictly routed,
715		 * or do nothing if loosely routed.
716		 * Record interface address and bring up next address
717		 * component.  If strictly routed make sure next
718		 * address is on directly accessible net.
719		 */
720		case IPOPT_LSRR:
721		case IPOPT_SSRR:
722			if ((off = cp[IPOPT_OFFSET]) < IPOPT_MINOFF) {
723				code = &cp[IPOPT_OFFSET] - (u_char *)ip;
724				goto bad;
725			}
726			ipaddr.sin_addr = ip->ip_dst;
727			ia = (struct in_ifaddr *)
728				ifa_ifwithaddr((struct sockaddr *)&ipaddr);
729			if (ia == 0) {
730				if (opt == IPOPT_SSRR) {
731					type = ICMP_UNREACH;
732					code = ICMP_UNREACH_SRCFAIL;
733					goto bad;
734				}
735				/*
736				 * Loose routing, and not at next destination
737				 * yet; nothing to do except forward.
738				 */
739				break;
740			}
741			off--;			/* 0 origin */
742			if (off > optlen - sizeof(struct in_addr)) {
743				/*
744				 * End of source route.  Should be for us.
745				 */
746				save_rte(cp, ip->ip_src);
747				break;
748			}
749			/*
750			 * locate outgoing interface
751			 */
752			bcopy((caddr_t)(cp + off), (caddr_t)&ipaddr.sin_addr,
753			    sizeof(ipaddr.sin_addr));
754			if (opt == IPOPT_SSRR) {
755#define	INA	struct in_ifaddr *
756#define	SA	struct sockaddr *
757			    if ((ia = (INA)ifa_ifwithdstaddr((SA)&ipaddr)) == 0)
758				ia = (INA)ifa_ifwithnet((SA)&ipaddr);
759			} else
760				ia = ip_rtaddr(ipaddr.sin_addr);
761			if (ia == 0) {
762				type = ICMP_UNREACH;
763				code = ICMP_UNREACH_SRCFAIL;
764				goto bad;
765			}
766			ip->ip_dst = ipaddr.sin_addr;
767			bcopy((caddr_t)&(IA_SIN(ia)->sin_addr),
768			    (caddr_t)(cp + off), sizeof(struct in_addr));
769			cp[IPOPT_OFFSET] += sizeof(struct in_addr);
770			/*
771			 * Let ip_intr's mcast routing check handle mcast pkts
772			 */
773			forward = !IN_MULTICAST(ntohl(ip->ip_dst.s_addr));
774			break;
775
776		case IPOPT_RR:
777			if ((off = cp[IPOPT_OFFSET]) < IPOPT_MINOFF) {
778				code = &cp[IPOPT_OFFSET] - (u_char *)ip;
779				goto bad;
780			}
781			/*
782			 * If no space remains, ignore.
783			 */
784			off--;			/* 0 origin */
785			if (off > optlen - sizeof(struct in_addr))
786				break;
787			bcopy((caddr_t)(&ip->ip_dst), (caddr_t)&ipaddr.sin_addr,
788			    sizeof(ipaddr.sin_addr));
789			/*
790			 * locate outgoing interface; if we're the destination,
791			 * use the incoming interface (should be same).
792			 */
793			if ((ia = (INA)ifa_ifwithaddr((SA)&ipaddr)) == 0 &&
794			    (ia = ip_rtaddr(ipaddr.sin_addr)) == 0) {
795				type = ICMP_UNREACH;
796				code = ICMP_UNREACH_HOST;
797				goto bad;
798			}
799			bcopy((caddr_t)&(IA_SIN(ia)->sin_addr),
800			    (caddr_t)(cp + off), sizeof(struct in_addr));
801			cp[IPOPT_OFFSET] += sizeof(struct in_addr);
802			break;
803
804		case IPOPT_TS:
805			code = cp - (u_char *)ip;
806			ipt = (struct ip_timestamp *)cp;
807			if (ipt->ipt_len < 5)
808				goto bad;
809			if (ipt->ipt_ptr > ipt->ipt_len - sizeof (long)) {
810				if (++ipt->ipt_oflw == 0)
811					goto bad;
812				break;
813			}
814			sin = (struct in_addr *)(cp + ipt->ipt_ptr - 1);
815			switch (ipt->ipt_flg) {
816
817			case IPOPT_TS_TSONLY:
818				break;
819
820			case IPOPT_TS_TSANDADDR:
821				if (ipt->ipt_ptr + sizeof(n_time) +
822				    sizeof(struct in_addr) > ipt->ipt_len)
823					goto bad;
824				ipaddr.sin_addr = dst;
825				ia = (INA)ifaof_ifpforaddr((SA)&ipaddr,
826							    m->m_pkthdr.rcvif);
827				if (ia == 0)
828					continue;
829				bcopy((caddr_t)&IA_SIN(ia)->sin_addr,
830				    (caddr_t)sin, sizeof(struct in_addr));
831				ipt->ipt_ptr += sizeof(struct in_addr);
832				break;
833
834			case IPOPT_TS_PRESPEC:
835				if (ipt->ipt_ptr + sizeof(n_time) +
836				    sizeof(struct in_addr) > ipt->ipt_len)
837					goto bad;
838				bcopy((caddr_t)sin, (caddr_t)&ipaddr.sin_addr,
839				    sizeof(struct in_addr));
840				if (ifa_ifwithaddr((SA)&ipaddr) == 0)
841					continue;
842				ipt->ipt_ptr += sizeof(struct in_addr);
843				break;
844
845			default:
846				goto bad;
847			}
848			ntime = iptime();
849			bcopy((caddr_t)&ntime, (caddr_t)cp + ipt->ipt_ptr - 1,
850			    sizeof(n_time));
851			ipt->ipt_ptr += sizeof(n_time);
852		}
853	}
854	if (forward) {
855		ip_forward(m, 1);
856		return (1);
857	}
858	return (0);
859bad:
860	ip->ip_len -= ip->ip_hl << 2;   /* XXX icmp_error adds in hdr length */
861	icmp_error(m, type, code, 0, 0);
862	ipstat.ips_badoptions++;
863	return (1);
864}
865
866/*
867 * Given address of next destination (final or next hop),
868 * return internet address info of interface to be used to get there.
869 */
870struct in_ifaddr *
871ip_rtaddr(dst)
872	 struct in_addr dst;
873{
874	register struct sockaddr_in *sin;
875
876	sin = (struct sockaddr_in *) &ipforward_rt.ro_dst;
877
878	if (ipforward_rt.ro_rt == 0 || dst.s_addr != sin->sin_addr.s_addr) {
879		if (ipforward_rt.ro_rt) {
880			RTFREE(ipforward_rt.ro_rt);
881			ipforward_rt.ro_rt = 0;
882		}
883		sin->sin_family = AF_INET;
884		sin->sin_len = sizeof(*sin);
885		sin->sin_addr = dst;
886
887		rtalloc_ign(&ipforward_rt, RTF_PRCLONING);
888	}
889	if (ipforward_rt.ro_rt == 0)
890		return ((struct in_ifaddr *)0);
891	return ((struct in_ifaddr *) ipforward_rt.ro_rt->rt_ifa);
892}
893
894/*
895 * Save incoming source route for use in replies,
896 * to be picked up later by ip_srcroute if the receiver is interested.
897 */
898void
899save_rte(option, dst)
900	u_char *option;
901	struct in_addr dst;
902{
903	unsigned olen;
904
905	olen = option[IPOPT_OLEN];
906#ifdef DIAGNOSTIC
907	if (ipprintfs)
908		printf("save_rte: olen %d\n", olen);
909#endif
910	if (olen > sizeof(ip_srcrt) - (1 + sizeof(dst)))
911		return;
912	bcopy((caddr_t)option, (caddr_t)ip_srcrt.srcopt, olen);
913	ip_nhops = (olen - IPOPT_OFFSET - 1) / sizeof(struct in_addr);
914	ip_srcrt.dst = dst;
915}
916
917/*
918 * Retrieve incoming source route for use in replies,
919 * in the same form used by setsockopt.
920 * The first hop is placed before the options, will be removed later.
921 */
922struct mbuf *
923ip_srcroute()
924{
925	register struct in_addr *p, *q;
926	register struct mbuf *m;
927
928	if (ip_nhops == 0)
929		return ((struct mbuf *)0);
930	m = m_get(M_DONTWAIT, MT_SOOPTS);
931	if (m == 0)
932		return ((struct mbuf *)0);
933
934#define OPTSIZ	(sizeof(ip_srcrt.nop) + sizeof(ip_srcrt.srcopt))
935
936	/* length is (nhops+1)*sizeof(addr) + sizeof(nop + srcrt header) */
937	m->m_len = ip_nhops * sizeof(struct in_addr) + sizeof(struct in_addr) +
938	    OPTSIZ;
939#ifdef DIAGNOSTIC
940	if (ipprintfs)
941		printf("ip_srcroute: nhops %d mlen %d", ip_nhops, m->m_len);
942#endif
943
944	/*
945	 * First save first hop for return route
946	 */
947	p = &ip_srcrt.route[ip_nhops - 1];
948	*(mtod(m, struct in_addr *)) = *p--;
949#ifdef DIAGNOSTIC
950	if (ipprintfs)
951		printf(" hops %lx", ntohl(mtod(m, struct in_addr *)->s_addr));
952#endif
953
954	/*
955	 * Copy option fields and padding (nop) to mbuf.
956	 */
957	ip_srcrt.nop = IPOPT_NOP;
958	ip_srcrt.srcopt[IPOPT_OFFSET] = IPOPT_MINOFF;
959	bcopy((caddr_t)&ip_srcrt.nop,
960	    mtod(m, caddr_t) + sizeof(struct in_addr), OPTSIZ);
961	q = (struct in_addr *)(mtod(m, caddr_t) +
962	    sizeof(struct in_addr) + OPTSIZ);
963#undef OPTSIZ
964	/*
965	 * Record return path as an IP source route,
966	 * reversing the path (pointers are now aligned).
967	 */
968	while (p >= ip_srcrt.route) {
969#ifdef DIAGNOSTIC
970		if (ipprintfs)
971			printf(" %lx", ntohl(q->s_addr));
972#endif
973		*q++ = *p--;
974	}
975	/*
976	 * Last hop goes to final destination.
977	 */
978	*q = ip_srcrt.dst;
979#ifdef DIAGNOSTIC
980	if (ipprintfs)
981		printf(" %lx\n", ntohl(q->s_addr));
982#endif
983	return (m);
984}
985
986/*
987 * Strip out IP options, at higher
988 * level protocol in the kernel.
989 * Second argument is buffer to which options
990 * will be moved, and return value is their length.
991 * XXX should be deleted; last arg currently ignored.
992 */
993void
994ip_stripoptions(m, mopt)
995	register struct mbuf *m;
996	struct mbuf *mopt;
997{
998	register int i;
999	struct ip *ip = mtod(m, struct ip *);
1000	register caddr_t opts;
1001	int olen;
1002
1003	olen = (ip->ip_hl<<2) - sizeof (struct ip);
1004	opts = (caddr_t)(ip + 1);
1005	i = m->m_len - (sizeof (struct ip) + olen);
1006	bcopy(opts  + olen, opts, (unsigned)i);
1007	m->m_len -= olen;
1008	if (m->m_flags & M_PKTHDR)
1009		m->m_pkthdr.len -= olen;
1010	ip->ip_hl = sizeof(struct ip) >> 2;
1011}
1012
1013u_char inetctlerrmap[PRC_NCMDS] = {
1014	0,		0,		0,		0,
1015	0,		EMSGSIZE,	EHOSTDOWN,	EHOSTUNREACH,
1016	EHOSTUNREACH,	EHOSTUNREACH,	ECONNREFUSED,	ECONNREFUSED,
1017	EMSGSIZE,	EHOSTUNREACH,	0,		0,
1018	0,		0,		0,		0,
1019	ENOPROTOOPT
1020};
1021
1022/*
1023 * Forward a packet.  If some error occurs return the sender
1024 * an icmp packet.  Note we can't always generate a meaningful
1025 * icmp message because icmp doesn't have a large enough repertoire
1026 * of codes and types.
1027 *
1028 * If not forwarding, just drop the packet.  This could be confusing
1029 * if ipforwarding was zero but some routing protocol was advancing
1030 * us as a gateway to somewhere.  However, we must let the routing
1031 * protocol deal with that.
1032 *
1033 * The srcrt parameter indicates whether the packet is being forwarded
1034 * via a source route.
1035 */
1036void
1037ip_forward(m, srcrt)
1038	struct mbuf *m;
1039	int srcrt;
1040{
1041	register struct ip *ip = mtod(m, struct ip *);
1042	register struct sockaddr_in *sin;
1043	register struct rtentry *rt;
1044	int error, type = 0, code = 0;
1045	struct mbuf *mcopy;
1046	n_long dest;
1047	struct ifnet *destifp;
1048
1049	dest = 0;
1050#ifdef DIAGNOSTIC
1051	if (ipprintfs)
1052		printf("forward: src %lx dst %lx ttl %x\n",
1053			ip->ip_src.s_addr, ip->ip_dst.s_addr, ip->ip_ttl);
1054#endif
1055
1056
1057	if (m->m_flags & M_BCAST || in_canforward(ip->ip_dst) == 0) {
1058		ipstat.ips_cantforward++;
1059		m_freem(m);
1060		return;
1061	}
1062	HTONS(ip->ip_id);
1063	if (ip->ip_ttl <= IPTTLDEC) {
1064		icmp_error(m, ICMP_TIMXCEED, ICMP_TIMXCEED_INTRANS, dest, 0);
1065		return;
1066	}
1067	ip->ip_ttl -= IPTTLDEC;
1068
1069	sin = (struct sockaddr_in *)&ipforward_rt.ro_dst;
1070	if ((rt = ipforward_rt.ro_rt) == 0 ||
1071	    ip->ip_dst.s_addr != sin->sin_addr.s_addr) {
1072		if (ipforward_rt.ro_rt) {
1073			RTFREE(ipforward_rt.ro_rt);
1074			ipforward_rt.ro_rt = 0;
1075		}
1076		sin->sin_family = AF_INET;
1077		sin->sin_len = sizeof(*sin);
1078		sin->sin_addr = ip->ip_dst;
1079
1080		rtalloc_ign(&ipforward_rt, RTF_PRCLONING);
1081		if (ipforward_rt.ro_rt == 0) {
1082			icmp_error(m, ICMP_UNREACH, ICMP_UNREACH_HOST, dest, 0);
1083			return;
1084		}
1085		rt = ipforward_rt.ro_rt;
1086	}
1087
1088	/*
1089	 * Save at most 64 bytes of the packet in case
1090	 * we need to generate an ICMP message to the src.
1091	 */
1092	mcopy = m_copy(m, 0, imin((int)ip->ip_len, 64));
1093
1094#ifdef bogus
1095#ifdef GATEWAY
1096	ip_ifmatrix[rt->rt_ifp->if_index +
1097	     if_index * m->m_pkthdr.rcvif->if_index]++;
1098#endif
1099#endif
1100	/*
1101	 * If forwarding packet using same interface that it came in on,
1102	 * perhaps should send a redirect to sender to shortcut a hop.
1103	 * Only send redirect if source is sending directly to us,
1104	 * and if packet was not source routed (or has any options).
1105	 * Also, don't send redirect if forwarding using a default route
1106	 * or a route modified by a redirect.
1107	 */
1108#define	satosin(sa)	((struct sockaddr_in *)(sa))
1109	if (rt->rt_ifp == m->m_pkthdr.rcvif &&
1110	    (rt->rt_flags & (RTF_DYNAMIC|RTF_MODIFIED)) == 0 &&
1111	    satosin(rt_key(rt))->sin_addr.s_addr != 0 &&
1112	    ipsendredirects && !srcrt) {
1113#define	RTA(rt)	((struct in_ifaddr *)(rt->rt_ifa))
1114		u_long src = ntohl(ip->ip_src.s_addr);
1115
1116		if (RTA(rt) &&
1117		    (src & RTA(rt)->ia_subnetmask) == RTA(rt)->ia_subnet) {
1118		    if (rt->rt_flags & RTF_GATEWAY)
1119			dest = satosin(rt->rt_gateway)->sin_addr.s_addr;
1120		    else
1121			dest = ip->ip_dst.s_addr;
1122		    /* Router requirements says to only send host redirects */
1123		    type = ICMP_REDIRECT;
1124		    code = ICMP_REDIRECT_HOST;
1125#ifdef DIAGNOSTIC
1126		    if (ipprintfs)
1127		        printf("redirect (%d) to %lx\n", code, (u_long)dest);
1128#endif
1129		}
1130	}
1131
1132	error = ip_output(m, (struct mbuf *)0, &ipforward_rt, IP_FORWARDING
1133#ifdef DIRECTED_BROADCAST
1134			    | IP_ALLOWBROADCAST
1135#endif
1136						, 0);
1137	if (error)
1138		ipstat.ips_cantforward++;
1139	else {
1140		ipstat.ips_forward++;
1141		if (type)
1142			ipstat.ips_redirectsent++;
1143		else {
1144			if (mcopy)
1145				m_freem(mcopy);
1146			return;
1147		}
1148	}
1149	if (mcopy == NULL)
1150		return;
1151	destifp = NULL;
1152
1153	switch (error) {
1154
1155	case 0:				/* forwarded, but need redirect */
1156		/* type, code set above */
1157		break;
1158
1159	case ENETUNREACH:		/* shouldn't happen, checked above */
1160	case EHOSTUNREACH:
1161	case ENETDOWN:
1162	case EHOSTDOWN:
1163	default:
1164		type = ICMP_UNREACH;
1165		code = ICMP_UNREACH_HOST;
1166		break;
1167
1168	case EMSGSIZE:
1169		type = ICMP_UNREACH;
1170		code = ICMP_UNREACH_NEEDFRAG;
1171		if (ipforward_rt.ro_rt)
1172			destifp = ipforward_rt.ro_rt->rt_ifp;
1173		ipstat.ips_cantfrag++;
1174		break;
1175
1176	case ENOBUFS:
1177		type = ICMP_SOURCEQUENCH;
1178		code = 0;
1179		break;
1180	}
1181	icmp_error(mcopy, type, code, dest, destifp);
1182}
1183
1184int
1185ip_sysctl(name, namelen, oldp, oldlenp, newp, newlen)
1186	int *name;
1187	u_int namelen;
1188	void *oldp;
1189	size_t *oldlenp;
1190	void *newp;
1191	size_t newlen;
1192{
1193	/* All sysctl names at this level are terminal. */
1194	if (namelen != 1)
1195		return (ENOTDIR);
1196
1197	switch (name[0]) {
1198	case IPCTL_FORWARDING:
1199		return (sysctl_int(oldp, oldlenp, newp, newlen, &ipforwarding));
1200	case IPCTL_SENDREDIRECTS:
1201		return (sysctl_int(oldp, oldlenp, newp, newlen,
1202			&ipsendredirects));
1203	case IPCTL_DEFTTL:
1204		return (sysctl_int(oldp, oldlenp, newp, newlen, &ip_defttl));
1205#ifdef notyet
1206	case IPCTL_DEFMTU:
1207		return (sysctl_int(oldp, oldlenp, newp, newlen, &ip_mtu));
1208#endif
1209	case IPCTL_RTEXPIRE:
1210		return (sysctl_int(oldp, oldlenp, newp, newlen,
1211				   &rtq_reallyold));
1212	case IPCTL_RTMINEXPIRE:
1213		return (sysctl_int(oldp, oldlenp, newp, newlen,
1214				   &rtq_minreallyold));
1215	case IPCTL_RTMAXCACHE:
1216		return (sysctl_int(oldp, oldlenp, newp, newlen,
1217				   &rtq_toomany));
1218	default:
1219		return (EOPNOTSUPP);
1220	}
1221	/* NOTREACHED */
1222}
1223
1224int
1225ip_rsvp_init(struct socket *so)
1226{
1227	if (so->so_type != SOCK_RAW ||
1228	    so->so_proto->pr_protocol != IPPROTO_RSVP)
1229	  return EOPNOTSUPP;
1230
1231	if (ip_rsvpd != NULL)
1232	  return EADDRINUSE;
1233
1234	ip_rsvpd = so;
1235
1236	return 0;
1237}
1238
1239int
1240ip_rsvp_done(void)
1241{
1242	ip_rsvpd = NULL;
1243	return 0;
1244}
1245