ip_input.c revision 1.41
1/*	$NetBSD: ip_input.c,v 1.41 1996/10/25 06:30:32 thorpej 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#ifdef PFIL_HOOKS
442	m0 = m;
443	for (pfh = pfil_hook_get(PFIL_BAD); pfh; pfh = pfh->pfil_link.le_next)
444		if (pfh->pfil_func) {
445			(void)pfh->pfil_func(ip, hlen, m->m_pkthdr.rcvif, 2, &m0);
446			ip = mtod(m = m0, struct ip *);
447		}
448#endif /* PFIL_HOOKS */
449	m_freem(m);
450	goto next;
451}
452
453/*
454 * Take incoming datagram fragment and try to
455 * reassemble it into whole datagram.  If a chain for
456 * reassembly of this datagram already exists, then it
457 * is given as fp; otherwise have to make a chain.
458 */
459struct ip *
460ip_reass(ipqe, fp)
461	register struct ipqent *ipqe;
462	register struct ipq *fp;
463{
464	register struct mbuf *m = dtom(ipqe->ipqe_ip);
465	register struct ipqent *nq, *p, *q;
466	struct ip *ip;
467	struct mbuf *t;
468	int hlen = ipqe->ipqe_ip->ip_hl << 2;
469	int i, next;
470
471	/*
472	 * Presence of header sizes in mbufs
473	 * would confuse code below.
474	 */
475	m->m_data += hlen;
476	m->m_len -= hlen;
477
478	/*
479	 * If first fragment to arrive, create a reassembly queue.
480	 */
481	if (fp == 0) {
482		if ((t = m_get(M_DONTWAIT, MT_FTABLE)) == NULL)
483			goto dropfrag;
484		fp = mtod(t, struct ipq *);
485		LIST_INSERT_HEAD(&ipq, fp, ipq_q);
486		fp->ipq_ttl = IPFRAGTTL;
487		fp->ipq_p = ipqe->ipqe_ip->ip_p;
488		fp->ipq_id = ipqe->ipqe_ip->ip_id;
489		LIST_INIT(&fp->ipq_fragq);
490		fp->ipq_src = ipqe->ipqe_ip->ip_src;
491		fp->ipq_dst = ipqe->ipqe_ip->ip_dst;
492		p = NULL;
493		goto insert;
494	}
495
496	/*
497	 * Find a segment which begins after this one does.
498	 */
499	for (p = NULL, q = fp->ipq_fragq.lh_first; q != NULL;
500	    p = q, q = q->ipqe_q.le_next)
501		if (q->ipqe_ip->ip_off > ipqe->ipqe_ip->ip_off)
502			break;
503
504	/*
505	 * If there is a preceding segment, it may provide some of
506	 * our data already.  If so, drop the data from the incoming
507	 * segment.  If it provides all of our data, drop us.
508	 */
509	if (p != NULL) {
510		i = p->ipqe_ip->ip_off + p->ipqe_ip->ip_len -
511		    ipqe->ipqe_ip->ip_off;
512		if (i > 0) {
513			if (i >= ipqe->ipqe_ip->ip_len)
514				goto dropfrag;
515			m_adj(dtom(ipqe->ipqe_ip), i);
516			ipqe->ipqe_ip->ip_off += i;
517			ipqe->ipqe_ip->ip_len -= i;
518		}
519	}
520
521	/*
522	 * While we overlap succeeding segments trim them or,
523	 * if they are completely covered, dequeue them.
524	 */
525	for (; q != NULL && ipqe->ipqe_ip->ip_off + ipqe->ipqe_ip->ip_len >
526	    q->ipqe_ip->ip_off; q = nq) {
527		i = (ipqe->ipqe_ip->ip_off + ipqe->ipqe_ip->ip_len) -
528		    q->ipqe_ip->ip_off;
529		if (i < q->ipqe_ip->ip_len) {
530			q->ipqe_ip->ip_len -= i;
531			q->ipqe_ip->ip_off += i;
532			m_adj(dtom(q->ipqe_ip), i);
533			break;
534		}
535		nq = q->ipqe_q.le_next;
536		m_freem(dtom(q->ipqe_ip));
537		LIST_REMOVE(q, ipqe_q);
538		FREE(q, M_IPQ);
539	}
540
541insert:
542	/*
543	 * Stick new segment in its place;
544	 * check for complete reassembly.
545	 */
546	if (p == NULL) {
547		LIST_INSERT_HEAD(&fp->ipq_fragq, ipqe, ipqe_q);
548	} else {
549		LIST_INSERT_AFTER(p, ipqe, ipqe_q);
550	}
551	next = 0;
552	for (p = NULL, q = fp->ipq_fragq.lh_first; q != NULL;
553	    p = q, q = q->ipqe_q.le_next) {
554		if (q->ipqe_ip->ip_off != next)
555			return (0);
556		next += q->ipqe_ip->ip_len;
557	}
558	if (p->ipqe_mff)
559		return (0);
560
561	/*
562	 * Reassembly is complete.  Check for a bogus message size and
563	 * concatenate fragments.
564	 */
565	q = fp->ipq_fragq.lh_first;
566	ip = q->ipqe_ip;
567	if ((next + (ip->ip_hl << 2)) > IP_MAXPACKET) {
568		ipstat.ips_toolong++;
569		ip_freef(fp);
570		return (0);
571	}
572	m = dtom(q->ipqe_ip);
573	t = m->m_next;
574	m->m_next = 0;
575	m_cat(m, t);
576	nq = q->ipqe_q.le_next;
577	FREE(q, M_IPQ);
578	for (q = nq; q != NULL; q = nq) {
579		t = dtom(q->ipqe_ip);
580		nq = q->ipqe_q.le_next;
581		FREE(q, M_IPQ);
582		m_cat(m, t);
583	}
584
585	/*
586	 * Create header for new ip packet by
587	 * modifying header of first packet;
588	 * dequeue and discard fragment reassembly header.
589	 * Make header visible.
590	 */
591	ip->ip_len = next;
592	ip->ip_src = fp->ipq_src;
593	ip->ip_dst = fp->ipq_dst;
594	LIST_REMOVE(fp, ipq_q);
595	(void) m_free(dtom(fp));
596	m->m_len += (ip->ip_hl << 2);
597	m->m_data -= (ip->ip_hl << 2);
598	/* some debugging cruft by sklower, below, will go away soon */
599	if (m->m_flags & M_PKTHDR) { /* XXX this should be done elsewhere */
600		register int plen = 0;
601		for (t = m; m; m = m->m_next)
602			plen += m->m_len;
603		t->m_pkthdr.len = plen;
604	}
605	return (ip);
606
607dropfrag:
608	ipstat.ips_fragdropped++;
609	m_freem(m);
610	FREE(ipqe, M_IPQ);
611	return (0);
612}
613
614/*
615 * Free a fragment reassembly header and all
616 * associated datagrams.
617 */
618void
619ip_freef(fp)
620	struct ipq *fp;
621{
622	register struct ipqent *q, *p;
623
624	for (q = fp->ipq_fragq.lh_first; q != NULL; q = p) {
625		p = q->ipqe_q.le_next;
626		m_freem(dtom(q->ipqe_ip));
627		LIST_REMOVE(q, ipqe_q);
628		FREE(q, M_IPQ);
629	}
630	LIST_REMOVE(fp, ipq_q);
631	(void) m_free(dtom(fp));
632}
633
634/*
635 * IP timer processing;
636 * if a timer expires on a reassembly
637 * queue, discard it.
638 */
639void
640ip_slowtimo()
641{
642	register struct ipq *fp, *nfp;
643	int s = splsoftnet();
644
645	for (fp = ipq.lh_first; fp != NULL; fp = nfp) {
646		nfp = fp->ipq_q.le_next;
647		if (--fp->ipq_ttl == 0) {
648			ipstat.ips_fragtimeout++;
649			ip_freef(fp);
650		}
651	}
652	splx(s);
653}
654
655/*
656 * Drain off all datagram fragments.
657 */
658void
659ip_drain()
660{
661
662	while (ipq.lh_first != NULL) {
663		ipstat.ips_fragdropped++;
664		ip_freef(ipq.lh_first);
665	}
666}
667
668/*
669 * Do option processing on a datagram,
670 * possibly discarding it if bad options are encountered,
671 * or forwarding it if source-routed.
672 * Returns 1 if packet has been forwarded/freed,
673 * 0 if the packet should be processed further.
674 */
675int
676ip_dooptions(m)
677	struct mbuf *m;
678{
679	register struct ip *ip = mtod(m, struct ip *);
680	register u_char *cp;
681	register struct ip_timestamp *ipt;
682	register struct in_ifaddr *ia;
683	int opt, optlen, cnt, off, code, type = ICMP_PARAMPROB, forward = 0;
684	struct in_addr *sin, dst;
685	n_time ntime;
686
687	dst = ip->ip_dst;
688	cp = (u_char *)(ip + 1);
689	cnt = (ip->ip_hl << 2) - sizeof (struct ip);
690	for (; cnt > 0; cnt -= optlen, cp += optlen) {
691		opt = cp[IPOPT_OPTVAL];
692		if (opt == IPOPT_EOL)
693			break;
694		if (opt == IPOPT_NOP)
695			optlen = 1;
696		else {
697			optlen = cp[IPOPT_OLEN];
698			if (optlen <= 0 || optlen > cnt) {
699				code = &cp[IPOPT_OLEN] - (u_char *)ip;
700				goto bad;
701			}
702		}
703		switch (opt) {
704
705		default:
706			break;
707
708		/*
709		 * Source routing with record.
710		 * Find interface with current destination address.
711		 * If none on this machine then drop if strictly routed,
712		 * or do nothing if loosely routed.
713		 * Record interface address and bring up next address
714		 * component.  If strictly routed make sure next
715		 * address is on directly accessible net.
716		 */
717		case IPOPT_LSRR:
718		case IPOPT_SSRR:
719			if ((off = cp[IPOPT_OFFSET]) < IPOPT_MINOFF) {
720				code = &cp[IPOPT_OFFSET] - (u_char *)ip;
721				goto bad;
722			}
723			ipaddr.sin_addr = ip->ip_dst;
724			ia = ifatoia(ifa_ifwithaddr(sintosa(&ipaddr)));
725			if (ia == 0) {
726				if (opt == IPOPT_SSRR) {
727					type = ICMP_UNREACH;
728					code = ICMP_UNREACH_SRCFAIL;
729					goto bad;
730				}
731				/*
732				 * Loose routing, and not at next destination
733				 * yet; nothing to do except forward.
734				 */
735				break;
736			}
737			off--;			/* 0 origin */
738			if (off > optlen - sizeof(struct in_addr)) {
739				/*
740				 * End of source route.  Should be for us.
741				 */
742				save_rte(cp, ip->ip_src);
743				break;
744			}
745			/*
746			 * locate outgoing interface
747			 */
748			bcopy((caddr_t)(cp + off), (caddr_t)&ipaddr.sin_addr,
749			    sizeof(ipaddr.sin_addr));
750			if (opt == IPOPT_SSRR) {
751#define	INA	struct in_ifaddr *
752#define	SA	struct sockaddr *
753			    ia = (INA)ifa_ifwithladdr((SA)&ipaddr);
754			} else
755				ia = ip_rtaddr(ipaddr.sin_addr);
756			if (ia == 0) {
757				type = ICMP_UNREACH;
758				code = ICMP_UNREACH_SRCFAIL;
759				goto bad;
760			}
761			ip->ip_dst = ipaddr.sin_addr;
762			bcopy((caddr_t)&ia->ia_addr.sin_addr,
763			    (caddr_t)(cp + off), sizeof(struct in_addr));
764			cp[IPOPT_OFFSET] += sizeof(struct in_addr);
765			/*
766			 * Let ip_intr's mcast routing check handle mcast pkts
767			 */
768			forward = !IN_MULTICAST(ip->ip_dst.s_addr);
769			break;
770
771		case IPOPT_RR:
772			if ((off = cp[IPOPT_OFFSET]) < IPOPT_MINOFF) {
773				code = &cp[IPOPT_OFFSET] - (u_char *)ip;
774				goto bad;
775			}
776			/*
777			 * If no space remains, ignore.
778			 */
779			off--;			/* 0 origin */
780			if (off > optlen - sizeof(struct in_addr))
781				break;
782			bcopy((caddr_t)(&ip->ip_dst), (caddr_t)&ipaddr.sin_addr,
783			    sizeof(ipaddr.sin_addr));
784			/*
785			 * locate outgoing interface; if we're the destination,
786			 * use the incoming interface (should be same).
787			 */
788			if ((ia = (INA)ifa_ifwithaddr((SA)&ipaddr)) == 0 &&
789			    (ia = ip_rtaddr(ipaddr.sin_addr)) == 0) {
790				type = ICMP_UNREACH;
791				code = ICMP_UNREACH_HOST;
792				goto bad;
793			}
794			bcopy((caddr_t)&ia->ia_addr.sin_addr,
795			    (caddr_t)(cp + off), sizeof(struct in_addr));
796			cp[IPOPT_OFFSET] += sizeof(struct in_addr);
797			break;
798
799		case IPOPT_TS:
800			code = cp - (u_char *)ip;
801			ipt = (struct ip_timestamp *)cp;
802			if (ipt->ipt_len < 5)
803				goto bad;
804			if (ipt->ipt_ptr > ipt->ipt_len - sizeof (int32_t)) {
805				if (++ipt->ipt_oflw == 0)
806					goto bad;
807				break;
808			}
809			sin = (struct in_addr *)(cp + ipt->ipt_ptr - 1);
810			switch (ipt->ipt_flg) {
811
812			case IPOPT_TS_TSONLY:
813				break;
814
815			case IPOPT_TS_TSANDADDR:
816				if (ipt->ipt_ptr + sizeof(n_time) +
817				    sizeof(struct in_addr) > ipt->ipt_len)
818					goto bad;
819				ipaddr.sin_addr = dst;
820				ia = (INA)ifaof_ifpforaddr((SA)&ipaddr,
821							    m->m_pkthdr.rcvif);
822				if (ia == 0)
823					continue;
824				bcopy((caddr_t)&ia->ia_addr.sin_addr,
825				    (caddr_t)sin, sizeof(struct in_addr));
826				ipt->ipt_ptr += sizeof(struct in_addr);
827				break;
828
829			case IPOPT_TS_PRESPEC:
830				if (ipt->ipt_ptr + sizeof(n_time) +
831				    sizeof(struct in_addr) > ipt->ipt_len)
832					goto bad;
833				bcopy((caddr_t)sin, (caddr_t)&ipaddr.sin_addr,
834				    sizeof(struct in_addr));
835				if (ifa_ifwithaddr((SA)&ipaddr) == 0)
836					continue;
837				ipt->ipt_ptr += sizeof(struct in_addr);
838				break;
839
840			default:
841				goto bad;
842			}
843			ntime = iptime();
844			bcopy((caddr_t)&ntime, (caddr_t)cp + ipt->ipt_ptr - 1,
845			    sizeof(n_time));
846			ipt->ipt_ptr += sizeof(n_time);
847		}
848	}
849	if (forward) {
850		if (ip_forwsrcrt == 0) {
851			type = ICMP_UNREACH;
852			code = ICMP_UNREACH_SRCFAIL;
853			goto bad;
854		}
855		ip_forward(m, 1);
856		return (1);
857	}
858	return (0);
859bad:
860	ip->ip_len -= ip->ip_hl << 2;   /* XXX icmp_error adds in hdr length */
861	icmp_error(m, type, code, 0, 0);
862	ipstat.ips_badoptions++;
863	return (1);
864}
865
866/*
867 * Given address of next destination (final or next hop),
868 * return internet address info of interface to be used to get there.
869 */
870struct in_ifaddr *
871ip_rtaddr(dst)
872	 struct in_addr dst;
873{
874	register struct sockaddr_in *sin;
875
876	sin = satosin(&ipforward_rt.ro_dst);
877
878	if (ipforward_rt.ro_rt == 0 || !in_hosteq(dst, sin->sin_addr)) {
879		if (ipforward_rt.ro_rt) {
880			RTFREE(ipforward_rt.ro_rt);
881			ipforward_rt.ro_rt = 0;
882		}
883		sin->sin_family = AF_INET;
884		sin->sin_len = sizeof(*sin);
885		sin->sin_addr = dst;
886
887		rtalloc(&ipforward_rt);
888	}
889	if (ipforward_rt.ro_rt == 0)
890		return ((struct in_ifaddr *)0);
891	return (ifatoia(ipforward_rt.ro_rt->rt_ifa));
892}
893
894/*
895 * Save incoming source route for use in replies,
896 * to be picked up later by ip_srcroute if the receiver is interested.
897 */
898void
899save_rte(option, dst)
900	u_char *option;
901	struct in_addr dst;
902{
903	unsigned olen;
904
905	olen = option[IPOPT_OLEN];
906#ifdef DIAGNOSTIC
907	if (ipprintfs)
908		printf("save_rte: olen %d\n", olen);
909#endif
910	if (olen > sizeof(ip_srcrt) - (1 + sizeof(dst)))
911		return;
912	bcopy((caddr_t)option, (caddr_t)ip_srcrt.srcopt, olen);
913	ip_nhops = (olen - IPOPT_OFFSET - 1) / sizeof(struct in_addr);
914	ip_srcrt.dst = dst;
915}
916
917/*
918 * Retrieve incoming source route for use in replies,
919 * in the same form used by setsockopt.
920 * The first hop is placed before the options, will be removed later.
921 */
922struct mbuf *
923ip_srcroute()
924{
925	register struct in_addr *p, *q;
926	register struct mbuf *m;
927
928	if (ip_nhops == 0)
929		return ((struct mbuf *)0);
930	m = m_get(M_DONTWAIT, MT_SOOPTS);
931	if (m == 0)
932		return ((struct mbuf *)0);
933
934#define OPTSIZ	(sizeof(ip_srcrt.nop) + sizeof(ip_srcrt.srcopt))
935
936	/* length is (nhops+1)*sizeof(addr) + sizeof(nop + srcrt header) */
937	m->m_len = ip_nhops * sizeof(struct in_addr) + sizeof(struct in_addr) +
938	    OPTSIZ;
939#ifdef DIAGNOSTIC
940	if (ipprintfs)
941		printf("ip_srcroute: nhops %d mlen %d", ip_nhops, m->m_len);
942#endif
943
944	/*
945	 * First save first hop for return route
946	 */
947	p = &ip_srcrt.route[ip_nhops - 1];
948	*(mtod(m, struct in_addr *)) = *p--;
949#ifdef DIAGNOSTIC
950	if (ipprintfs)
951		printf(" hops %x", ntohl(mtod(m, struct in_addr *)->s_addr));
952#endif
953
954	/*
955	 * Copy option fields and padding (nop) to mbuf.
956	 */
957	ip_srcrt.nop = IPOPT_NOP;
958	ip_srcrt.srcopt[IPOPT_OFFSET] = IPOPT_MINOFF;
959	bcopy((caddr_t)&ip_srcrt.nop,
960	    mtod(m, caddr_t) + sizeof(struct in_addr), OPTSIZ);
961	q = (struct in_addr *)(mtod(m, caddr_t) +
962	    sizeof(struct in_addr) + OPTSIZ);
963#undef OPTSIZ
964	/*
965	 * Record return path as an IP source route,
966	 * reversing the path (pointers are now aligned).
967	 */
968	while (p >= ip_srcrt.route) {
969#ifdef DIAGNOSTIC
970		if (ipprintfs)
971			printf(" %x", ntohl(q->s_addr));
972#endif
973		*q++ = *p--;
974	}
975	/*
976	 * Last hop goes to final destination.
977	 */
978	*q = ip_srcrt.dst;
979#ifdef DIAGNOSTIC
980	if (ipprintfs)
981		printf(" %x\n", ntohl(q->s_addr));
982#endif
983	return (m);
984}
985
986/*
987 * Strip out IP options, at higher
988 * level protocol in the kernel.
989 * Second argument is buffer to which options
990 * will be moved, and return value is their length.
991 * XXX should be deleted; last arg currently ignored.
992 */
993void
994ip_stripoptions(m, mopt)
995	register struct mbuf *m;
996	struct mbuf *mopt;
997{
998	register int i;
999	struct ip *ip = mtod(m, struct ip *);
1000	register caddr_t opts;
1001	int olen;
1002
1003	olen = (ip->ip_hl<<2) - sizeof (struct ip);
1004	opts = (caddr_t)(ip + 1);
1005	i = m->m_len - (sizeof (struct ip) + olen);
1006	bcopy(opts  + olen, opts, (unsigned)i);
1007	m->m_len -= olen;
1008	if (m->m_flags & M_PKTHDR)
1009		m->m_pkthdr.len -= olen;
1010	ip->ip_hl = sizeof(struct ip) >> 2;
1011}
1012
1013int inetctlerrmap[PRC_NCMDS] = {
1014	0,		0,		0,		0,
1015	0,		EMSGSIZE,	EHOSTDOWN,	EHOSTUNREACH,
1016	EHOSTUNREACH,	EHOSTUNREACH,	ECONNREFUSED,	ECONNREFUSED,
1017	EMSGSIZE,	EHOSTUNREACH,	0,		0,
1018	0,		0,		0,		0,
1019	ENOPROTOOPT
1020};
1021
1022/*
1023 * Forward a packet.  If some error occurs return the sender
1024 * an icmp packet.  Note we can't always generate a meaningful
1025 * icmp message because icmp doesn't have a large enough repertoire
1026 * of codes and types.
1027 *
1028 * If not forwarding, just drop the packet.  This could be confusing
1029 * if ipforwarding was zero but some routing protocol was advancing
1030 * us as a gateway to somewhere.  However, we must let the routing
1031 * protocol deal with that.
1032 *
1033 * The srcrt parameter indicates whether the packet is being forwarded
1034 * via a source route.
1035 */
1036void
1037ip_forward(m, srcrt)
1038	struct mbuf *m;
1039	int srcrt;
1040{
1041	register struct ip *ip = mtod(m, struct ip *);
1042	register struct sockaddr_in *sin;
1043	register struct rtentry *rt;
1044	int error, type = 0, code = 0;
1045	struct mbuf *mcopy;
1046	n_long dest;
1047	struct ifnet *destifp;
1048
1049	dest = 0;
1050#ifdef DIAGNOSTIC
1051	if (ipprintfs)
1052		printf("forward: src %x dst %x ttl %x\n",
1053		    ip->ip_src.s_addr, ip->ip_dst.s_addr, ip->ip_ttl);
1054#endif
1055	if (m->m_flags & M_BCAST || in_canforward(ip->ip_dst) == 0) {
1056		ipstat.ips_cantforward++;
1057		m_freem(m);
1058		return;
1059	}
1060	HTONS(ip->ip_id);
1061	if (ip->ip_ttl <= IPTTLDEC) {
1062		icmp_error(m, ICMP_TIMXCEED, ICMP_TIMXCEED_INTRANS, dest, 0);
1063		return;
1064	}
1065	ip->ip_ttl -= IPTTLDEC;
1066
1067	sin = satosin(&ipforward_rt.ro_dst);
1068	if ((rt = ipforward_rt.ro_rt) == 0 ||
1069	    !in_hosteq(ip->ip_dst, sin->sin_addr)) {
1070		if (ipforward_rt.ro_rt) {
1071			RTFREE(ipforward_rt.ro_rt);
1072			ipforward_rt.ro_rt = 0;
1073		}
1074		sin->sin_family = AF_INET;
1075		sin->sin_len = sizeof(struct sockaddr_in);
1076		sin->sin_addr = ip->ip_dst;
1077
1078		rtalloc(&ipforward_rt);
1079		if (ipforward_rt.ro_rt == 0) {
1080			icmp_error(m, ICMP_UNREACH, ICMP_UNREACH_HOST, dest, 0);
1081			return;
1082		}
1083		rt = ipforward_rt.ro_rt;
1084	}
1085
1086	/*
1087	 * Save at most 68 bytes of the packet in case
1088	 * we need to generate an ICMP message to the src.
1089	 */
1090	mcopy = m_copy(m, 0, imin((int)ip->ip_len, 68));
1091
1092	/*
1093	 * If forwarding packet using same interface that it came in on,
1094	 * perhaps should send a redirect to sender to shortcut a hop.
1095	 * Only send redirect if source is sending directly to us,
1096	 * and if packet was not source routed (or has any options).
1097	 * Also, don't send redirect if forwarding using a default route
1098	 * or a route modified by a redirect.
1099	 */
1100	if (rt->rt_ifp == m->m_pkthdr.rcvif &&
1101	    (rt->rt_flags & (RTF_DYNAMIC|RTF_MODIFIED)) == 0 &&
1102	    !in_nullhost(satosin(rt_key(rt))->sin_addr) &&
1103	    ipsendredirects && !srcrt) {
1104		if (rt->rt_ifa &&
1105		    (ip->ip_src.s_addr & ifatoia(rt->rt_ifa)->ia_subnetmask) ==
1106		    ifatoia(rt->rt_ifa)->ia_subnet) {
1107		    if (rt->rt_flags & RTF_GATEWAY)
1108			dest = satosin(rt->rt_gateway)->sin_addr.s_addr;
1109		    else
1110			dest = ip->ip_dst.s_addr;
1111		    /* Router requirements says to only send host redirects */
1112		    type = ICMP_REDIRECT;
1113		    code = ICMP_REDIRECT_HOST;
1114#ifdef DIAGNOSTIC
1115		    if (ipprintfs)
1116		    	printf("redirect (%d) to %x\n", code, (u_int32_t)dest);
1117#endif
1118		}
1119	}
1120
1121	error = ip_output(m, (struct mbuf *)0, &ipforward_rt,
1122	    (IP_FORWARDING | (ip_directedbcast ? IP_ALLOWBROADCAST : 0)), 0);
1123	if (error)
1124		ipstat.ips_cantforward++;
1125	else {
1126		ipstat.ips_forward++;
1127		if (type)
1128			ipstat.ips_redirectsent++;
1129		else {
1130			if (mcopy)
1131				m_freem(mcopy);
1132			return;
1133		}
1134	}
1135	if (mcopy == NULL)
1136		return;
1137	destifp = NULL;
1138
1139	switch (error) {
1140
1141	case 0:				/* forwarded, but need redirect */
1142		/* type, code set above */
1143		break;
1144
1145	case ENETUNREACH:		/* shouldn't happen, checked above */
1146	case EHOSTUNREACH:
1147	case ENETDOWN:
1148	case EHOSTDOWN:
1149	default:
1150		type = ICMP_UNREACH;
1151		code = ICMP_UNREACH_HOST;
1152		break;
1153
1154	case EMSGSIZE:
1155		type = ICMP_UNREACH;
1156		code = ICMP_UNREACH_NEEDFRAG;
1157		if (ipforward_rt.ro_rt)
1158			destifp = ipforward_rt.ro_rt->rt_ifp;
1159		ipstat.ips_cantfrag++;
1160		break;
1161
1162	case ENOBUFS:
1163		type = ICMP_SOURCEQUENCH;
1164		code = 0;
1165		break;
1166	}
1167	icmp_error(mcopy, type, code, dest, destifp);
1168}
1169
1170int
1171ip_sysctl(name, namelen, oldp, oldlenp, newp, newlen)
1172	int *name;
1173	u_int namelen;
1174	void *oldp;
1175	size_t *oldlenp;
1176	void *newp;
1177	size_t newlen;
1178{
1179	/* All sysctl names at this level are terminal. */
1180	if (namelen != 1)
1181		return (ENOTDIR);
1182
1183	switch (name[0]) {
1184	case IPCTL_FORWARDING:
1185		return (sysctl_int(oldp, oldlenp, newp, newlen, &ipforwarding));
1186	case IPCTL_SENDREDIRECTS:
1187		return (sysctl_int(oldp, oldlenp, newp, newlen,
1188			&ipsendredirects));
1189	case IPCTL_DEFTTL:
1190		return (sysctl_int(oldp, oldlenp, newp, newlen, &ip_defttl));
1191#ifdef notyet
1192	case IPCTL_DEFMTU:
1193		return (sysctl_int(oldp, oldlenp, newp, newlen, &ip_mtu));
1194#endif
1195	case IPCTL_FORWSRCRT:
1196		/*
1197		 * Don't allow this to change in a secure environment.
1198		 */
1199		if (securelevel > 0)
1200			return (EPERM);
1201		return (sysctl_int(oldp, oldlenp, newp, newlen,
1202		    &ip_forwsrcrt));
1203	case IPCTL_DIRECTEDBCAST:
1204		return (sysctl_int(oldp, oldlenp, newp, newlen,
1205		    &ip_directedbcast));
1206	default:
1207		return (EOPNOTSUPP);
1208	}
1209	/* NOTREACHED */
1210}
1211