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