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