xref: /freebsd/sys/netinet/ip_input.c (revision 7ad194ad1dbaf20b2755a448f06ff50c39bc9eda)
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 			if (cnt < IPOPT_OLEN + sizeof(*cp)) {
1082 				code = &cp[IPOPT_OLEN] - (u_char *)ip;
1083 				goto bad;
1084 			}
1085 			optlen = cp[IPOPT_OLEN];
1086 			if (optlen < IPOPT_OLEN + sizeof(*cp) || optlen > cnt) {
1087 				code = &cp[IPOPT_OLEN] - (u_char *)ip;
1088 				goto bad;
1089 			}
1090 		}
1091 		switch (opt) {
1092 
1093 		default:
1094 			break;
1095 
1096 		/*
1097 		 * Source routing with record.
1098 		 * Find interface with current destination address.
1099 		 * If none on this machine then drop if strictly routed,
1100 		 * or do nothing if loosely routed.
1101 		 * Record interface address and bring up next address
1102 		 * component.  If strictly routed make sure next
1103 		 * address is on directly accessible net.
1104 		 */
1105 		case IPOPT_LSRR:
1106 		case IPOPT_SSRR:
1107 			if ((off = cp[IPOPT_OFFSET]) < IPOPT_MINOFF) {
1108 				code = &cp[IPOPT_OFFSET] - (u_char *)ip;
1109 				goto bad;
1110 			}
1111 			ipaddr.sin_addr = ip->ip_dst;
1112 			ia = (struct in_ifaddr *)
1113 				ifa_ifwithaddr((struct sockaddr *)&ipaddr);
1114 			if (ia == 0) {
1115 				if (opt == IPOPT_SSRR) {
1116 					type = ICMP_UNREACH;
1117 					code = ICMP_UNREACH_SRCFAIL;
1118 					goto bad;
1119 				}
1120 				if (!ip_dosourceroute)
1121 					goto nosourcerouting;
1122 				/*
1123 				 * Loose routing, and not at next destination
1124 				 * yet; nothing to do except forward.
1125 				 */
1126 				break;
1127 			}
1128 			off--;			/* 0 origin */
1129 			if (off > optlen - (int)sizeof(struct in_addr)) {
1130 				/*
1131 				 * End of source route.  Should be for us.
1132 				 */
1133 				if (!ip_acceptsourceroute)
1134 					goto nosourcerouting;
1135 				save_rte(cp, ip->ip_src);
1136 				break;
1137 			}
1138 
1139 			if (!ip_dosourceroute) {
1140 				if (ipforwarding) {
1141 					char buf[16]; /* aaa.bbb.ccc.ddd\0 */
1142 					/*
1143 					 * Acting as a router, so generate ICMP
1144 					 */
1145 nosourcerouting:
1146 					strcpy(buf, inet_ntoa(ip->ip_dst));
1147 					log(LOG_WARNING,
1148 					    "attempted source route from %s to %s\n",
1149 					    inet_ntoa(ip->ip_src), buf);
1150 					type = ICMP_UNREACH;
1151 					code = ICMP_UNREACH_SRCFAIL;
1152 					goto bad;
1153 				} else {
1154 					/*
1155 					 * Not acting as a router, so silently drop.
1156 					 */
1157 					ipstat.ips_cantforward++;
1158 					m_freem(m);
1159 					return (1);
1160 				}
1161 			}
1162 
1163 			/*
1164 			 * locate outgoing interface
1165 			 */
1166 			(void)memcpy(&ipaddr.sin_addr, cp + off,
1167 			    sizeof(ipaddr.sin_addr));
1168 
1169 			if (opt == IPOPT_SSRR) {
1170 #define	INA	struct in_ifaddr *
1171 #define	SA	struct sockaddr *
1172 			    if ((ia = (INA)ifa_ifwithdstaddr((SA)&ipaddr)) == 0)
1173 				ia = (INA)ifa_ifwithnet((SA)&ipaddr);
1174 			} else
1175 				ia = ip_rtaddr(ipaddr.sin_addr);
1176 			if (ia == 0) {
1177 				type = ICMP_UNREACH;
1178 				code = ICMP_UNREACH_SRCFAIL;
1179 				goto bad;
1180 			}
1181 			ip->ip_dst = ipaddr.sin_addr;
1182 			(void)memcpy(cp + off, &(IA_SIN(ia)->sin_addr),
1183 			    sizeof(struct in_addr));
1184 			cp[IPOPT_OFFSET] += sizeof(struct in_addr);
1185 			/*
1186 			 * Let ip_intr's mcast routing check handle mcast pkts
1187 			 */
1188 			forward = !IN_MULTICAST(ntohl(ip->ip_dst.s_addr));
1189 			break;
1190 
1191 		case IPOPT_RR:
1192 			if (optlen < IPOPT_OFFSET + sizeof(*cp)) {
1193 				code = &cp[IPOPT_OFFSET] - (u_char *)ip;
1194 				goto bad;
1195 			}
1196 			if ((off = cp[IPOPT_OFFSET]) < IPOPT_MINOFF) {
1197 				code = &cp[IPOPT_OFFSET] - (u_char *)ip;
1198 				goto bad;
1199 			}
1200 			/*
1201 			 * If no space remains, ignore.
1202 			 */
1203 			off--;			/* 0 origin */
1204 			if (off > optlen - (int)sizeof(struct in_addr))
1205 				break;
1206 			(void)memcpy(&ipaddr.sin_addr, &ip->ip_dst,
1207 			    sizeof(ipaddr.sin_addr));
1208 			/*
1209 			 * locate outgoing interface; if we're the destination,
1210 			 * use the incoming interface (should be same).
1211 			 */
1212 			if ((ia = (INA)ifa_ifwithaddr((SA)&ipaddr)) == 0 &&
1213 			    (ia = ip_rtaddr(ipaddr.sin_addr)) == 0) {
1214 				type = ICMP_UNREACH;
1215 				code = ICMP_UNREACH_HOST;
1216 				goto bad;
1217 			}
1218 			(void)memcpy(cp + off, &(IA_SIN(ia)->sin_addr),
1219 			    sizeof(struct in_addr));
1220 			cp[IPOPT_OFFSET] += sizeof(struct in_addr);
1221 			break;
1222 
1223 		case IPOPT_TS:
1224 			code = cp - (u_char *)ip;
1225 			ipt = (struct ip_timestamp *)cp;
1226 			if (ipt->ipt_len < 5)
1227 				goto bad;
1228 			if (ipt->ipt_ptr >
1229 			    ipt->ipt_len - (int)sizeof(int32_t)) {
1230 				if (++ipt->ipt_oflw == 0)
1231 					goto bad;
1232 				break;
1233 			}
1234 			sin = (struct in_addr *)(cp + ipt->ipt_ptr - 1);
1235 			switch (ipt->ipt_flg) {
1236 
1237 			case IPOPT_TS_TSONLY:
1238 				break;
1239 
1240 			case IPOPT_TS_TSANDADDR:
1241 				if (ipt->ipt_ptr - 1 + sizeof(n_time) +
1242 				    sizeof(struct in_addr) > ipt->ipt_len)
1243 					goto bad;
1244 				ipaddr.sin_addr = dst;
1245 				ia = (INA)ifaof_ifpforaddr((SA)&ipaddr,
1246 							    m->m_pkthdr.rcvif);
1247 				if (ia == 0)
1248 					continue;
1249 				(void)memcpy(sin, &IA_SIN(ia)->sin_addr,
1250 				    sizeof(struct in_addr));
1251 				ipt->ipt_ptr += sizeof(struct in_addr);
1252 				break;
1253 
1254 			case IPOPT_TS_PRESPEC:
1255 				if (ipt->ipt_ptr - 1 + sizeof(n_time) +
1256 				    sizeof(struct in_addr) > ipt->ipt_len)
1257 					goto bad;
1258 				(void)memcpy(&ipaddr.sin_addr, sin,
1259 				    sizeof(struct in_addr));
1260 				if (ifa_ifwithaddr((SA)&ipaddr) == 0)
1261 					continue;
1262 				ipt->ipt_ptr += sizeof(struct in_addr);
1263 				break;
1264 
1265 			default:
1266 				goto bad;
1267 			}
1268 			ntime = iptime();
1269 			(void)memcpy(cp + ipt->ipt_ptr - 1, &ntime,
1270 			    sizeof(n_time));
1271 			ipt->ipt_ptr += sizeof(n_time);
1272 		}
1273 	}
1274 	if (forward && ipforwarding) {
1275 		ip_forward(m, 1);
1276 		return (1);
1277 	}
1278 	return (0);
1279 bad:
1280 	ip->ip_len -= IP_VHL_HL(ip->ip_vhl) << 2;   /* XXX icmp_error adds in hdr length */
1281 	icmp_error(m, type, code, 0, 0);
1282 	ipstat.ips_badoptions++;
1283 	return (1);
1284 }
1285 
1286 /*
1287  * Given address of next destination (final or next hop),
1288  * return internet address info of interface to be used to get there.
1289  */
1290 static struct in_ifaddr *
1291 ip_rtaddr(dst)
1292 	 struct in_addr dst;
1293 {
1294 	register struct sockaddr_in *sin;
1295 
1296 	sin = (struct sockaddr_in *) &ipforward_rt.ro_dst;
1297 
1298 	if (ipforward_rt.ro_rt == 0 || dst.s_addr != sin->sin_addr.s_addr) {
1299 		if (ipforward_rt.ro_rt) {
1300 			RTFREE(ipforward_rt.ro_rt);
1301 			ipforward_rt.ro_rt = 0;
1302 		}
1303 		sin->sin_family = AF_INET;
1304 		sin->sin_len = sizeof(*sin);
1305 		sin->sin_addr = dst;
1306 
1307 		rtalloc_ign(&ipforward_rt, RTF_PRCLONING);
1308 	}
1309 	if (ipforward_rt.ro_rt == 0)
1310 		return ((struct in_ifaddr *)0);
1311 	return ((struct in_ifaddr *) ipforward_rt.ro_rt->rt_ifa);
1312 }
1313 
1314 /*
1315  * Save incoming source route for use in replies,
1316  * to be picked up later by ip_srcroute if the receiver is interested.
1317  */
1318 void
1319 save_rte(option, dst)
1320 	u_char *option;
1321 	struct in_addr dst;
1322 {
1323 	unsigned olen;
1324 
1325 	olen = option[IPOPT_OLEN];
1326 #ifdef DIAGNOSTIC
1327 	if (ipprintfs)
1328 		printf("save_rte: olen %d\n", olen);
1329 #endif
1330 	if (olen > sizeof(ip_srcrt) - (1 + sizeof(dst)))
1331 		return;
1332 	bcopy(option, ip_srcrt.srcopt, olen);
1333 	ip_nhops = (olen - IPOPT_OFFSET - 1) / sizeof(struct in_addr);
1334 	ip_srcrt.dst = dst;
1335 }
1336 
1337 /*
1338  * Retrieve incoming source route for use in replies,
1339  * in the same form used by setsockopt.
1340  * The first hop is placed before the options, will be removed later.
1341  */
1342 struct mbuf *
1343 ip_srcroute()
1344 {
1345 	register struct in_addr *p, *q;
1346 	register struct mbuf *m;
1347 
1348 	if (ip_nhops == 0)
1349 		return ((struct mbuf *)0);
1350 	m = m_get(M_DONTWAIT, MT_HEADER);
1351 	if (m == 0)
1352 		return ((struct mbuf *)0);
1353 
1354 #define OPTSIZ	(sizeof(ip_srcrt.nop) + sizeof(ip_srcrt.srcopt))
1355 
1356 	/* length is (nhops+1)*sizeof(addr) + sizeof(nop + srcrt header) */
1357 	m->m_len = ip_nhops * sizeof(struct in_addr) + sizeof(struct in_addr) +
1358 	    OPTSIZ;
1359 #ifdef DIAGNOSTIC
1360 	if (ipprintfs)
1361 		printf("ip_srcroute: nhops %d mlen %d", ip_nhops, m->m_len);
1362 #endif
1363 
1364 	/*
1365 	 * First save first hop for return route
1366 	 */
1367 	p = &ip_srcrt.route[ip_nhops - 1];
1368 	*(mtod(m, struct in_addr *)) = *p--;
1369 #ifdef DIAGNOSTIC
1370 	if (ipprintfs)
1371 		printf(" hops %lx", (u_long)ntohl(mtod(m, struct in_addr *)->s_addr));
1372 #endif
1373 
1374 	/*
1375 	 * Copy option fields and padding (nop) to mbuf.
1376 	 */
1377 	ip_srcrt.nop = IPOPT_NOP;
1378 	ip_srcrt.srcopt[IPOPT_OFFSET] = IPOPT_MINOFF;
1379 	(void)memcpy(mtod(m, caddr_t) + sizeof(struct in_addr),
1380 	    &ip_srcrt.nop, OPTSIZ);
1381 	q = (struct in_addr *)(mtod(m, caddr_t) +
1382 	    sizeof(struct in_addr) + OPTSIZ);
1383 #undef OPTSIZ
1384 	/*
1385 	 * Record return path as an IP source route,
1386 	 * reversing the path (pointers are now aligned).
1387 	 */
1388 	while (p >= ip_srcrt.route) {
1389 #ifdef DIAGNOSTIC
1390 		if (ipprintfs)
1391 			printf(" %lx", (u_long)ntohl(q->s_addr));
1392 #endif
1393 		*q++ = *p--;
1394 	}
1395 	/*
1396 	 * Last hop goes to final destination.
1397 	 */
1398 	*q = ip_srcrt.dst;
1399 #ifdef DIAGNOSTIC
1400 	if (ipprintfs)
1401 		printf(" %lx\n", (u_long)ntohl(q->s_addr));
1402 #endif
1403 	return (m);
1404 }
1405 
1406 /*
1407  * Strip out IP options, at higher
1408  * level protocol in the kernel.
1409  * Second argument is buffer to which options
1410  * will be moved, and return value is their length.
1411  * XXX should be deleted; last arg currently ignored.
1412  */
1413 void
1414 ip_stripoptions(m, mopt)
1415 	register struct mbuf *m;
1416 	struct mbuf *mopt;
1417 {
1418 	register int i;
1419 	struct ip *ip = mtod(m, struct ip *);
1420 	register caddr_t opts;
1421 	int olen;
1422 
1423 	olen = (IP_VHL_HL(ip->ip_vhl) << 2) - sizeof (struct ip);
1424 	opts = (caddr_t)(ip + 1);
1425 	i = m->m_len - (sizeof (struct ip) + olen);
1426 	bcopy(opts + olen, opts, (unsigned)i);
1427 	m->m_len -= olen;
1428 	if (m->m_flags & M_PKTHDR)
1429 		m->m_pkthdr.len -= olen;
1430 	ip->ip_vhl = IP_MAKE_VHL(IPVERSION, sizeof(struct ip) >> 2);
1431 }
1432 
1433 u_char inetctlerrmap[PRC_NCMDS] = {
1434 	0,		0,		0,		0,
1435 	0,		EMSGSIZE,	EHOSTDOWN,	EHOSTUNREACH,
1436 	EHOSTUNREACH,	EHOSTUNREACH,	ECONNREFUSED,	ECONNREFUSED,
1437 	EMSGSIZE,	EHOSTUNREACH,	0,		0,
1438 	0,		0,		0,		0,
1439 	ENOPROTOOPT
1440 };
1441 
1442 /*
1443  * Forward a packet.  If some error occurs return the sender
1444  * an icmp packet.  Note we can't always generate a meaningful
1445  * icmp message because icmp doesn't have a large enough repertoire
1446  * of codes and types.
1447  *
1448  * If not forwarding, just drop the packet.  This could be confusing
1449  * if ipforwarding was zero but some routing protocol was advancing
1450  * us as a gateway to somewhere.  However, we must let the routing
1451  * protocol deal with that.
1452  *
1453  * The srcrt parameter indicates whether the packet is being forwarded
1454  * via a source route.
1455  */
1456 static void
1457 ip_forward(m, srcrt)
1458 	struct mbuf *m;
1459 	int srcrt;
1460 {
1461 	register struct ip *ip = mtod(m, struct ip *);
1462 	register struct sockaddr_in *sin;
1463 	register struct rtentry *rt;
1464 	int error, type = 0, code = 0;
1465 	struct mbuf *mcopy;
1466 	n_long dest;
1467 	struct ifnet *destifp;
1468 #ifdef IPSEC
1469 	struct ifnet dummyifp;
1470 #endif
1471 
1472 	dest = 0;
1473 #ifdef DIAGNOSTIC
1474 	if (ipprintfs)
1475 		printf("forward: src %lx dst %lx ttl %x\n",
1476 		    (u_long)ip->ip_src.s_addr, (u_long)ip->ip_dst.s_addr,
1477 		    ip->ip_ttl);
1478 #endif
1479 
1480 
1481 	if (m->m_flags & (M_BCAST|M_MCAST) || in_canforward(ip->ip_dst) == 0) {
1482 		ipstat.ips_cantforward++;
1483 		m_freem(m);
1484 		return;
1485 	}
1486 	HTONS(ip->ip_id);
1487 #ifdef IPSTEALTH
1488 	if (!ipstealth) {
1489 #endif
1490 		if (ip->ip_ttl <= IPTTLDEC) {
1491 			icmp_error(m, ICMP_TIMXCEED, ICMP_TIMXCEED_INTRANS,
1492 			    dest, 0);
1493 			return;
1494 		}
1495 		ip->ip_ttl -= IPTTLDEC;
1496 #ifdef IPSTEALTH
1497 	}
1498 #endif
1499 
1500 	sin = (struct sockaddr_in *)&ipforward_rt.ro_dst;
1501 	if ((rt = ipforward_rt.ro_rt) == 0 ||
1502 	    ip->ip_dst.s_addr != sin->sin_addr.s_addr) {
1503 		if (ipforward_rt.ro_rt) {
1504 			RTFREE(ipforward_rt.ro_rt);
1505 			ipforward_rt.ro_rt = 0;
1506 		}
1507 		sin->sin_family = AF_INET;
1508 		sin->sin_len = sizeof(*sin);
1509 		sin->sin_addr = ip->ip_dst;
1510 
1511 		rtalloc_ign(&ipforward_rt, RTF_PRCLONING);
1512 		if (ipforward_rt.ro_rt == 0) {
1513 			icmp_error(m, ICMP_UNREACH, ICMP_UNREACH_HOST, dest, 0);
1514 			return;
1515 		}
1516 		rt = ipforward_rt.ro_rt;
1517 	}
1518 
1519 	/*
1520 	 * Save at most 64 bytes of the packet in case
1521 	 * we need to generate an ICMP message to the src.
1522 	 */
1523 	mcopy = m_copy(m, 0, imin((int)ip->ip_len, 64));
1524 
1525 	/*
1526 	 * If forwarding packet using same interface that it came in on,
1527 	 * perhaps should send a redirect to sender to shortcut a hop.
1528 	 * Only send redirect if source is sending directly to us,
1529 	 * and if packet was not source routed (or has any options).
1530 	 * Also, don't send redirect if forwarding using a default route
1531 	 * or a route modified by a redirect.
1532 	 */
1533 #define	satosin(sa)	((struct sockaddr_in *)(sa))
1534 	if (rt->rt_ifp == m->m_pkthdr.rcvif &&
1535 	    (rt->rt_flags & (RTF_DYNAMIC|RTF_MODIFIED)) == 0 &&
1536 	    satosin(rt_key(rt))->sin_addr.s_addr != 0 &&
1537 	    ipsendredirects && !srcrt) {
1538 #define	RTA(rt)	((struct in_ifaddr *)(rt->rt_ifa))
1539 		u_long src = ntohl(ip->ip_src.s_addr);
1540 
1541 		if (RTA(rt) &&
1542 		    (src & RTA(rt)->ia_subnetmask) == RTA(rt)->ia_subnet) {
1543 		    if (rt->rt_flags & RTF_GATEWAY)
1544 			dest = satosin(rt->rt_gateway)->sin_addr.s_addr;
1545 		    else
1546 			dest = ip->ip_dst.s_addr;
1547 		    /* Router requirements says to only send host redirects */
1548 		    type = ICMP_REDIRECT;
1549 		    code = ICMP_REDIRECT_HOST;
1550 #ifdef DIAGNOSTIC
1551 		    if (ipprintfs)
1552 		        printf("redirect (%d) to %lx\n", code, (u_long)dest);
1553 #endif
1554 		}
1555 	}
1556 
1557 	error = ip_output(m, (struct mbuf *)0, &ipforward_rt,
1558 			  IP_FORWARDING, 0);
1559 	if (error)
1560 		ipstat.ips_cantforward++;
1561 	else {
1562 		ipstat.ips_forward++;
1563 		if (type)
1564 			ipstat.ips_redirectsent++;
1565 		else {
1566 			if (mcopy) {
1567 				ipflow_create(&ipforward_rt, mcopy);
1568 				m_freem(mcopy);
1569 			}
1570 			return;
1571 		}
1572 	}
1573 	if (mcopy == NULL)
1574 		return;
1575 	destifp = NULL;
1576 
1577 	switch (error) {
1578 
1579 	case 0:				/* forwarded, but need redirect */
1580 		/* type, code set above */
1581 		break;
1582 
1583 	case ENETUNREACH:		/* shouldn't happen, checked above */
1584 	case EHOSTUNREACH:
1585 	case ENETDOWN:
1586 	case EHOSTDOWN:
1587 	default:
1588 		type = ICMP_UNREACH;
1589 		code = ICMP_UNREACH_HOST;
1590 		break;
1591 
1592 	case EMSGSIZE:
1593 		type = ICMP_UNREACH;
1594 		code = ICMP_UNREACH_NEEDFRAG;
1595 #ifndef IPSEC
1596 		if (ipforward_rt.ro_rt)
1597 			destifp = ipforward_rt.ro_rt->rt_ifp;
1598 #else
1599 		/*
1600 		 * If the packet is routed over IPsec tunnel, tell the
1601 		 * originator the tunnel MTU.
1602 		 *	tunnel MTU = if MTU - sizeof(IP) - ESP/AH hdrsiz
1603 		 * XXX quickhack!!!
1604 		 */
1605 		if (ipforward_rt.ro_rt) {
1606 			struct secpolicy *sp = NULL;
1607 			int ipsecerror;
1608 			int ipsechdr;
1609 			struct route *ro;
1610 
1611 			sp = ipsec4_getpolicybyaddr(mcopy,
1612 						    IPSEC_DIR_OUTBOUND,
1613 			                            IP_FORWARDING,
1614 			                            &ipsecerror);
1615 
1616 			if (sp == NULL)
1617 				destifp = ipforward_rt.ro_rt->rt_ifp;
1618 			else {
1619 				/* count IPsec header size */
1620 				ipsechdr = ipsec4_hdrsiz(mcopy,
1621 							 IPSEC_DIR_OUTBOUND,
1622 							 NULL);
1623 
1624 				/*
1625 				 * find the correct route for outer IPv4
1626 				 * header, compute tunnel MTU.
1627 				 *
1628 				 * XXX BUG ALERT
1629 				 * The "dummyifp" code relies upon the fact
1630 				 * that icmp_error() touches only ifp->if_mtu.
1631 				 */
1632 				/*XXX*/
1633 				destifp = NULL;
1634 				if (sp->req != NULL
1635 				 && sp->req->sav != NULL
1636 				 && sp->req->sav->sah != NULL) {
1637 					ro = &sp->req->sav->sah->sa_route;
1638 					if (ro->ro_rt && ro->ro_rt->rt_ifp) {
1639 						dummyifp.if_mtu =
1640 						    ro->ro_rt->rt_ifp->if_mtu;
1641 						dummyifp.if_mtu -= ipsechdr;
1642 						destifp = &dummyifp;
1643 					}
1644 				}
1645 
1646 				key_freesp(sp);
1647 			}
1648 		}
1649 #endif /*IPSEC*/
1650 		ipstat.ips_cantfrag++;
1651 		break;
1652 
1653 	case ENOBUFS:
1654 		type = ICMP_SOURCEQUENCH;
1655 		code = 0;
1656 		break;
1657 
1658 	case EACCES:			/* ipfw denied packet */
1659 		m_freem(mcopy);
1660 		return;
1661 	}
1662 	icmp_error(mcopy, type, code, dest, destifp);
1663 }
1664 
1665 void
1666 ip_savecontrol(inp, mp, ip, m)
1667 	register struct inpcb *inp;
1668 	register struct mbuf **mp;
1669 	register struct ip *ip;
1670 	register struct mbuf *m;
1671 {
1672 	if (inp->inp_socket->so_options & SO_TIMESTAMP) {
1673 		struct timeval tv;
1674 
1675 		microtime(&tv);
1676 		*mp = sbcreatecontrol((caddr_t) &tv, sizeof(tv),
1677 			SCM_TIMESTAMP, SOL_SOCKET);
1678 		if (*mp)
1679 			mp = &(*mp)->m_next;
1680 	}
1681 	if (inp->inp_flags & INP_RECVDSTADDR) {
1682 		*mp = sbcreatecontrol((caddr_t) &ip->ip_dst,
1683 		    sizeof(struct in_addr), IP_RECVDSTADDR, IPPROTO_IP);
1684 		if (*mp)
1685 			mp = &(*mp)->m_next;
1686 	}
1687 #ifdef notyet
1688 	/* XXX
1689 	 * Moving these out of udp_input() made them even more broken
1690 	 * than they already were.
1691 	 */
1692 	/* options were tossed already */
1693 	if (inp->inp_flags & INP_RECVOPTS) {
1694 		*mp = sbcreatecontrol((caddr_t) opts_deleted_above,
1695 		    sizeof(struct in_addr), IP_RECVOPTS, IPPROTO_IP);
1696 		if (*mp)
1697 			mp = &(*mp)->m_next;
1698 	}
1699 	/* ip_srcroute doesn't do what we want here, need to fix */
1700 	if (inp->inp_flags & INP_RECVRETOPTS) {
1701 		*mp = sbcreatecontrol((caddr_t) ip_srcroute(),
1702 		    sizeof(struct in_addr), IP_RECVRETOPTS, IPPROTO_IP);
1703 		if (*mp)
1704 			mp = &(*mp)->m_next;
1705 	}
1706 #endif
1707 	if (inp->inp_flags & INP_RECVIF) {
1708 		struct ifnet *ifp;
1709 		struct sdlbuf {
1710 			struct sockaddr_dl sdl;
1711 			u_char	pad[32];
1712 		} sdlbuf;
1713 		struct sockaddr_dl *sdp;
1714 		struct sockaddr_dl *sdl2 = &sdlbuf.sdl;
1715 
1716 		if (((ifp = m->m_pkthdr.rcvif))
1717 		&& ( ifp->if_index && (ifp->if_index <= if_index))) {
1718 			sdp = (struct sockaddr_dl *)(ifnet_addrs
1719 					[ifp->if_index - 1]->ifa_addr);
1720 			/*
1721 			 * Change our mind and don't try copy.
1722 			 */
1723 			if ((sdp->sdl_family != AF_LINK)
1724 			|| (sdp->sdl_len > sizeof(sdlbuf))) {
1725 				goto makedummy;
1726 			}
1727 			bcopy(sdp, sdl2, sdp->sdl_len);
1728 		} else {
1729 makedummy:
1730 			sdl2->sdl_len
1731 				= offsetof(struct sockaddr_dl, sdl_data[0]);
1732 			sdl2->sdl_family = AF_LINK;
1733 			sdl2->sdl_index = 0;
1734 			sdl2->sdl_nlen = sdl2->sdl_alen = sdl2->sdl_slen = 0;
1735 		}
1736 		*mp = sbcreatecontrol((caddr_t) sdl2, sdl2->sdl_len,
1737 			IP_RECVIF, IPPROTO_IP);
1738 		if (*mp)
1739 			mp = &(*mp)->m_next;
1740 	}
1741 }
1742 
1743 int
1744 ip_rsvp_init(struct socket *so)
1745 {
1746 	if (so->so_type != SOCK_RAW ||
1747 	    so->so_proto->pr_protocol != IPPROTO_RSVP)
1748 	  return EOPNOTSUPP;
1749 
1750 	if (ip_rsvpd != NULL)
1751 	  return EADDRINUSE;
1752 
1753 	ip_rsvpd = so;
1754 	/*
1755 	 * This may seem silly, but we need to be sure we don't over-increment
1756 	 * the RSVP counter, in case something slips up.
1757 	 */
1758 	if (!ip_rsvp_on) {
1759 		ip_rsvp_on = 1;
1760 		rsvp_on++;
1761 	}
1762 
1763 	return 0;
1764 }
1765 
1766 int
1767 ip_rsvp_done(void)
1768 {
1769 	ip_rsvpd = NULL;
1770 	/*
1771 	 * This may seem silly, but we need to be sure we don't over-decrement
1772 	 * the RSVP counter, in case something slips up.
1773 	 */
1774 	if (ip_rsvp_on) {
1775 		ip_rsvp_on = 0;
1776 		rsvp_on--;
1777 	}
1778 	return 0;
1779 }
1780