xref: /freebsd/sys/netinet/ip_input.c (revision 11afcc8f9f96d657b8e6f7547c02c1957331fc96)
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.96 1998/07/08 08:49:51 dg Exp $
35  *	$ANA: ip_input.c,v 1.5 1996/09/18 14:34:59 wollman Exp $
36  */
37 
38 #define	_IP_VHL
39 
40 #include "opt_bootp.h"
41 #include "opt_ipfw.h"
42 #include "opt_ipdivert.h"
43 #include "opt_ipfilter.h"
44 
45 #include <stddef.h>
46 
47 #include <sys/param.h>
48 #include <sys/systm.h>
49 #include <sys/mbuf.h>
50 #include <sys/domain.h>
51 #include <sys/protosw.h>
52 #include <sys/socket.h>
53 #include <sys/time.h>
54 #include <sys/kernel.h>
55 #include <sys/syslog.h>
56 #include <sys/sysctl.h>
57 
58 #include <net/if.h>
59 #include <net/if_var.h>
60 #include <net/if_dl.h>
61 #include <net/route.h>
62 #include <net/netisr.h>
63 
64 #include <netinet/in.h>
65 #include <netinet/in_systm.h>
66 #include <netinet/in_var.h>
67 #include <netinet/ip.h>
68 #include <netinet/in_pcb.h>
69 #include <netinet/ip_var.h>
70 #include <netinet/ip_icmp.h>
71 #include <machine/in_cksum.h>
72 
73 #include <sys/socketvar.h>
74 
75 #ifdef IPFIREWALL
76 #include <netinet/ip_fw.h>
77 #endif
78 
79 int rsvp_on = 0;
80 static int ip_rsvp_on;
81 struct socket *ip_rsvpd;
82 
83 int	ipforwarding = 0;
84 SYSCTL_INT(_net_inet_ip, IPCTL_FORWARDING, forwarding, CTLFLAG_RW,
85 	&ipforwarding, 0, "");
86 
87 static int	ipsendredirects = 1; /* XXX */
88 SYSCTL_INT(_net_inet_ip, IPCTL_SENDREDIRECTS, redirect, CTLFLAG_RW,
89 	&ipsendredirects, 0, "");
90 
91 int	ip_defttl = IPDEFTTL;
92 SYSCTL_INT(_net_inet_ip, IPCTL_DEFTTL, ttl, CTLFLAG_RW,
93 	&ip_defttl, 0, "");
94 
95 static int	ip_dosourceroute = 0;
96 SYSCTL_INT(_net_inet_ip, IPCTL_SOURCEROUTE, sourceroute, CTLFLAG_RW,
97 	&ip_dosourceroute, 0, "");
98 
99 static int	ip_acceptsourceroute = 0;
100 SYSCTL_INT(_net_inet_ip, IPCTL_ACCEPTSOURCEROUTE, accept_sourceroute,
101 	CTLFLAG_RW, &ip_acceptsourceroute, 0, "");
102 #ifdef DIAGNOSTIC
103 static int	ipprintfs = 0;
104 #endif
105 
106 extern	struct domain inetdomain;
107 extern	struct protosw inetsw[];
108 u_char	ip_protox[IPPROTO_MAX];
109 static int	ipqmaxlen = IFQ_MAXLEN;
110 struct	in_ifaddrhead in_ifaddrhead; /* first inet address */
111 struct	ifqueue ipintrq;
112 SYSCTL_INT(_net_inet_ip, IPCTL_INTRQMAXLEN, intr_queue_maxlen, CTLFLAG_RD,
113 	&ipintrq.ifq_maxlen, 0, "");
114 SYSCTL_INT(_net_inet_ip, IPCTL_INTRQDROPS, intr_queue_drops, CTLFLAG_RD,
115 	&ipintrq.ifq_drops, 0, "");
116 
117 struct ipstat ipstat;
118 SYSCTL_STRUCT(_net_inet_ip, IPCTL_STATS, stats, CTLFLAG_RD,
119 	&ipstat, ipstat, "");
120 
121 /* Packet reassembly stuff */
122 #define IPREASS_NHASH_LOG2      6
123 #define IPREASS_NHASH           (1 << IPREASS_NHASH_LOG2)
124 #define IPREASS_HMASK           (IPREASS_NHASH - 1)
125 #define IPREASS_HASH(x,y) \
126 	((((x) & 0xF | ((((x) >> 8) & 0xF) << 4)) ^ (y)) & IPREASS_HMASK)
127 
128 static struct ipq ipq[IPREASS_NHASH];
129 static int    nipq = 0;         /* total # of reass queues */
130 static int    maxnipq;
131 
132 #ifdef IPCTL_DEFMTU
133 SYSCTL_INT(_net_inet_ip, IPCTL_DEFMTU, mtu, CTLFLAG_RW,
134 	&ip_mtu, 0, "");
135 #endif
136 
137 #if !defined(COMPAT_IPFW) || COMPAT_IPFW == 1
138 #undef COMPAT_IPFW
139 #define COMPAT_IPFW 1
140 #else
141 #undef COMPAT_IPFW
142 #endif
143 
144 #ifdef COMPAT_IPFW
145 /* Firewall hooks */
146 ip_fw_chk_t *ip_fw_chk_ptr;
147 ip_fw_ctl_t *ip_fw_ctl_ptr;
148 
149 /* IP Network Address Translation (NAT) hooks */
150 ip_nat_t *ip_nat_ptr;
151 ip_nat_ctl_t *ip_nat_ctl_ptr;
152 #endif
153 
154 #if defined(IPFILTER_LKM) || defined(IPFILTER)
155 int iplattach __P((void));
156 int (*fr_checkp) __P((struct ip *, int, struct ifnet *, int, struct mbuf **)) = NULL;
157 #endif
158 
159 
160 /*
161  * We need to save the IP options in case a protocol wants to respond
162  * to an incoming packet over the same route if the packet got here
163  * using IP source routing.  This allows connection establishment and
164  * maintenance when the remote end is on a network that is not known
165  * to us.
166  */
167 static int	ip_nhops = 0;
168 static	struct ip_srcrt {
169 	struct	in_addr dst;			/* final destination */
170 	char	nop;				/* one NOP to align */
171 	char	srcopt[IPOPT_OFFSET + 1];	/* OPTVAL, OLEN and OFFSET */
172 	struct	in_addr route[MAX_IPOPTLEN/sizeof(struct in_addr)];
173 } ip_srcrt;
174 
175 #ifdef IPDIVERT
176 /*
177  * Shared variable between ip_input() and ip_reass() to communicate
178  * about which packets, once assembled from fragments, get diverted,
179  * and to which port.
180  */
181 static u_short	frag_divert_port;
182 #endif
183 
184 struct sockaddr_in *ip_fw_fwd_addr;
185 
186 static void save_rte __P((u_char *, struct in_addr));
187 static void	 ip_deq __P((struct ipasfrag *));
188 static int	 ip_dooptions __P((struct mbuf *));
189 static void	 ip_enq __P((struct ipasfrag *, struct ipasfrag *));
190 static void	 ip_forward __P((struct mbuf *, int));
191 static void	 ip_freef __P((struct ipq *));
192 static struct ip *
193 	 ip_reass __P((struct ipasfrag *, struct ipq *, struct ipq *));
194 static struct in_ifaddr *
195 	 ip_rtaddr __P((struct in_addr));
196 static void	ipintr __P((void));
197 /*
198  * IP initialization: fill in IP protocol switch table.
199  * All protocols not implemented in kernel go to raw IP protocol handler.
200  */
201 void
202 ip_init()
203 {
204 	register struct protosw *pr;
205 	register int i;
206 
207 	TAILQ_INIT(&in_ifaddrhead);
208 	pr = pffindproto(PF_INET, IPPROTO_RAW, SOCK_RAW);
209 	if (pr == 0)
210 		panic("ip_init");
211 	for (i = 0; i < IPPROTO_MAX; i++)
212 		ip_protox[i] = pr - inetsw;
213 	for (pr = inetdomain.dom_protosw;
214 	    pr < inetdomain.dom_protoswNPROTOSW; pr++)
215 		if (pr->pr_domain->dom_family == PF_INET &&
216 		    pr->pr_protocol && pr->pr_protocol != IPPROTO_RAW)
217 			ip_protox[pr->pr_protocol] = pr - inetsw;
218 
219 	for (i = 0; i < IPREASS_NHASH; i++)
220 	    ipq[i].next = ipq[i].prev = &ipq[i];
221 
222 	maxnipq = nmbclusters/4;
223 
224 	ip_id = time_second & 0xffff;
225 	ipintrq.ifq_maxlen = ipqmaxlen;
226 #ifdef IPFIREWALL
227 	ip_fw_init();
228 #endif
229 #ifdef IPNAT
230         ip_nat_init();
231 #endif
232 #ifdef IPFILTER
233         iplattach();
234 #endif
235 
236 }
237 
238 static struct	sockaddr_in ipaddr = { sizeof(ipaddr), AF_INET };
239 static struct	route ipforward_rt;
240 
241 /*
242  * Ip input routine.  Checksum and byte swap header.  If fragmented
243  * try to reassemble.  Process options.  Pass to next level.
244  */
245 void
246 ip_input(struct mbuf *m)
247 {
248 	struct ip *ip;
249 	struct ipq *fp;
250 	struct in_ifaddr *ia;
251 	int    i, hlen;
252 	u_short sum;
253 
254 #ifdef	DIAGNOSTIC
255 	if (m == NULL || (m->m_flags & M_PKTHDR) == 0)
256 		panic("ip_input no HDR");
257 #endif
258 	/*
259 	 * If no IP addresses have been set yet but the interfaces
260 	 * are receiving, can't do anything with incoming packets yet.
261 	 * XXX This is broken! We should be able to receive broadcasts
262 	 * and multicasts even without any local addresses configured.
263 	 */
264 	if (TAILQ_EMPTY(&in_ifaddrhead))
265 		goto bad;
266 	ipstat.ips_total++;
267 
268 	if (m->m_pkthdr.len < sizeof(struct ip))
269 		goto tooshort;
270 
271 	if (m->m_len < sizeof (struct ip) &&
272 	    (m = m_pullup(m, sizeof (struct ip))) == 0) {
273 		ipstat.ips_toosmall++;
274 		return;
275 	}
276 	ip = mtod(m, struct ip *);
277 
278 	if (IP_VHL_V(ip->ip_vhl) != IPVERSION) {
279 		ipstat.ips_badvers++;
280 		goto bad;
281 	}
282 
283 	hlen = IP_VHL_HL(ip->ip_vhl) << 2;
284 	if (hlen < sizeof(struct ip)) {	/* minimum header length */
285 		ipstat.ips_badhlen++;
286 		goto bad;
287 	}
288 	if (hlen > m->m_len) {
289 		if ((m = m_pullup(m, hlen)) == 0) {
290 			ipstat.ips_badhlen++;
291 			return;
292 		}
293 		ip = mtod(m, struct ip *);
294 	}
295 	if (hlen == sizeof(struct ip)) {
296 		sum = in_cksum_hdr(ip);
297 	} else {
298 		sum = in_cksum(m, hlen);
299 	}
300 	if (sum) {
301 		ipstat.ips_badsum++;
302 		goto bad;
303 	}
304 
305 	/*
306 	 * Convert fields to host representation.
307 	 */
308 	NTOHS(ip->ip_len);
309 	if (ip->ip_len < hlen) {
310 		ipstat.ips_badlen++;
311 		goto bad;
312 	}
313 	NTOHS(ip->ip_id);
314 	NTOHS(ip->ip_off);
315 
316 	/*
317 	 * Check that the amount of data in the buffers
318 	 * is as at least much as the IP header would have us expect.
319 	 * Trim mbufs if longer than we expect.
320 	 * Drop packet if shorter than we expect.
321 	 */
322 	if (m->m_pkthdr.len < ip->ip_len) {
323 tooshort:
324 		ipstat.ips_tooshort++;
325 		goto bad;
326 	}
327 	if (m->m_pkthdr.len > ip->ip_len) {
328 		if (m->m_len == m->m_pkthdr.len) {
329 			m->m_len = ip->ip_len;
330 			m->m_pkthdr.len = ip->ip_len;
331 		} else
332 			m_adj(m, ip->ip_len - m->m_pkthdr.len);
333 	}
334 	/*
335 	 * IpHack's section.
336 	 * Right now when no processing on packet has done
337 	 * and it is still fresh out of network we do our black
338 	 * deals with it.
339 	 * - Firewall: deny/allow/divert
340 	 * - Xlate: translate packet's addr/port (NAT).
341 	 * - Wrap: fake packet's addr/port <unimpl.>
342 	 * - Encapsulate: put it in another IP and send out. <unimp.>
343  	 */
344 #if defined(IPFILTER) || defined(IPFILTER_LKM)
345 	/*
346 	 * Check if we want to allow this packet to be processed.
347 	 * Consider it to be bad if not.
348 	 */
349 	if (fr_checkp) {
350 		struct	mbuf	*m1 = m;
351 
352 		if ((*fr_checkp)(ip, hlen, m->m_pkthdr.rcvif, 0, &m1) || !m1)
353 			return;
354 		ip = mtod(m = m1, struct ip *);
355 	}
356 #endif
357 #ifdef COMPAT_IPFW
358 	if (ip_fw_chk_ptr) {
359 		u_int16_t	port;
360 
361 #ifdef IPFIREWALL_FORWARD
362 		/*
363 		 * If we've been forwarded from the output side, then
364 		 * skip the firewall a second time
365 		 */
366 		if (ip_fw_fwd_addr)
367 			goto ours;
368 #endif	/* IPFIREWALL_FORWARD */
369 #ifdef IPDIVERT
370 		port = (*ip_fw_chk_ptr)(&ip, hlen, NULL, &ip_divert_cookie,
371 					&m, &ip_fw_fwd_addr);
372 		if (port) {
373 			/* Divert packet */
374 			frag_divert_port = port;
375 			goto ours;
376 		}
377 #else	/* !DIVERT */
378 		/*
379 		 * If ipfw says divert, we have to just drop packet
380 		 *  Use port as a dummy argument.
381 		 */
382 		port = 0;
383 		if ((*ip_fw_chk_ptr)(&ip, hlen, NULL, &port,
384 					&m, &ip_fw_fwd_addr)) {
385 			m_freem(m);
386 			m = NULL;
387 		}
388 #endif	/* !DIVERT */
389 		if (!m)
390 			return;
391 	}
392 
393         if (ip_nat_ptr && !(*ip_nat_ptr)(&ip, &m, m->m_pkthdr.rcvif, IP_NAT_IN))
394 		return;
395 #endif	/* !COMPAT_IPFW */
396 
397 	/*
398 	 * Process options and, if not destined for us,
399 	 * ship it on.  ip_dooptions returns 1 when an
400 	 * error was detected (causing an icmp message
401 	 * to be sent and the original packet to be freed).
402 	 */
403 	ip_nhops = 0;		/* for source routed packets */
404 	if (hlen > sizeof (struct ip) && ip_dooptions(m))
405 		return;
406 
407         /* greedy RSVP, snatches any PATH packet of the RSVP protocol and no
408          * matter if it is destined to another node, or whether it is
409          * a multicast one, RSVP wants it! and prevents it from being forwarded
410          * anywhere else. Also checks if the rsvp daemon is running before
411 	 * grabbing the packet.
412          */
413 	if (rsvp_on && ip->ip_p==IPPROTO_RSVP)
414 		goto ours;
415 
416 	/*
417 	 * Check our list of addresses, to see if the packet is for us.
418 	 */
419 	for (ia = TAILQ_FIRST(&in_ifaddrhead); ia;
420 					ia = TAILQ_NEXT(ia, ia_link)) {
421 #define	satosin(sa)	((struct sockaddr_in *)(sa))
422 
423 		if (IA_SIN(ia)->sin_addr.s_addr == ip->ip_dst.s_addr)
424 			goto ours;
425 #ifdef BOOTP_COMPAT
426 		if (IA_SIN(ia)->sin_addr.s_addr == INADDR_ANY)
427 			goto ours;
428 #endif
429 #ifdef IPFIREWALL_FORWARD
430 		/*
431 		 * If the addr to forward to is one of ours, we pretend to
432 		 * be the destination for this packet.
433 		 */
434 		if (ip_fw_fwd_addr != NULL &&
435 			IA_SIN(ia)->sin_addr.s_addr ==
436 					 ip_fw_fwd_addr->sin_addr.s_addr)
437 			goto ours;
438 #endif
439 		if (ia->ia_ifp && ia->ia_ifp->if_flags & IFF_BROADCAST) {
440 			if (satosin(&ia->ia_broadaddr)->sin_addr.s_addr ==
441 			    ip->ip_dst.s_addr)
442 				goto ours;
443 			if (ip->ip_dst.s_addr == ia->ia_netbroadcast.s_addr)
444 				goto ours;
445 		}
446 	}
447 	if (IN_MULTICAST(ntohl(ip->ip_dst.s_addr))) {
448 		struct in_multi *inm;
449 		if (ip_mrouter) {
450 			/*
451 			 * If we are acting as a multicast router, all
452 			 * incoming multicast packets are passed to the
453 			 * kernel-level multicast forwarding function.
454 			 * The packet is returned (relatively) intact; if
455 			 * ip_mforward() returns a non-zero value, the packet
456 			 * must be discarded, else it may be accepted below.
457 			 *
458 			 * (The IP ident field is put in the same byte order
459 			 * as expected when ip_mforward() is called from
460 			 * ip_output().)
461 			 */
462 			ip->ip_id = htons(ip->ip_id);
463 			if (ip_mforward(ip, m->m_pkthdr.rcvif, m, 0) != 0) {
464 				ipstat.ips_cantforward++;
465 				m_freem(m);
466 				return;
467 			}
468 			ip->ip_id = ntohs(ip->ip_id);
469 
470 			/*
471 			 * The process-level routing demon needs to receive
472 			 * all multicast IGMP packets, whether or not this
473 			 * host belongs to their destination groups.
474 			 */
475 			if (ip->ip_p == IPPROTO_IGMP)
476 				goto ours;
477 			ipstat.ips_forward++;
478 		}
479 		/*
480 		 * See if we belong to the destination multicast group on the
481 		 * arrival interface.
482 		 */
483 		IN_LOOKUP_MULTI(ip->ip_dst, m->m_pkthdr.rcvif, inm);
484 		if (inm == NULL) {
485 			ipstat.ips_notmember++;
486 			m_freem(m);
487 			return;
488 		}
489 		goto ours;
490 	}
491 	if (ip->ip_dst.s_addr == (u_long)INADDR_BROADCAST)
492 		goto ours;
493 	if (ip->ip_dst.s_addr == INADDR_ANY)
494 		goto ours;
495 
496 	/*
497 	 * Not for us; forward if possible and desirable.
498 	 */
499 	if (ipforwarding == 0) {
500 		ipstat.ips_cantforward++;
501 		m_freem(m);
502 	} else
503 		ip_forward(m, 0);
504 	return;
505 
506 ours:
507 
508 	/*
509 	 * If offset or IP_MF are set, must reassemble.
510 	 * Otherwise, nothing need be done.
511 	 * (We could look in the reassembly queue to see
512 	 * if the packet was previously fragmented,
513 	 * but it's not worth the time; just let them time out.)
514 	 */
515 	if (ip->ip_off & (IP_MF | IP_OFFMASK | IP_RF)) {
516 		if (m->m_flags & M_EXT) {		/* XXX */
517 			if ((m = m_pullup(m, sizeof (struct ip))) == 0) {
518 				ipstat.ips_toosmall++;
519 #ifdef IPDIVERT
520 				frag_divert_port = 0;
521 				ip_divert_cookie = 0;
522 #endif
523 				return;
524 			}
525 			ip = mtod(m, struct ip *);
526 		}
527 		sum = IPREASS_HASH(ip->ip_src.s_addr, ip->ip_id);
528 		/*
529 		 * Look for queue of fragments
530 		 * of this datagram.
531 		 */
532 		for (fp = ipq[sum].next; fp != &ipq[sum]; fp = fp->next)
533 			if (ip->ip_id == fp->ipq_id &&
534 			    ip->ip_src.s_addr == fp->ipq_src.s_addr &&
535 			    ip->ip_dst.s_addr == fp->ipq_dst.s_addr &&
536 			    ip->ip_p == fp->ipq_p)
537 				goto found;
538 
539 		fp = 0;
540 
541 		/* check if there's a place for the new queue */
542 		if (nipq > maxnipq) {
543 		    /*
544 		     * drop something from the tail of the current queue
545 		     * before proceeding further
546 		     */
547 		    if (ipq[sum].prev == &ipq[sum]) {   /* gak */
548 			for (i = 0; i < IPREASS_NHASH; i++) {
549 			    if (ipq[i].prev != &ipq[i]) {
550 				ip_freef(ipq[i].prev);
551 				break;
552 			    }
553 			}
554 		    } else
555 			ip_freef(ipq[sum].prev);
556 		}
557 found:
558 		/*
559 		 * Adjust ip_len to not reflect header,
560 		 * set ip_mff if more fragments are expected,
561 		 * convert offset of this to bytes.
562 		 */
563 		ip->ip_len -= hlen;
564 		((struct ipasfrag *)ip)->ipf_mff &= ~1;
565 		if (ip->ip_off & IP_MF)
566 			((struct ipasfrag *)ip)->ipf_mff |= 1;
567 		ip->ip_off <<= 3;
568 
569 		/*
570 		 * If datagram marked as having more fragments
571 		 * or if this is not the first fragment,
572 		 * attempt reassembly; if it succeeds, proceed.
573 		 */
574 		if (((struct ipasfrag *)ip)->ipf_mff & 1 || ip->ip_off) {
575 			ipstat.ips_fragments++;
576 			ip = ip_reass((struct ipasfrag *)ip, fp, &ipq[sum]);
577 			if (ip == 0) {
578 #ifdef	IPFIREWALL_FORWARD
579 				ip_fw_fwd_addr = NULL;
580 #endif
581 				return;
582 			}
583 			/* Get the length of the reassembled packets header */
584 			hlen = IP_VHL_HL(ip->ip_vhl) << 2;
585 			ipstat.ips_reassembled++;
586 			m = dtom(ip);
587 #ifdef IPDIVERT
588 			if (frag_divert_port) {
589 				ip->ip_len += hlen;
590 				HTONS(ip->ip_len);
591 				HTONS(ip->ip_off);
592 				HTONS(ip->ip_id);
593 				ip->ip_sum = 0;
594 				ip->ip_sum = in_cksum_hdr(ip);
595 				NTOHS(ip->ip_id);
596 				NTOHS(ip->ip_off);
597 				NTOHS(ip->ip_len);
598 				ip->ip_len -= hlen;
599 			}
600 #endif
601 		} else
602 			if (fp)
603 				ip_freef(fp);
604 	} else
605 		ip->ip_len -= hlen;
606 
607 #ifdef IPDIVERT
608 	/*
609 	 * Divert reassembled packets to the divert protocol if required
610 	 *  If divert port is null then cookie should be too,
611 	 * so we shouldn't need to clear them here. Assume ip_divert does so.
612 	 */
613 	if (frag_divert_port) {
614 		ipstat.ips_delivered++;
615 		ip_divert_port = frag_divert_port;
616 		frag_divert_port = 0;
617 		(*inetsw[ip_protox[IPPROTO_DIVERT]].pr_input)(m, hlen);
618 		return;
619 	}
620 
621 	/* Don't let packets divert themselves */
622 	if (ip->ip_p == IPPROTO_DIVERT) {
623 		ipstat.ips_noproto++;
624 		goto bad;
625 	}
626 
627 #endif
628 
629 	/*
630 	 * Switch out to protocol's input routine.
631 	 */
632 	ipstat.ips_delivered++;
633 	(*inetsw[ip_protox[ip->ip_p]].pr_input)(m, hlen);
634 #ifdef	IPFIREWALL_FORWARD
635 	ip_fw_fwd_addr = NULL;	/* tcp needed it */
636 #endif
637 	return;
638 bad:
639 #ifdef	IPFIREWALL_FORWARD
640 	ip_fw_fwd_addr = NULL;
641 #endif
642 	m_freem(m);
643 }
644 
645 /*
646  * IP software interrupt routine - to go away sometime soon
647  */
648 static void
649 ipintr(void)
650 {
651 	int s;
652 	struct mbuf *m;
653 
654 	while(1) {
655 		s = splimp();
656 		IF_DEQUEUE(&ipintrq, m);
657 		splx(s);
658 		if (m == 0)
659 			return;
660 		ip_input(m);
661 	}
662 }
663 
664 NETISR_SET(NETISR_IP, ipintr);
665 
666 /*
667  * Take incoming datagram fragment and try to
668  * reassemble it into whole datagram.  If a chain for
669  * reassembly of this datagram already exists, then it
670  * is given as fp; otherwise have to make a chain.
671  */
672 static struct ip *
673 ip_reass(ip, fp, where)
674 	register struct ipasfrag *ip;
675 	register struct ipq *fp;
676 	struct   ipq    *where;
677 {
678 	register struct mbuf *m = dtom(ip);
679 	register struct ipasfrag *q;
680 	struct mbuf *t;
681 	int hlen = ip->ip_hl << 2;
682 	int i, next;
683 
684 	/*
685 	 * Presence of header sizes in mbufs
686 	 * would confuse code below.
687 	 */
688 	m->m_data += hlen;
689 	m->m_len -= hlen;
690 
691 	/*
692 	 * If first fragment to arrive, create a reassembly queue.
693 	 */
694 	if (fp == 0) {
695 		if ((t = m_get(M_DONTWAIT, MT_FTABLE)) == NULL)
696 			goto dropfrag;
697 		fp = mtod(t, struct ipq *);
698 		insque(fp, where);
699 		nipq++;
700 		fp->ipq_ttl = IPFRAGTTL;
701 		fp->ipq_p = ip->ip_p;
702 		fp->ipq_id = ip->ip_id;
703 		fp->ipq_next = fp->ipq_prev = (struct ipasfrag *)fp;
704 		fp->ipq_src = ((struct ip *)ip)->ip_src;
705 		fp->ipq_dst = ((struct ip *)ip)->ip_dst;
706 #ifdef IPDIVERT
707 		fp->ipq_divert = 0;
708 		fp->ipq_div_cookie = 0;
709 #endif
710 		q = (struct ipasfrag *)fp;
711 		goto insert;
712 	}
713 
714 	/*
715 	 * Find a segment which begins after this one does.
716 	 */
717 	for (q = fp->ipq_next; q != (struct ipasfrag *)fp; q = q->ipf_next)
718 		if (q->ip_off > ip->ip_off)
719 			break;
720 
721 	/*
722 	 * If there is a preceding segment, it may provide some of
723 	 * our data already.  If so, drop the data from the incoming
724 	 * segment.  If it provides all of our data, drop us.
725 	 */
726 	if (q->ipf_prev != (struct ipasfrag *)fp) {
727 		i = q->ipf_prev->ip_off + q->ipf_prev->ip_len - ip->ip_off;
728 		if (i > 0) {
729 			if (i >= ip->ip_len)
730 				goto dropfrag;
731 			m_adj(dtom(ip), i);
732 			ip->ip_off += i;
733 			ip->ip_len -= i;
734 		}
735 	}
736 
737 	/*
738 	 * While we overlap succeeding segments trim them or,
739 	 * if they are completely covered, dequeue them.
740 	 */
741 	while (q != (struct ipasfrag *)fp &&
742 	    ip->ip_off + ip->ip_len > q->ip_off) {
743 		struct mbuf *m0;
744 
745 		i = (ip->ip_off + ip->ip_len) - q->ip_off;
746 		if (i < q->ip_len) {
747 			q->ip_len -= i;
748 			q->ip_off += i;
749 			m_adj(dtom(q), i);
750 			break;
751 		}
752 		m0 = dtom(q);
753 		q = q->ipf_next;
754 		ip_deq(q->ipf_prev);
755 		m_freem(m0);
756 	}
757 
758 insert:
759 
760 #ifdef IPDIVERT
761 	/*
762 	 * Any fragment diverting causes the whole packet to divert
763 	 */
764 	if (frag_divert_port) {
765 		fp->ipq_divert = frag_divert_port;
766 		fp->ipq_div_cookie = ip_divert_cookie;
767 	}
768 	frag_divert_port = 0;
769 	ip_divert_cookie = 0;
770 #endif
771 
772 	/*
773 	 * Stick new segment in its place;
774 	 * check for complete reassembly.
775 	 */
776 	ip_enq(ip, q->ipf_prev);
777 	next = 0;
778 	for (q = fp->ipq_next; q != (struct ipasfrag *)fp; q = q->ipf_next) {
779 		if (q->ip_off != next)
780 			return (0);
781 		next += q->ip_len;
782 	}
783 	if (q->ipf_prev->ipf_mff & 1)
784 		return (0);
785 
786 	/*
787 	 * Reassembly is complete.  Make sure the packet is a sane size.
788 	 */
789 	if (next + (IP_VHL_HL(((struct ip *)fp->ipq_next)->ip_vhl) << 2)
790 							> IP_MAXPACKET) {
791 		ipstat.ips_toolong++;
792 		ip_freef(fp);
793 		return (0);
794 	}
795 
796 	/*
797 	 * Concatenate fragments.
798 	 */
799 	q = fp->ipq_next;
800 	m = dtom(q);
801 	t = m->m_next;
802 	m->m_next = 0;
803 	m_cat(m, t);
804 	q = q->ipf_next;
805 	while (q != (struct ipasfrag *)fp) {
806 		t = dtom(q);
807 		q = q->ipf_next;
808 		m_cat(m, t);
809 	}
810 
811 #ifdef IPDIVERT
812 	/*
813 	 * extract divert port for packet, if any
814 	 */
815 	frag_divert_port = fp->ipq_divert;
816 	ip_divert_cookie = fp->ipq_div_cookie;
817 #endif
818 
819 	/*
820 	 * Create header for new ip packet by
821 	 * modifying header of first packet;
822 	 * dequeue and discard fragment reassembly header.
823 	 * Make header visible.
824 	 */
825 	ip = fp->ipq_next;
826 	ip->ip_len = next;
827 	ip->ipf_mff &= ~1;
828 	((struct ip *)ip)->ip_src = fp->ipq_src;
829 	((struct ip *)ip)->ip_dst = fp->ipq_dst;
830 	remque(fp);
831 	nipq--;
832 	(void) m_free(dtom(fp));
833 	m = dtom(ip);
834 	m->m_len += (ip->ip_hl << 2);
835 	m->m_data -= (ip->ip_hl << 2);
836 	/* some debugging cruft by sklower, below, will go away soon */
837 	if (m->m_flags & M_PKTHDR) { /* XXX this should be done elsewhere */
838 		register int plen = 0;
839 		for (t = m; m; m = m->m_next)
840 			plen += m->m_len;
841 		t->m_pkthdr.len = plen;
842 	}
843 	return ((struct ip *)ip);
844 
845 dropfrag:
846 #ifdef IPDIVERT
847 	frag_divert_port = 0;
848 	ip_divert_cookie = 0;
849 #endif
850 	ipstat.ips_fragdropped++;
851 	m_freem(m);
852 	return (0);
853 }
854 
855 /*
856  * Free a fragment reassembly header and all
857  * associated datagrams.
858  */
859 static void
860 ip_freef(fp)
861 	struct ipq *fp;
862 {
863 	register struct ipasfrag *q, *p;
864 
865 	for (q = fp->ipq_next; q != (struct ipasfrag *)fp; q = p) {
866 		p = q->ipf_next;
867 		ip_deq(q);
868 		m_freem(dtom(q));
869 	}
870 	remque(fp);
871 	(void) m_free(dtom(fp));
872 	nipq--;
873 }
874 
875 /*
876  * Put an ip fragment on a reassembly chain.
877  * Like insque, but pointers in middle of structure.
878  */
879 static void
880 ip_enq(p, prev)
881 	register struct ipasfrag *p, *prev;
882 {
883 
884 	p->ipf_prev = prev;
885 	p->ipf_next = prev->ipf_next;
886 	prev->ipf_next->ipf_prev = p;
887 	prev->ipf_next = p;
888 }
889 
890 /*
891  * To ip_enq as remque is to insque.
892  */
893 static void
894 ip_deq(p)
895 	register struct ipasfrag *p;
896 {
897 
898 	p->ipf_prev->ipf_next = p->ipf_next;
899 	p->ipf_next->ipf_prev = p->ipf_prev;
900 }
901 
902 /*
903  * IP timer processing;
904  * if a timer expires on a reassembly
905  * queue, discard it.
906  */
907 void
908 ip_slowtimo()
909 {
910 	register struct ipq *fp;
911 	int s = splnet();
912 	int i;
913 
914 	for (i = 0; i < IPREASS_NHASH; i++) {
915 		fp = ipq[i].next;
916 		if (fp == 0)
917 			continue;
918 		while (fp != &ipq[i]) {
919 			--fp->ipq_ttl;
920 			fp = fp->next;
921 			if (fp->prev->ipq_ttl == 0) {
922 				ipstat.ips_fragtimeout++;
923 				ip_freef(fp->prev);
924 			}
925 		}
926 	}
927 	ipflow_slowtimo();
928 	splx(s);
929 }
930 
931 /*
932  * Drain off all datagram fragments.
933  */
934 void
935 ip_drain()
936 {
937 	int     i;
938 
939 	for (i = 0; i < IPREASS_NHASH; i++) {
940 		while (ipq[i].next != &ipq[i]) {
941 			ipstat.ips_fragdropped++;
942 			ip_freef(ipq[i].next);
943 		}
944 	}
945 	in_rtqdrain();
946 }
947 
948 /*
949  * Do option processing on a datagram,
950  * possibly discarding it if bad options are encountered,
951  * or forwarding it if source-routed.
952  * Returns 1 if packet has been forwarded/freed,
953  * 0 if the packet should be processed further.
954  */
955 static int
956 ip_dooptions(m)
957 	struct mbuf *m;
958 {
959 	register struct ip *ip = mtod(m, struct ip *);
960 	register u_char *cp;
961 	register struct ip_timestamp *ipt;
962 	register struct in_ifaddr *ia;
963 	int opt, optlen, cnt, off, code, type = ICMP_PARAMPROB, forward = 0;
964 	struct in_addr *sin, dst;
965 	n_time ntime;
966 
967 	dst = ip->ip_dst;
968 	cp = (u_char *)(ip + 1);
969 	cnt = (IP_VHL_HL(ip->ip_vhl) << 2) - sizeof (struct ip);
970 	for (; cnt > 0; cnt -= optlen, cp += optlen) {
971 		opt = cp[IPOPT_OPTVAL];
972 		if (opt == IPOPT_EOL)
973 			break;
974 		if (opt == IPOPT_NOP)
975 			optlen = 1;
976 		else {
977 			optlen = cp[IPOPT_OLEN];
978 			if (optlen <= 0 || optlen > cnt) {
979 				code = &cp[IPOPT_OLEN] - (u_char *)ip;
980 				goto bad;
981 			}
982 		}
983 		switch (opt) {
984 
985 		default:
986 			break;
987 
988 		/*
989 		 * Source routing with record.
990 		 * Find interface with current destination address.
991 		 * If none on this machine then drop if strictly routed,
992 		 * or do nothing if loosely routed.
993 		 * Record interface address and bring up next address
994 		 * component.  If strictly routed make sure next
995 		 * address is on directly accessible net.
996 		 */
997 		case IPOPT_LSRR:
998 		case IPOPT_SSRR:
999 			if ((off = cp[IPOPT_OFFSET]) < IPOPT_MINOFF) {
1000 				code = &cp[IPOPT_OFFSET] - (u_char *)ip;
1001 				goto bad;
1002 			}
1003 			ipaddr.sin_addr = ip->ip_dst;
1004 			ia = (struct in_ifaddr *)
1005 				ifa_ifwithaddr((struct sockaddr *)&ipaddr);
1006 			if (ia == 0) {
1007 				if (opt == IPOPT_SSRR) {
1008 					type = ICMP_UNREACH;
1009 					code = ICMP_UNREACH_SRCFAIL;
1010 					goto bad;
1011 				}
1012 				if (!ip_dosourceroute)
1013 					goto nosourcerouting;
1014 				/*
1015 				 * Loose routing, and not at next destination
1016 				 * yet; nothing to do except forward.
1017 				 */
1018 				break;
1019 			}
1020 			off--;			/* 0 origin */
1021 			if (off > optlen - sizeof(struct in_addr)) {
1022 				/*
1023 				 * End of source route.  Should be for us.
1024 				 */
1025 				if (!ip_acceptsourceroute)
1026 					goto nosourcerouting;
1027 				save_rte(cp, ip->ip_src);
1028 				break;
1029 			}
1030 
1031 			if (!ip_dosourceroute) {
1032 				if (ipforwarding) {
1033 					char buf[16]; /* aaa.bbb.ccc.ddd\0 */
1034 					/*
1035 					 * Acting as a router, so generate ICMP
1036 					 */
1037 nosourcerouting:
1038 					strcpy(buf, inet_ntoa(ip->ip_dst));
1039 					log(LOG_WARNING,
1040 					    "attempted source route from %s to %s\n",
1041 					    inet_ntoa(ip->ip_src), buf);
1042 					type = ICMP_UNREACH;
1043 					code = ICMP_UNREACH_SRCFAIL;
1044 					goto bad;
1045 				} else {
1046 					/*
1047 					 * Not acting as a router, so silently drop.
1048 					 */
1049 					ipstat.ips_cantforward++;
1050 					m_freem(m);
1051 					return (1);
1052 				}
1053 			}
1054 
1055 			/*
1056 			 * locate outgoing interface
1057 			 */
1058 			(void)memcpy(&ipaddr.sin_addr, cp + off,
1059 			    sizeof(ipaddr.sin_addr));
1060 
1061 			if (opt == IPOPT_SSRR) {
1062 #define	INA	struct in_ifaddr *
1063 #define	SA	struct sockaddr *
1064 			    if ((ia = (INA)ifa_ifwithdstaddr((SA)&ipaddr)) == 0)
1065 				ia = (INA)ifa_ifwithnet((SA)&ipaddr);
1066 			} else
1067 				ia = ip_rtaddr(ipaddr.sin_addr);
1068 			if (ia == 0) {
1069 				type = ICMP_UNREACH;
1070 				code = ICMP_UNREACH_SRCFAIL;
1071 				goto bad;
1072 			}
1073 			ip->ip_dst = ipaddr.sin_addr;
1074 			(void)memcpy(cp + off, &(IA_SIN(ia)->sin_addr),
1075 			    sizeof(struct in_addr));
1076 			cp[IPOPT_OFFSET] += sizeof(struct in_addr);
1077 			/*
1078 			 * Let ip_intr's mcast routing check handle mcast pkts
1079 			 */
1080 			forward = !IN_MULTICAST(ntohl(ip->ip_dst.s_addr));
1081 			break;
1082 
1083 		case IPOPT_RR:
1084 			if ((off = cp[IPOPT_OFFSET]) < IPOPT_MINOFF) {
1085 				code = &cp[IPOPT_OFFSET] - (u_char *)ip;
1086 				goto bad;
1087 			}
1088 			/*
1089 			 * If no space remains, ignore.
1090 			 */
1091 			off--;			/* 0 origin */
1092 			if (off > optlen - sizeof(struct in_addr))
1093 				break;
1094 			(void)memcpy(&ipaddr.sin_addr, &ip->ip_dst,
1095 			    sizeof(ipaddr.sin_addr));
1096 			/*
1097 			 * locate outgoing interface; if we're the destination,
1098 			 * use the incoming interface (should be same).
1099 			 */
1100 			if ((ia = (INA)ifa_ifwithaddr((SA)&ipaddr)) == 0 &&
1101 			    (ia = ip_rtaddr(ipaddr.sin_addr)) == 0) {
1102 				type = ICMP_UNREACH;
1103 				code = ICMP_UNREACH_HOST;
1104 				goto bad;
1105 			}
1106 			(void)memcpy(cp + off, &(IA_SIN(ia)->sin_addr),
1107 			    sizeof(struct in_addr));
1108 			cp[IPOPT_OFFSET] += sizeof(struct in_addr);
1109 			break;
1110 
1111 		case IPOPT_TS:
1112 			code = cp - (u_char *)ip;
1113 			ipt = (struct ip_timestamp *)cp;
1114 			if (ipt->ipt_len < 5)
1115 				goto bad;
1116 			if (ipt->ipt_ptr > ipt->ipt_len - sizeof(int32_t)) {
1117 				if (++ipt->ipt_oflw == 0)
1118 					goto bad;
1119 				break;
1120 			}
1121 			sin = (struct in_addr *)(cp + ipt->ipt_ptr - 1);
1122 			switch (ipt->ipt_flg) {
1123 
1124 			case IPOPT_TS_TSONLY:
1125 				break;
1126 
1127 			case IPOPT_TS_TSANDADDR:
1128 				if (ipt->ipt_ptr - 1 + sizeof(n_time) +
1129 				    sizeof(struct in_addr) > ipt->ipt_len)
1130 					goto bad;
1131 				ipaddr.sin_addr = dst;
1132 				ia = (INA)ifaof_ifpforaddr((SA)&ipaddr,
1133 							    m->m_pkthdr.rcvif);
1134 				if (ia == 0)
1135 					continue;
1136 				(void)memcpy(sin, &IA_SIN(ia)->sin_addr,
1137 				    sizeof(struct in_addr));
1138 				ipt->ipt_ptr += sizeof(struct in_addr);
1139 				break;
1140 
1141 			case IPOPT_TS_PRESPEC:
1142 				if (ipt->ipt_ptr - 1 + sizeof(n_time) +
1143 				    sizeof(struct in_addr) > ipt->ipt_len)
1144 					goto bad;
1145 				(void)memcpy(&ipaddr.sin_addr, sin,
1146 				    sizeof(struct in_addr));
1147 				if (ifa_ifwithaddr((SA)&ipaddr) == 0)
1148 					continue;
1149 				ipt->ipt_ptr += sizeof(struct in_addr);
1150 				break;
1151 
1152 			default:
1153 				goto bad;
1154 			}
1155 			ntime = iptime();
1156 			(void)memcpy(cp + ipt->ipt_ptr - 1, &ntime,
1157 			    sizeof(n_time));
1158 			ipt->ipt_ptr += sizeof(n_time);
1159 		}
1160 	}
1161 	if (forward && ipforwarding) {
1162 		ip_forward(m, 1);
1163 		return (1);
1164 	}
1165 	return (0);
1166 bad:
1167 	ip->ip_len -= IP_VHL_HL(ip->ip_vhl) << 2;   /* XXX icmp_error adds in hdr length */
1168 	icmp_error(m, type, code, 0, 0);
1169 	ipstat.ips_badoptions++;
1170 	return (1);
1171 }
1172 
1173 /*
1174  * Given address of next destination (final or next hop),
1175  * return internet address info of interface to be used to get there.
1176  */
1177 static struct in_ifaddr *
1178 ip_rtaddr(dst)
1179 	 struct in_addr dst;
1180 {
1181 	register struct sockaddr_in *sin;
1182 
1183 	sin = (struct sockaddr_in *) &ipforward_rt.ro_dst;
1184 
1185 	if (ipforward_rt.ro_rt == 0 || dst.s_addr != sin->sin_addr.s_addr) {
1186 		if (ipforward_rt.ro_rt) {
1187 			RTFREE(ipforward_rt.ro_rt);
1188 			ipforward_rt.ro_rt = 0;
1189 		}
1190 		sin->sin_family = AF_INET;
1191 		sin->sin_len = sizeof(*sin);
1192 		sin->sin_addr = dst;
1193 
1194 		rtalloc_ign(&ipforward_rt, RTF_PRCLONING);
1195 	}
1196 	if (ipforward_rt.ro_rt == 0)
1197 		return ((struct in_ifaddr *)0);
1198 	return ((struct in_ifaddr *) ipforward_rt.ro_rt->rt_ifa);
1199 }
1200 
1201 /*
1202  * Save incoming source route for use in replies,
1203  * to be picked up later by ip_srcroute if the receiver is interested.
1204  */
1205 void
1206 save_rte(option, dst)
1207 	u_char *option;
1208 	struct in_addr dst;
1209 {
1210 	unsigned olen;
1211 
1212 	olen = option[IPOPT_OLEN];
1213 #ifdef DIAGNOSTIC
1214 	if (ipprintfs)
1215 		printf("save_rte: olen %d\n", olen);
1216 #endif
1217 	if (olen > sizeof(ip_srcrt) - (1 + sizeof(dst)))
1218 		return;
1219 	bcopy(option, ip_srcrt.srcopt, olen);
1220 	ip_nhops = (olen - IPOPT_OFFSET - 1) / sizeof(struct in_addr);
1221 	ip_srcrt.dst = dst;
1222 }
1223 
1224 /*
1225  * Retrieve incoming source route for use in replies,
1226  * in the same form used by setsockopt.
1227  * The first hop is placed before the options, will be removed later.
1228  */
1229 struct mbuf *
1230 ip_srcroute()
1231 {
1232 	register struct in_addr *p, *q;
1233 	register struct mbuf *m;
1234 
1235 	if (ip_nhops == 0)
1236 		return ((struct mbuf *)0);
1237 	m = m_get(M_DONTWAIT, MT_SOOPTS);
1238 	if (m == 0)
1239 		return ((struct mbuf *)0);
1240 
1241 #define OPTSIZ	(sizeof(ip_srcrt.nop) + sizeof(ip_srcrt.srcopt))
1242 
1243 	/* length is (nhops+1)*sizeof(addr) + sizeof(nop + srcrt header) */
1244 	m->m_len = ip_nhops * sizeof(struct in_addr) + sizeof(struct in_addr) +
1245 	    OPTSIZ;
1246 #ifdef DIAGNOSTIC
1247 	if (ipprintfs)
1248 		printf("ip_srcroute: nhops %d mlen %d", ip_nhops, m->m_len);
1249 #endif
1250 
1251 	/*
1252 	 * First save first hop for return route
1253 	 */
1254 	p = &ip_srcrt.route[ip_nhops - 1];
1255 	*(mtod(m, struct in_addr *)) = *p--;
1256 #ifdef DIAGNOSTIC
1257 	if (ipprintfs)
1258 		printf(" hops %lx", ntohl(mtod(m, struct in_addr *)->s_addr));
1259 #endif
1260 
1261 	/*
1262 	 * Copy option fields and padding (nop) to mbuf.
1263 	 */
1264 	ip_srcrt.nop = IPOPT_NOP;
1265 	ip_srcrt.srcopt[IPOPT_OFFSET] = IPOPT_MINOFF;
1266 	(void)memcpy(mtod(m, caddr_t) + sizeof(struct in_addr),
1267 	    &ip_srcrt.nop, OPTSIZ);
1268 	q = (struct in_addr *)(mtod(m, caddr_t) +
1269 	    sizeof(struct in_addr) + OPTSIZ);
1270 #undef OPTSIZ
1271 	/*
1272 	 * Record return path as an IP source route,
1273 	 * reversing the path (pointers are now aligned).
1274 	 */
1275 	while (p >= ip_srcrt.route) {
1276 #ifdef DIAGNOSTIC
1277 		if (ipprintfs)
1278 			printf(" %lx", ntohl(q->s_addr));
1279 #endif
1280 		*q++ = *p--;
1281 	}
1282 	/*
1283 	 * Last hop goes to final destination.
1284 	 */
1285 	*q = ip_srcrt.dst;
1286 #ifdef DIAGNOSTIC
1287 	if (ipprintfs)
1288 		printf(" %lx\n", ntohl(q->s_addr));
1289 #endif
1290 	return (m);
1291 }
1292 
1293 /*
1294  * Strip out IP options, at higher
1295  * level protocol in the kernel.
1296  * Second argument is buffer to which options
1297  * will be moved, and return value is their length.
1298  * XXX should be deleted; last arg currently ignored.
1299  */
1300 void
1301 ip_stripoptions(m, mopt)
1302 	register struct mbuf *m;
1303 	struct mbuf *mopt;
1304 {
1305 	register int i;
1306 	struct ip *ip = mtod(m, struct ip *);
1307 	register caddr_t opts;
1308 	int olen;
1309 
1310 	olen = (IP_VHL_HL(ip->ip_vhl) << 2) - sizeof (struct ip);
1311 	opts = (caddr_t)(ip + 1);
1312 	i = m->m_len - (sizeof (struct ip) + olen);
1313 	bcopy(opts + olen, opts, (unsigned)i);
1314 	m->m_len -= olen;
1315 	if (m->m_flags & M_PKTHDR)
1316 		m->m_pkthdr.len -= olen;
1317 	ip->ip_vhl = IP_MAKE_VHL(IPVERSION, sizeof(struct ip) >> 2);
1318 }
1319 
1320 u_char inetctlerrmap[PRC_NCMDS] = {
1321 	0,		0,		0,		0,
1322 	0,		EMSGSIZE,	EHOSTDOWN,	EHOSTUNREACH,
1323 	EHOSTUNREACH,	EHOSTUNREACH,	ECONNREFUSED,	ECONNREFUSED,
1324 	EMSGSIZE,	EHOSTUNREACH,	0,		0,
1325 	0,		0,		0,		0,
1326 	ENOPROTOOPT
1327 };
1328 
1329 /*
1330  * Forward a packet.  If some error occurs return the sender
1331  * an icmp packet.  Note we can't always generate a meaningful
1332  * icmp message because icmp doesn't have a large enough repertoire
1333  * of codes and types.
1334  *
1335  * If not forwarding, just drop the packet.  This could be confusing
1336  * if ipforwarding was zero but some routing protocol was advancing
1337  * us as a gateway to somewhere.  However, we must let the routing
1338  * protocol deal with that.
1339  *
1340  * The srcrt parameter indicates whether the packet is being forwarded
1341  * via a source route.
1342  */
1343 static void
1344 ip_forward(m, srcrt)
1345 	struct mbuf *m;
1346 	int srcrt;
1347 {
1348 	register struct ip *ip = mtod(m, struct ip *);
1349 	register struct sockaddr_in *sin;
1350 	register struct rtentry *rt;
1351 	int error, type = 0, code = 0;
1352 	struct mbuf *mcopy;
1353 	n_long dest;
1354 	struct ifnet *destifp;
1355 
1356 	dest = 0;
1357 #ifdef DIAGNOSTIC
1358 	if (ipprintfs)
1359 		printf("forward: src %lx dst %lx ttl %x\n",
1360 			ip->ip_src.s_addr, ip->ip_dst.s_addr, ip->ip_ttl);
1361 #endif
1362 
1363 
1364 	if (m->m_flags & M_BCAST || in_canforward(ip->ip_dst) == 0) {
1365 		ipstat.ips_cantforward++;
1366 		m_freem(m);
1367 		return;
1368 	}
1369 	HTONS(ip->ip_id);
1370 	if (ip->ip_ttl <= IPTTLDEC) {
1371 		icmp_error(m, ICMP_TIMXCEED, ICMP_TIMXCEED_INTRANS, dest, 0);
1372 		return;
1373 	}
1374 	ip->ip_ttl -= IPTTLDEC;
1375 
1376 	sin = (struct sockaddr_in *)&ipforward_rt.ro_dst;
1377 	if ((rt = ipforward_rt.ro_rt) == 0 ||
1378 	    ip->ip_dst.s_addr != sin->sin_addr.s_addr) {
1379 		if (ipforward_rt.ro_rt) {
1380 			RTFREE(ipforward_rt.ro_rt);
1381 			ipforward_rt.ro_rt = 0;
1382 		}
1383 		sin->sin_family = AF_INET;
1384 		sin->sin_len = sizeof(*sin);
1385 		sin->sin_addr = ip->ip_dst;
1386 
1387 		rtalloc_ign(&ipforward_rt, RTF_PRCLONING);
1388 		if (ipforward_rt.ro_rt == 0) {
1389 			icmp_error(m, ICMP_UNREACH, ICMP_UNREACH_HOST, dest, 0);
1390 			return;
1391 		}
1392 		rt = ipforward_rt.ro_rt;
1393 	}
1394 
1395 	/*
1396 	 * Save at most 64 bytes of the packet in case
1397 	 * we need to generate an ICMP message to the src.
1398 	 */
1399 	mcopy = m_copy(m, 0, imin((int)ip->ip_len, 64));
1400 
1401 	/*
1402 	 * If forwarding packet using same interface that it came in on,
1403 	 * perhaps should send a redirect to sender to shortcut a hop.
1404 	 * Only send redirect if source is sending directly to us,
1405 	 * and if packet was not source routed (or has any options).
1406 	 * Also, don't send redirect if forwarding using a default route
1407 	 * or a route modified by a redirect.
1408 	 */
1409 #define	satosin(sa)	((struct sockaddr_in *)(sa))
1410 	if (rt->rt_ifp == m->m_pkthdr.rcvif &&
1411 	    (rt->rt_flags & (RTF_DYNAMIC|RTF_MODIFIED)) == 0 &&
1412 	    satosin(rt_key(rt))->sin_addr.s_addr != 0 &&
1413 	    ipsendredirects && !srcrt) {
1414 #define	RTA(rt)	((struct in_ifaddr *)(rt->rt_ifa))
1415 		u_long src = ntohl(ip->ip_src.s_addr);
1416 
1417 		if (RTA(rt) &&
1418 		    (src & RTA(rt)->ia_subnetmask) == RTA(rt)->ia_subnet) {
1419 		    if (rt->rt_flags & RTF_GATEWAY)
1420 			dest = satosin(rt->rt_gateway)->sin_addr.s_addr;
1421 		    else
1422 			dest = ip->ip_dst.s_addr;
1423 		    /* Router requirements says to only send host redirects */
1424 		    type = ICMP_REDIRECT;
1425 		    code = ICMP_REDIRECT_HOST;
1426 #ifdef DIAGNOSTIC
1427 		    if (ipprintfs)
1428 		        printf("redirect (%d) to %lx\n", code, (u_long)dest);
1429 #endif
1430 		}
1431 	}
1432 
1433 	error = ip_output(m, (struct mbuf *)0, &ipforward_rt,
1434 			  IP_FORWARDING, 0);
1435 	if (error)
1436 		ipstat.ips_cantforward++;
1437 	else {
1438 		ipstat.ips_forward++;
1439 		if (type)
1440 			ipstat.ips_redirectsent++;
1441 		else {
1442 			if (mcopy) {
1443 				ipflow_create(&ipforward_rt, mcopy);
1444 				m_freem(mcopy);
1445 			}
1446 			return;
1447 		}
1448 	}
1449 	if (mcopy == NULL)
1450 		return;
1451 	destifp = NULL;
1452 
1453 	switch (error) {
1454 
1455 	case 0:				/* forwarded, but need redirect */
1456 		/* type, code set above */
1457 		break;
1458 
1459 	case ENETUNREACH:		/* shouldn't happen, checked above */
1460 	case EHOSTUNREACH:
1461 	case ENETDOWN:
1462 	case EHOSTDOWN:
1463 	default:
1464 		type = ICMP_UNREACH;
1465 		code = ICMP_UNREACH_HOST;
1466 		break;
1467 
1468 	case EMSGSIZE:
1469 		type = ICMP_UNREACH;
1470 		code = ICMP_UNREACH_NEEDFRAG;
1471 		if (ipforward_rt.ro_rt)
1472 			destifp = ipforward_rt.ro_rt->rt_ifp;
1473 		ipstat.ips_cantfrag++;
1474 		break;
1475 
1476 	case ENOBUFS:
1477 		type = ICMP_SOURCEQUENCH;
1478 		code = 0;
1479 		break;
1480 	}
1481 	icmp_error(mcopy, type, code, dest, destifp);
1482 }
1483 
1484 void
1485 ip_savecontrol(inp, mp, ip, m)
1486 	register struct inpcb *inp;
1487 	register struct mbuf **mp;
1488 	register struct ip *ip;
1489 	register struct mbuf *m;
1490 {
1491 	if (inp->inp_socket->so_options & SO_TIMESTAMP) {
1492 		struct timeval tv;
1493 
1494 		microtime(&tv);
1495 		*mp = sbcreatecontrol((caddr_t) &tv, sizeof(tv),
1496 			SCM_TIMESTAMP, SOL_SOCKET);
1497 		if (*mp)
1498 			mp = &(*mp)->m_next;
1499 	}
1500 	if (inp->inp_flags & INP_RECVDSTADDR) {
1501 		*mp = sbcreatecontrol((caddr_t) &ip->ip_dst,
1502 		    sizeof(struct in_addr), IP_RECVDSTADDR, IPPROTO_IP);
1503 		if (*mp)
1504 			mp = &(*mp)->m_next;
1505 	}
1506 #ifdef notyet
1507 	/* XXX
1508 	 * Moving these out of udp_input() made them even more broken
1509 	 * than they already were.
1510 	 */
1511 	/* options were tossed already */
1512 	if (inp->inp_flags & INP_RECVOPTS) {
1513 		*mp = sbcreatecontrol((caddr_t) opts_deleted_above,
1514 		    sizeof(struct in_addr), IP_RECVOPTS, IPPROTO_IP);
1515 		if (*mp)
1516 			mp = &(*mp)->m_next;
1517 	}
1518 	/* ip_srcroute doesn't do what we want here, need to fix */
1519 	if (inp->inp_flags & INP_RECVRETOPTS) {
1520 		*mp = sbcreatecontrol((caddr_t) ip_srcroute(),
1521 		    sizeof(struct in_addr), IP_RECVRETOPTS, IPPROTO_IP);
1522 		if (*mp)
1523 			mp = &(*mp)->m_next;
1524 	}
1525 #endif
1526 	if (inp->inp_flags & INP_RECVIF) {
1527 		struct ifnet *ifp;
1528 		struct sdlbuf {
1529 			struct sockaddr_dl sdl;
1530 			u_char	pad[32];
1531 		} sdlbuf;
1532 		struct sockaddr_dl *sdp;
1533 		struct sockaddr_dl *sdl2 = &sdlbuf.sdl;
1534 
1535 		if (((ifp = m->m_pkthdr.rcvif))
1536 		&& ( ifp->if_index && (ifp->if_index <= if_index))) {
1537 			sdp = (struct sockaddr_dl *)(ifnet_addrs
1538 					[ifp->if_index - 1]->ifa_addr);
1539 			/*
1540 			 * Change our mind and don't try copy.
1541 			 */
1542 			if ((sdp->sdl_family != AF_LINK)
1543 			|| (sdp->sdl_len > sizeof(sdlbuf))) {
1544 				goto makedummy;
1545 			}
1546 			bcopy(sdp, sdl2, sdp->sdl_len);
1547 		} else {
1548 makedummy:
1549 			sdl2->sdl_len
1550 				= offsetof(struct sockaddr_dl, sdl_data[0]);
1551 			sdl2->sdl_family = AF_LINK;
1552 			sdl2->sdl_index = 0;
1553 			sdl2->sdl_nlen = sdl2->sdl_alen = sdl2->sdl_slen = 0;
1554 		}
1555 		*mp = sbcreatecontrol((caddr_t) sdl2, sdl2->sdl_len,
1556 			IP_RECVIF, IPPROTO_IP);
1557 		if (*mp)
1558 			mp = &(*mp)->m_next;
1559 	}
1560 }
1561 
1562 int
1563 ip_rsvp_init(struct socket *so)
1564 {
1565 	if (so->so_type != SOCK_RAW ||
1566 	    so->so_proto->pr_protocol != IPPROTO_RSVP)
1567 	  return EOPNOTSUPP;
1568 
1569 	if (ip_rsvpd != NULL)
1570 	  return EADDRINUSE;
1571 
1572 	ip_rsvpd = so;
1573 	/*
1574 	 * This may seem silly, but we need to be sure we don't over-increment
1575 	 * the RSVP counter, in case something slips up.
1576 	 */
1577 	if (!ip_rsvp_on) {
1578 		ip_rsvp_on = 1;
1579 		rsvp_on++;
1580 	}
1581 
1582 	return 0;
1583 }
1584 
1585 int
1586 ip_rsvp_done(void)
1587 {
1588 	ip_rsvpd = NULL;
1589 	/*
1590 	 * This may seem silly, but we need to be sure we don't over-decrement
1591 	 * the RSVP counter, in case something slips up.
1592 	 */
1593 	if (ip_rsvp_on) {
1594 		ip_rsvp_on = 0;
1595 		rsvp_on--;
1596 	}
1597 	return 0;
1598 }
1599