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