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