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