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