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