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