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