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