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