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