xref: /openbsd-src/sys/netinet/ip_input.c (revision db3296cf5c1dd9058ceecc3a29fe4aaa0bd26000)
1 /*	$OpenBSD: ip_input.c,v 1.114 2003/07/29 03:21:57 itojun Exp $	*/
2 /*	$NetBSD: ip_input.c,v 1.30 1996/03/16 23:53:58 christos Exp $	*/
3 
4 /*
5  * Copyright (c) 1982, 1986, 1988, 1993
6  *	The Regents of the University of California.  All rights reserved.
7  *
8  * Redistribution and use in source and binary forms, with or without
9  * modification, are permitted provided that the following conditions
10  * are met:
11  * 1. Redistributions of source code must retain the above copyright
12  *    notice, this list of conditions and the following disclaimer.
13  * 2. Redistributions in binary form must reproduce the above copyright
14  *    notice, this list of conditions and the following disclaimer in the
15  *    documentation and/or other materials provided with the distribution.
16  * 3. Neither the name of the University nor the names of its contributors
17  *    may be used to endorse or promote products derived from this software
18  *    without specific prior written permission.
19  *
20  * THIS SOFTWARE IS PROVIDED BY THE REGENTS AND CONTRIBUTORS ``AS IS'' AND
21  * ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
22  * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE
23  * ARE DISCLAIMED.  IN NO EVENT SHALL THE REGENTS OR CONTRIBUTORS BE LIABLE
24  * FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL
25  * DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS
26  * OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION)
27  * HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT
28  * LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY
29  * OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF
30  * SUCH DAMAGE.
31  *
32  *	@(#)ip_input.c	8.2 (Berkeley) 1/4/94
33  */
34 
35 #include "pf.h"
36 
37 #include <sys/param.h>
38 #include <sys/systm.h>
39 #include <sys/mbuf.h>
40 #include <sys/domain.h>
41 #include <sys/protosw.h>
42 #include <sys/socket.h>
43 #include <sys/syslog.h>
44 #include <sys/sysctl.h>
45 
46 #include <net/if.h>
47 #include <net/if_dl.h>
48 #include <net/route.h>
49 
50 #include <netinet/in.h>
51 #include <netinet/in_systm.h>
52 #include <netinet/if_ether.h>
53 #include <netinet/ip.h>
54 #include <netinet/in_pcb.h>
55 #include <netinet/in_var.h>
56 #include <netinet/ip_var.h>
57 #include <netinet/ip_icmp.h>
58 
59 #if NPF > 0
60 #include <net/pfvar.h>
61 #endif
62 
63 #ifdef IPSEC
64 #include <netinet/ip_ipsp.h>
65 #endif /* IPSEC */
66 
67 #ifndef	IPFORWARDING
68 #ifdef GATEWAY
69 #define	IPFORWARDING	1	/* forward IP packets not for us */
70 #else /* GATEWAY */
71 #define	IPFORWARDING	0	/* don't forward IP packets not for us */
72 #endif /* GATEWAY */
73 #endif /* IPFORWARDING */
74 #ifndef	IPSENDREDIRECTS
75 #define	IPSENDREDIRECTS	1
76 #endif
77 
78 #ifndef IPMTUDISC
79 #define IPMTUDISC	1
80 #endif
81 #ifndef IPMTUDISCTIMEOUT
82 #define IPMTUDISCTIMEOUT (10 * 60)	/* as per RFC 1191 */
83 #endif
84 
85 struct ipqhead ipq;
86 
87 int encdebug = 0;
88 int ipsec_keep_invalid = IPSEC_DEFAULT_EMBRYONIC_SA_TIMEOUT;
89 int ipsec_require_pfs = IPSEC_DEFAULT_PFS;
90 int ipsec_soft_allocations = IPSEC_DEFAULT_SOFT_ALLOCATIONS;
91 int ipsec_exp_allocations = IPSEC_DEFAULT_EXP_ALLOCATIONS;
92 int ipsec_soft_bytes = IPSEC_DEFAULT_SOFT_BYTES;
93 int ipsec_exp_bytes = IPSEC_DEFAULT_EXP_BYTES;
94 int ipsec_soft_timeout = IPSEC_DEFAULT_SOFT_TIMEOUT;
95 int ipsec_exp_timeout = IPSEC_DEFAULT_EXP_TIMEOUT;
96 int ipsec_soft_first_use = IPSEC_DEFAULT_SOFT_FIRST_USE;
97 int ipsec_exp_first_use = IPSEC_DEFAULT_EXP_FIRST_USE;
98 int ipsec_expire_acquire = IPSEC_DEFAULT_EXPIRE_ACQUIRE;
99 char ipsec_def_enc[20];
100 char ipsec_def_auth[20];
101 char ipsec_def_comp[20];
102 
103 /*
104  * Note: DIRECTED_BROADCAST is handled this way so that previous
105  * configuration using this option will Just Work.
106  */
107 #ifndef IPDIRECTEDBCAST
108 #ifdef DIRECTED_BROADCAST
109 #define IPDIRECTEDBCAST	1
110 #else
111 #define	IPDIRECTEDBCAST	0
112 #endif /* DIRECTED_BROADCAST */
113 #endif /* IPDIRECTEDBCAST */
114 int	ipforwarding = IPFORWARDING;
115 int	ipsendredirects = IPSENDREDIRECTS;
116 int	ip_dosourceroute = 0;	/* no src-routing unless sysctl'd to enable */
117 int	ip_defttl = IPDEFTTL;
118 int	ip_mtudisc = IPMTUDISC;
119 u_int	ip_mtudisc_timeout = IPMTUDISCTIMEOUT;
120 int	ip_directedbcast = IPDIRECTEDBCAST;
121 #ifdef DIAGNOSTIC
122 int	ipprintfs = 0;
123 #endif
124 
125 struct rttimer_queue *ip_mtudisc_timeout_q = NULL;
126 
127 int	ipsec_auth_default_level = IPSEC_AUTH_LEVEL_DEFAULT;
128 int	ipsec_esp_trans_default_level = IPSEC_ESP_TRANS_LEVEL_DEFAULT;
129 int	ipsec_esp_network_default_level = IPSEC_ESP_NETWORK_LEVEL_DEFAULT;
130 int	ipsec_ipcomp_default_level = IPSEC_IPCOMP_LEVEL_DEFAULT;
131 
132 /* Keep track of memory used for reassembly */
133 int	ip_maxqueue = 300;
134 int	ip_frags = 0;
135 
136 /* from in_pcb.c */
137 extern int ipport_firstauto;
138 extern int ipport_lastauto;
139 extern int ipport_hifirstauto;
140 extern int ipport_hilastauto;
141 extern struct baddynamicports baddynamicports;
142 
143 extern	struct domain inetdomain;
144 extern	struct protosw inetsw[];
145 u_char	ip_protox[IPPROTO_MAX];
146 int	ipqmaxlen = IFQ_MAXLEN;
147 struct	in_ifaddrhead in_ifaddr;
148 struct	ifqueue ipintrq;
149 
150 int	ipq_locked;
151 static __inline int ipq_lock_try(void);
152 static __inline void ipq_unlock(void);
153 
154 struct pool ipqent_pool;
155 
156 struct ipstat ipstat;
157 
158 static __inline int
159 ipq_lock_try()
160 {
161 	int s;
162 
163 	s = splimp();
164 	if (ipq_locked) {
165 		splx(s);
166 		return (0);
167 	}
168 	ipq_locked = 1;
169 	splx(s);
170 	return (1);
171 }
172 
173 #define ipq_lock() ipq_lock_try()
174 
175 static __inline void
176 ipq_unlock()
177 {
178 	int s;
179 
180 	s = splimp();
181 	ipq_locked = 0;
182 	splx(s);
183 }
184 
185 char *
186 inet_ntoa(ina)
187 	struct in_addr ina;
188 {
189 	static char buf[4*sizeof "123"];
190 	unsigned char *ucp = (unsigned char *)&ina;
191 
192 	snprintf(buf, sizeof buf, "%d.%d.%d.%d",
193 	    ucp[0] & 0xff, ucp[1] & 0xff,
194 	    ucp[2] & 0xff, ucp[3] & 0xff);
195 	return (buf);
196 }
197 
198 /*
199  * We need to save the IP options in case a protocol wants to respond
200  * to an incoming packet over the same route if the packet got here
201  * using IP source routing.  This allows connection establishment and
202  * maintenance when the remote end is on a network that is not known
203  * to us.
204  */
205 int	ip_nhops = 0;
206 static	struct ip_srcrt {
207 	struct	in_addr dst;			/* final destination */
208 	char	nop;				/* one NOP to align */
209 	char	srcopt[IPOPT_OFFSET + 1];	/* OPTVAL, OLEN and OFFSET */
210 	struct	in_addr route[MAX_IPOPTLEN/sizeof(struct in_addr)];
211 } ip_srcrt;
212 
213 static void save_rte(u_char *, struct in_addr);
214 static int ip_weadvertise(u_int32_t);
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 protosw *pr;
224 	register int i;
225 	const u_int16_t defbaddynamicports_tcp[] = DEFBADDYNAMICPORTS_TCP;
226 	const u_int16_t defbaddynamicports_udp[] = DEFBADDYNAMICPORTS_UDP;
227 
228 	pool_init(&ipqent_pool, sizeof(struct ipqent), 0, 0, 0, "ipqepl",
229 	    NULL);
230 
231 	pr = pffindproto(PF_INET, IPPROTO_RAW, SOCK_RAW);
232 	if (pr == 0)
233 		panic("ip_init");
234 	for (i = 0; i < IPPROTO_MAX; i++)
235 		ip_protox[i] = pr - inetsw;
236 	for (pr = inetdomain.dom_protosw;
237 	    pr < inetdomain.dom_protoswNPROTOSW; pr++)
238 		if (pr->pr_domain->dom_family == PF_INET &&
239 		    pr->pr_protocol && pr->pr_protocol != IPPROTO_RAW)
240 			ip_protox[pr->pr_protocol] = pr - inetsw;
241 	LIST_INIT(&ipq);
242 	ipintrq.ifq_maxlen = ipqmaxlen;
243 	TAILQ_INIT(&in_ifaddr);
244 	if (ip_mtudisc != 0)
245 		ip_mtudisc_timeout_q =
246 		    rt_timer_queue_create(ip_mtudisc_timeout);
247 
248 	/* Fill in list of ports not to allocate dynamically. */
249 	bzero((void *)&baddynamicports, sizeof(baddynamicports));
250 	for (i = 0; defbaddynamicports_tcp[i] != 0; i++)
251 		DP_SET(baddynamicports.tcp, defbaddynamicports_tcp[i]);
252 	for (i = 0; defbaddynamicports_udp[i] != 0; i++)
253 		DP_SET(baddynamicports.udp, defbaddynamicports_tcp[i]);
254 
255 	strncpy(ipsec_def_enc, IPSEC_DEFAULT_DEF_ENC, sizeof(ipsec_def_enc));
256 	strncpy(ipsec_def_auth, IPSEC_DEFAULT_DEF_AUTH, sizeof(ipsec_def_auth));
257 	strncpy(ipsec_def_comp, IPSEC_DEFAULT_DEF_COMP, sizeof(ipsec_def_comp));
258 }
259 
260 struct	sockaddr_in ipaddr = { sizeof(ipaddr), AF_INET };
261 struct	route ipforward_rt;
262 
263 void
264 ipintr()
265 {
266 	struct mbuf *m;
267 	int s;
268 
269 	while (1) {
270 		/*
271 		 * Get next datagram off input queue and get IP header
272 		 * in first mbuf.
273 		 */
274 		s = splimp();
275 		IF_DEQUEUE(&ipintrq, m);
276 		splx(s);
277 		if (m == 0)
278 			return;
279 #ifdef	DIAGNOSTIC
280 		if ((m->m_flags & M_PKTHDR) == 0)
281 			panic("ipintr no HDR");
282 #endif
283 		ipv4_input(m);
284 	}
285 }
286 
287 /*
288  * Ip input routine.  Checksum and byte swap header.  If fragmented
289  * try to reassemble.  Process options.  Pass to next level.
290  */
291 void
292 ipv4_input(m)
293 	struct mbuf *m;
294 {
295 	register struct ip *ip;
296 	register struct ipq *fp;
297 	struct in_ifaddr *ia;
298 	struct ipqent *ipqe;
299 	int hlen, mff, len;
300 	in_addr_t pfrdr = 0;
301 #ifdef IPSEC
302 	int error, s;
303 	struct tdb *tdb;
304 	struct tdb_ident *tdbi;
305 	struct m_tag *mtag;
306 #endif /* IPSEC */
307 
308 	/*
309 	 * If no IP addresses have been set yet but the interfaces
310 	 * are receiving, can't do anything with incoming packets yet.
311 	 */
312 	if (in_ifaddr.tqh_first == 0)
313 		goto bad;
314 	ipstat.ips_total++;
315 	if (m->m_len < sizeof (struct ip) &&
316 	    (m = m_pullup(m, sizeof (struct ip))) == NULL) {
317 		ipstat.ips_toosmall++;
318 		return;
319 	}
320 	ip = mtod(m, struct ip *);
321 	if (ip->ip_v != IPVERSION) {
322 		ipstat.ips_badvers++;
323 		goto bad;
324 	}
325 	hlen = ip->ip_hl << 2;
326 	if (hlen < sizeof(struct ip)) {	/* minimum header length */
327 		ipstat.ips_badhlen++;
328 		goto bad;
329 	}
330 	if (hlen > m->m_len) {
331 		if ((m = m_pullup(m, hlen)) == NULL) {
332 			ipstat.ips_badhlen++;
333 			return;
334 		}
335 		ip = mtod(m, struct ip *);
336 	}
337 
338 	/* 127/8 must not appear on wire - RFC1122 */
339 	if ((ntohl(ip->ip_dst.s_addr) >> IN_CLASSA_NSHIFT) == IN_LOOPBACKNET ||
340 	    (ntohl(ip->ip_src.s_addr) >> IN_CLASSA_NSHIFT) == IN_LOOPBACKNET) {
341 		if ((m->m_pkthdr.rcvif->if_flags & IFF_LOOPBACK) == 0) {
342 			ipstat.ips_badaddr++;
343 			goto bad;
344 		}
345 	}
346 
347 	if ((m->m_pkthdr.csum & M_IPV4_CSUM_IN_OK) == 0) {
348 		if (m->m_pkthdr.csum & M_IPV4_CSUM_IN_BAD) {
349 			ipstat.ips_inhwcsum++;
350 			ipstat.ips_badsum++;
351 			goto bad;
352 		}
353 
354 		if (in_cksum(m, hlen) != 0) {
355 			ipstat.ips_badsum++;
356 			goto bad;
357 		}
358 	} else {
359 		m->m_pkthdr.csum &= ~M_IPV4_CSUM_IN_OK;
360 		ipstat.ips_inhwcsum++;
361 	}
362 
363 	/* Retrieve the packet lenght. */
364 	len = ntohs(ip->ip_len);
365 
366 	/*
367 	 * Convert fields to host representation.
368 	 */
369 	if (len < hlen) {
370 		ipstat.ips_badlen++;
371 		goto bad;
372 	}
373 
374 	/*
375 	 * Check that the amount of data in the buffers
376 	 * is at least as much as the IP header would have us expect.
377 	 * Trim mbufs if longer than we expect.
378 	 * Drop packet if shorter than we expect.
379 	 */
380 	if (m->m_pkthdr.len < len) {
381 		ipstat.ips_tooshort++;
382 		goto bad;
383 	}
384 	if (m->m_pkthdr.len > len) {
385 		if (m->m_len == m->m_pkthdr.len) {
386 			m->m_len = len;
387 			m->m_pkthdr.len = len;
388 		} else
389 			m_adj(m, len - m->m_pkthdr.len);
390 	}
391 
392 #if NPF > 0
393 	/*
394 	 * Packet filter
395 	 */
396 	pfrdr = ip->ip_dst.s_addr;
397 	if (pf_test(PF_IN, m->m_pkthdr.rcvif, &m) != PF_PASS)
398 		goto bad;
399 	if (m == NULL)
400 		return;
401 
402 	ip = mtod(m, struct ip *);
403 	hlen = ip->ip_hl << 2;
404 	pfrdr = (pfrdr != ip->ip_dst.s_addr);
405 #endif
406 
407 	/*
408 	 * Process options and, if not destined for us,
409 	 * ship it on.  ip_dooptions returns 1 when an
410 	 * error was detected (causing an icmp message
411 	 * to be sent and the original packet to be freed).
412 	 */
413 	ip_nhops = 0;		/* for source routed packets */
414 	if (hlen > sizeof (struct ip) && ip_dooptions(m)) {
415 	        return;
416 	}
417 
418 	/*
419 	 * Check our list of addresses, to see if the packet is for us.
420 	 */
421 	if ((ia = in_iawithaddr(ip->ip_dst, m)) != NULL &&
422 	    (ia->ia_ifp->if_flags & IFF_UP))
423 		goto ours;
424 
425 	if (IN_MULTICAST(ip->ip_dst.s_addr)) {
426 		struct in_multi *inm;
427 #ifdef MROUTING
428 		extern struct socket *ip_mrouter;
429 
430 		if (m->m_flags & M_EXT) {
431 			if ((m = m_pullup(m, hlen)) == NULL) {
432 				ipstat.ips_toosmall++;
433 				return;
434 			}
435 			ip = mtod(m, struct ip *);
436 		}
437 
438 		if (ip_mrouter) {
439 			/*
440 			 * If we are acting as a multicast router, all
441 			 * incoming multicast packets are passed to the
442 			 * kernel-level multicast forwarding function.
443 			 * The packet is returned (relatively) intact; if
444 			 * ip_mforward() returns a non-zero value, the packet
445 			 * must be discarded, else it may be accepted below.
446 			 *
447 			 * (The IP ident field is put in the same byte order
448 			 * as expected when ip_mforward() is called from
449 			 * ip_output().)
450 			 */
451 			if (ip_mforward(m, m->m_pkthdr.rcvif) != 0) {
452 				ipstat.ips_cantforward++;
453 				m_freem(m);
454 				return;
455 			}
456 
457 			/*
458 			 * The process-level routing demon needs to receive
459 			 * all multicast IGMP packets, whether or not this
460 			 * host belongs to their destination groups.
461 			 */
462 			if (ip->ip_p == IPPROTO_IGMP)
463 				goto ours;
464 			ipstat.ips_forward++;
465 		}
466 #endif
467 		/*
468 		 * See if we belong to the destination multicast group on the
469 		 * arrival interface.
470 		 */
471 		IN_LOOKUP_MULTI(ip->ip_dst, m->m_pkthdr.rcvif, inm);
472 		if (inm == NULL) {
473 			ipstat.ips_cantforward++;
474 			m_freem(m);
475 			return;
476 		}
477 		goto ours;
478 	}
479 	if (ip->ip_dst.s_addr == INADDR_BROADCAST ||
480 	    ip->ip_dst.s_addr == INADDR_ANY)
481 		goto ours;
482 
483 	/*
484 	 * Not for us; forward if possible and desirable.
485 	 */
486 	if (ipforwarding == 0) {
487 		ipstat.ips_cantforward++;
488 		m_freem(m);
489 	} else {
490 #ifdef IPSEC
491 	        /*
492 		 * IPsec policy check for forwarded packets. Look at
493 		 * inner-most IPsec SA used.
494 		 */
495 		mtag = m_tag_find(m, PACKET_TAG_IPSEC_IN_DONE, NULL);
496                 s = splnet();
497 		if (mtag != NULL) {
498 			tdbi = (struct tdb_ident *)(mtag + 1);
499 			tdb = gettdb(tdbi->spi, &tdbi->dst, tdbi->proto);
500 		} else
501 			tdb = NULL;
502 	        ipsp_spd_lookup(m, AF_INET, hlen, &error,
503 		    IPSP_DIRECTION_IN, tdb, NULL);
504                 splx(s);
505 
506 		/* Error or otherwise drop-packet indication */
507 		if (error) {
508 			ipstat.ips_cantforward++;
509 			m_freem(m);
510 			return;
511 		}
512 
513 		/*
514 		 * Fall through, forward packet. Outbound IPsec policy
515 		 * checking will occur in ip_output().
516 		 */
517 #endif /* IPSEC */
518 
519 		ip_forward(m, pfrdr);
520 	}
521 	return;
522 
523 ours:
524 	/*
525 	 * If offset or IP_MF are set, must reassemble.
526 	 * Otherwise, nothing need be done.
527 	 * (We could look in the reassembly queue to see
528 	 * if the packet was previously fragmented,
529 	 * but it's not worth the time; just let them time out.)
530 	 */
531 	if (ip->ip_off &~ htons(IP_DF | IP_RF)) {
532 		if (m->m_flags & M_EXT) {		/* XXX */
533 			if ((m = m_pullup(m, hlen)) == NULL) {
534 				ipstat.ips_toosmall++;
535 				return;
536 			}
537 			ip = mtod(m, struct ip *);
538 		}
539 
540 		/*
541 		 * Look for queue of fragments
542 		 * of this datagram.
543 		 */
544 		ipq_lock();
545 		for (fp = ipq.lh_first; fp != NULL; fp = fp->ipq_q.le_next)
546 			if (ip->ip_id == fp->ipq_id &&
547 			    ip->ip_src.s_addr == fp->ipq_src.s_addr &&
548 			    ip->ip_dst.s_addr == fp->ipq_dst.s_addr &&
549 			    ip->ip_p == fp->ipq_p)
550 				goto found;
551 		fp = 0;
552 found:
553 
554 		/*
555 		 * Adjust ip_len to not reflect header,
556 		 * set ipqe_mff if more fragments are expected,
557 		 * convert offset of this to bytes.
558 		 */
559 		ip->ip_len = htons(ntohs(ip->ip_len) - hlen);
560 		mff = (ip->ip_off & htons(IP_MF)) != 0;
561 		if (mff) {
562 			/*
563 			 * Make sure that fragments have a data length
564 			 * that's a non-zero multiple of 8 bytes.
565 			 */
566 			if (ntohs(ip->ip_len) == 0 ||
567 			    (ntohs(ip->ip_len) & 0x7) != 0) {
568 				ipstat.ips_badfrags++;
569 				ipq_unlock();
570 				goto bad;
571 			}
572 		}
573 		ip->ip_off = htons(ntohs(ip->ip_off) << 3);
574 
575 		/*
576 		 * If datagram marked as having more fragments
577 		 * or if this is not the first fragment,
578 		 * attempt reassembly; if it succeeds, proceed.
579 		 */
580 		if (mff || ip->ip_off) {
581 			ipstat.ips_fragments++;
582 			if (ip_frags + 1 > ip_maxqueue) {
583 				ip_flush();
584 				ipstat.ips_rcvmemdrop++;
585 				ipq_unlock();
586 				goto bad;
587 			}
588 
589 			ipqe = pool_get(&ipqent_pool, PR_NOWAIT);
590 			if (ipqe == NULL) {
591 				ipstat.ips_rcvmemdrop++;
592 				ipq_unlock();
593 				goto bad;
594 			}
595 			ip_frags++;
596 			ipqe->ipqe_mff = mff;
597 			ipqe->ipqe_m = m;
598 			ipqe->ipqe_ip = ip;
599 			m = ip_reass(ipqe, fp);
600 			if (m == 0) {
601 				ipq_unlock();
602 				return;
603 			}
604 			ipstat.ips_reassembled++;
605 			ip = mtod(m, struct ip *);
606 			hlen = ip->ip_hl << 2;
607 			ip->ip_len = htons(ntohs(ip->ip_len) + hlen);
608 		} else
609 			if (fp)
610 				ip_freef(fp);
611 		ipq_unlock();
612 	}
613 
614 #ifdef IPSEC
615         /*
616          * If it's a protected packet for us, skip the policy check.
617          * That's because we really only care about the properties of
618          * the protected packet, and not the intermediate versions.
619          * While this is not the most paranoid setting, it allows
620          * some flexibility in handling nested tunnels (in setting up
621 	 * the policies).
622          */
623         if ((ip->ip_p == IPPROTO_ESP) || (ip->ip_p == IPPROTO_AH) ||
624 	    (ip->ip_p == IPPROTO_IPCOMP))
625           goto skipipsec;
626 
627 	/*
628 	 * If the protected packet was tunneled, then we need to
629 	 * verify the protected packet's information, not the
630 	 * external headers. Thus, skip the policy lookup for the
631 	 * external packet, and keep the IPsec information linked on
632 	 * the packet header (the encapsulation routines know how
633 	 * to deal with that).
634 	 */
635 	if ((ip->ip_p == IPPROTO_IPIP) || (ip->ip_p == IPPROTO_IPV6))
636 	  goto skipipsec;
637 
638 	/*
639 	 * If the protected packet is TCP or UDP, we'll do the
640 	 * policy check in the respective input routine, so we can
641 	 * check for bypass sockets.
642 	 */
643 	if ((ip->ip_p == IPPROTO_TCP) || (ip->ip_p == IPPROTO_UDP))
644 	  goto skipipsec;
645 
646 	/*
647 	 * IPsec policy check for local-delivery packets. Look at the
648 	 * inner-most SA that protected the packet. This is in fact
649 	 * a bit too restrictive (it could end up causing packets to
650 	 * be dropped that semantically follow the policy, e.g., in
651 	 * certain SA-bundle configurations); but the alternative is
652 	 * very complicated (and requires keeping track of what
653 	 * kinds of tunneling headers have been seen in-between the
654 	 * IPsec headers), and I don't think we lose much functionality
655 	 * that's needed in the real world (who uses bundles anyway ?).
656 	 */
657 	mtag = m_tag_find(m, PACKET_TAG_IPSEC_IN_DONE, NULL);
658         s = splnet();
659 	if (mtag) {
660 		tdbi = (struct tdb_ident *)(mtag + 1);
661 	        tdb = gettdb(tdbi->spi, &tdbi->dst, tdbi->proto);
662 	} else
663 		tdb = NULL;
664 	ipsp_spd_lookup(m, AF_INET, hlen, &error, IPSP_DIRECTION_IN,
665 	    tdb, NULL);
666         splx(s);
667 
668 	/* Error or otherwise drop-packet indication. */
669 	if (error) {
670 	        ipstat.ips_cantforward++;
671 		m_freem(m);
672 		return;
673 	}
674 
675  skipipsec:
676 	/* Otherwise, just fall through and deliver the packet */
677 #endif /* IPSEC */
678 
679 	/*
680 	 * Switch out to protocol's input routine.
681 	 */
682 	ipstat.ips_delivered++;
683 	(*inetsw[ip_protox[ip->ip_p]].pr_input)(m, hlen, NULL, 0);
684 	return;
685 bad:
686 	m_freem(m);
687 }
688 
689 struct in_ifaddr *
690 in_iawithaddr(ina, m)
691 	struct in_addr ina;
692 	register struct mbuf *m;
693 {
694 	register struct in_ifaddr *ia;
695 
696 	TAILQ_FOREACH(ia, &in_ifaddr, ia_list) {
697 		if ((ina.s_addr == ia->ia_addr.sin_addr.s_addr) ||
698 		    ((ia->ia_ifp->if_flags & (IFF_LOOPBACK|IFF_LINK1)) ==
699 			(IFF_LOOPBACK|IFF_LINK1) &&
700 		     ia->ia_subnet == (ina.s_addr & ia->ia_subnetmask)))
701 			return ia;
702 		if (((ip_directedbcast == 0) || (m && ip_directedbcast &&
703 		    ia->ia_ifp == m->m_pkthdr.rcvif)) &&
704 		    (ia->ia_ifp->if_flags & IFF_BROADCAST)) {
705 			if (ina.s_addr == ia->ia_broadaddr.sin_addr.s_addr ||
706 			    ina.s_addr == ia->ia_netbroadcast.s_addr ||
707 			    /*
708 			     * Look for all-0's host part (old broadcast addr),
709 			     * either for subnet or net.
710 			     */
711 			    ina.s_addr == ia->ia_subnet ||
712 			    ina.s_addr == ia->ia_net) {
713 				/* Make sure M_BCAST is set */
714 				if (m)
715 					m->m_flags |= M_BCAST;
716 				return ia;
717 			    }
718 		}
719 	}
720 
721 	return NULL;
722 }
723 
724 /*
725  * Take incoming datagram fragment and try to
726  * reassemble it into whole datagram.  If a chain for
727  * reassembly of this datagram already exists, then it
728  * is given as fp; otherwise have to make a chain.
729  */
730 struct mbuf *
731 ip_reass(ipqe, fp)
732 	struct ipqent *ipqe;
733 	struct ipq *fp;
734 {
735 	struct mbuf *m = ipqe->ipqe_m;
736 	struct ipqent *nq, *p, *q;
737 	struct ip *ip;
738 	struct mbuf *t;
739 	int hlen = ipqe->ipqe_ip->ip_hl << 2;
740 	int i, next;
741 	u_int8_t ecn, ecn0;
742 
743 	/*
744 	 * Presence of header sizes in mbufs
745 	 * would confuse code below.
746 	 */
747 	m->m_data += hlen;
748 	m->m_len -= hlen;
749 
750 	/*
751 	 * If first fragment to arrive, create a reassembly queue.
752 	 */
753 	if (fp == 0) {
754 		MALLOC(fp, struct ipq *, sizeof (struct ipq),
755 		    M_FTABLE, M_NOWAIT);
756 		if (fp == NULL)
757 			goto dropfrag;
758 		LIST_INSERT_HEAD(&ipq, fp, ipq_q);
759 		fp->ipq_ttl = IPFRAGTTL;
760 		fp->ipq_p = ipqe->ipqe_ip->ip_p;
761 		fp->ipq_id = ipqe->ipqe_ip->ip_id;
762 		LIST_INIT(&fp->ipq_fragq);
763 		fp->ipq_src = ipqe->ipqe_ip->ip_src;
764 		fp->ipq_dst = ipqe->ipqe_ip->ip_dst;
765 		p = NULL;
766 		goto insert;
767 	}
768 
769 	/*
770 	 * Handle ECN by comparing this segment with the first one;
771 	 * if CE is set, do not lose CE.
772 	 * drop if CE and not-ECT are mixed for the same packet.
773 	 */
774 	ecn = ipqe->ipqe_ip->ip_tos & IPTOS_ECN_MASK;
775 	ecn0 = fp->ipq_fragq.lh_first->ipqe_ip->ip_tos & IPTOS_ECN_MASK;
776 	if (ecn == IPTOS_ECN_CE) {
777 		if (ecn0 == IPTOS_ECN_NOTECT)
778 			goto dropfrag;
779 		if (ecn0 != IPTOS_ECN_CE)
780 			fp->ipq_fragq.lh_first->ipqe_ip->ip_tos |= IPTOS_ECN_CE;
781 	}
782 	if (ecn == IPTOS_ECN_NOTECT && ecn0 != IPTOS_ECN_NOTECT)
783 		goto dropfrag;
784 
785 	/*
786 	 * Find a segment which begins after this one does.
787 	 */
788 	for (p = NULL, q = fp->ipq_fragq.lh_first; q != NULL;
789 	    p = q, q = q->ipqe_q.le_next)
790 		if (ntohs(q->ipqe_ip->ip_off) > ntohs(ipqe->ipqe_ip->ip_off))
791 			break;
792 
793 	/*
794 	 * If there is a preceding segment, it may provide some of
795 	 * our data already.  If so, drop the data from the incoming
796 	 * segment.  If it provides all of our data, drop us.
797 	 */
798 	if (p != NULL) {
799 		i = ntohs(p->ipqe_ip->ip_off) + ntohs(p->ipqe_ip->ip_len) -
800 		    ntohs(ipqe->ipqe_ip->ip_off);
801 		if (i > 0) {
802 			if (i >= ntohs(ipqe->ipqe_ip->ip_len))
803 				goto dropfrag;
804 			m_adj(ipqe->ipqe_m, i);
805 			ipqe->ipqe_ip->ip_off =
806 			    htons(ntohs(ipqe->ipqe_ip->ip_off) + i);
807 			ipqe->ipqe_ip->ip_len =
808 			    htons(ntohs(ipqe->ipqe_ip->ip_len) - i);
809 		}
810 	}
811 
812 	/*
813 	 * While we overlap succeeding segments trim them or,
814 	 * if they are completely covered, dequeue them.
815 	 */
816 	for (; q != NULL &&
817 	    ntohs(ipqe->ipqe_ip->ip_off) + ntohs(ipqe->ipqe_ip->ip_len) >
818 	    ntohs(q->ipqe_ip->ip_off); q = nq) {
819 		i = (ntohs(ipqe->ipqe_ip->ip_off) +
820 		    ntohs(ipqe->ipqe_ip->ip_len)) - ntohs(q->ipqe_ip->ip_off);
821 		if (i < ntohs(q->ipqe_ip->ip_len)) {
822 			q->ipqe_ip->ip_len =
823 			    htons(ntohs(q->ipqe_ip->ip_len) - i);
824 			q->ipqe_ip->ip_off =
825 			    htons(ntohs(q->ipqe_ip->ip_off) + i);
826 			m_adj(q->ipqe_m, i);
827 			break;
828 		}
829 		nq = q->ipqe_q.le_next;
830 		m_freem(q->ipqe_m);
831 		LIST_REMOVE(q, ipqe_q);
832 		pool_put(&ipqent_pool, q);
833 		ip_frags--;
834 	}
835 
836 insert:
837 	/*
838 	 * Stick new segment in its place;
839 	 * check for complete reassembly.
840 	 */
841 	if (p == NULL) {
842 		LIST_INSERT_HEAD(&fp->ipq_fragq, ipqe, ipqe_q);
843 	} else {
844 		LIST_INSERT_AFTER(p, ipqe, ipqe_q);
845 	}
846 	next = 0;
847 	for (p = NULL, q = fp->ipq_fragq.lh_first; q != NULL;
848 	    p = q, q = q->ipqe_q.le_next) {
849 		if (ntohs(q->ipqe_ip->ip_off) != next)
850 			return (0);
851 		next += ntohs(q->ipqe_ip->ip_len);
852 	}
853 	if (p->ipqe_mff)
854 		return (0);
855 
856 	/*
857 	 * Reassembly is complete.  Check for a bogus message size and
858 	 * concatenate fragments.
859 	 */
860 	q = fp->ipq_fragq.lh_first;
861 	ip = q->ipqe_ip;
862 	if ((next + (ip->ip_hl << 2)) > IP_MAXPACKET) {
863 		ipstat.ips_toolong++;
864 		ip_freef(fp);
865 		return (0);
866 	}
867 	m = q->ipqe_m;
868 	t = m->m_next;
869 	m->m_next = 0;
870 	m_cat(m, t);
871 	nq = q->ipqe_q.le_next;
872 	pool_put(&ipqent_pool, q);
873 	ip_frags--;
874 	for (q = nq; q != NULL; q = nq) {
875 		t = q->ipqe_m;
876 		nq = q->ipqe_q.le_next;
877 		pool_put(&ipqent_pool, q);
878 		ip_frags--;
879 		m_cat(m, t);
880 	}
881 
882 	/*
883 	 * Create header for new ip packet by
884 	 * modifying header of first packet;
885 	 * dequeue and discard fragment reassembly header.
886 	 * Make header visible.
887 	 */
888 	ip->ip_len = htons(next);
889 	ip->ip_src = fp->ipq_src;
890 	ip->ip_dst = fp->ipq_dst;
891 	LIST_REMOVE(fp, ipq_q);
892 	FREE(fp, M_FTABLE);
893 	m->m_len += (ip->ip_hl << 2);
894 	m->m_data -= (ip->ip_hl << 2);
895 	/* some debugging cruft by sklower, below, will go away soon */
896 	if (m->m_flags & M_PKTHDR) { /* XXX this should be done elsewhere */
897 		int plen = 0;
898 		for (t = m; t; t = t->m_next)
899 			plen += t->m_len;
900 		m->m_pkthdr.len = plen;
901 	}
902 	return (m);
903 
904 dropfrag:
905 	ipstat.ips_fragdropped++;
906 	m_freem(m);
907 	pool_put(&ipqent_pool, ipqe);
908 	ip_frags--;
909 	return (0);
910 }
911 
912 /*
913  * Free a fragment reassembly header and all
914  * associated datagrams.
915  */
916 void
917 ip_freef(fp)
918 	struct ipq *fp;
919 {
920 	register struct ipqent *q, *p;
921 
922 	for (q = fp->ipq_fragq.lh_first; q != NULL; q = p) {
923 		p = q->ipqe_q.le_next;
924 		m_freem(q->ipqe_m);
925 		LIST_REMOVE(q, ipqe_q);
926 		pool_put(&ipqent_pool, q);
927 		ip_frags--;
928 	}
929 	LIST_REMOVE(fp, ipq_q);
930 	FREE(fp, M_FTABLE);
931 }
932 
933 /*
934  * IP timer processing;
935  * if a timer expires on a reassembly
936  * queue, discard it.
937  */
938 void
939 ip_slowtimo()
940 {
941 	register struct ipq *fp, *nfp;
942 	int s = splsoftnet();
943 
944 	ipq_lock();
945 	for (fp = ipq.lh_first; fp != NULL; fp = nfp) {
946 		nfp = fp->ipq_q.le_next;
947 		if (--fp->ipq_ttl == 0) {
948 			ipstat.ips_fragtimeout++;
949 			ip_freef(fp);
950 		}
951 	}
952 	ipq_unlock();
953 	splx(s);
954 }
955 
956 /*
957  * Drain off all datagram fragments.
958  */
959 void
960 ip_drain()
961 {
962 
963 	if (ipq_lock_try() == 0)
964 		return;
965 	while (ipq.lh_first != NULL) {
966 		ipstat.ips_fragdropped++;
967 		ip_freef(ipq.lh_first);
968 	}
969 	ipq_unlock();
970 }
971 
972 /*
973  * Flush a bunch of datagram fragments, till we are down to 75%.
974  */
975 void
976 ip_flush()
977 {
978 	int max = 50;
979 
980 	/* ipq already locked */
981 	while (ipq.lh_first != NULL && ip_frags > ip_maxqueue * 3 / 4 && --max) {
982 		ipstat.ips_fragdropped++;
983 		ip_freef(ipq.lh_first);
984 	}
985 }
986 
987 /*
988  * Do option processing on a datagram,
989  * possibly discarding it if bad options are encountered,
990  * or forwarding it if source-routed.
991  * Returns 1 if packet has been forwarded/freed,
992  * 0 if the packet should be processed further.
993  */
994 int
995 ip_dooptions(m)
996 	struct mbuf *m;
997 {
998 	register struct ip *ip = mtod(m, struct ip *);
999 	register u_char *cp;
1000 	struct ip_timestamp ipt;
1001 	register struct in_ifaddr *ia;
1002 	int opt, optlen, cnt, off, code, type = ICMP_PARAMPROB, forward = 0;
1003 	struct in_addr sin, dst;
1004 	n_time ntime;
1005 
1006 	dst = ip->ip_dst;
1007 	cp = (u_char *)(ip + 1);
1008 	cnt = (ip->ip_hl << 2) - sizeof (struct ip);
1009 
1010 	for (; cnt > 0; cnt -= optlen, cp += optlen) {
1011 		opt = cp[IPOPT_OPTVAL];
1012 		if (opt == IPOPT_EOL)
1013 			break;
1014 		if (opt == IPOPT_NOP)
1015 			optlen = 1;
1016 		else {
1017 			if (cnt < IPOPT_OLEN + sizeof(*cp)) {
1018 				code = &cp[IPOPT_OLEN] - (u_char *)ip;
1019 				goto bad;
1020 			}
1021 			optlen = cp[IPOPT_OLEN];
1022 			if (optlen < IPOPT_OLEN + sizeof(*cp) || optlen > cnt) {
1023 				code = &cp[IPOPT_OLEN] - (u_char *)ip;
1024 				goto bad;
1025 			}
1026 		}
1027 
1028 		switch (opt) {
1029 
1030 		default:
1031 			break;
1032 
1033 		/*
1034 		 * Source routing with record.
1035 		 * Find interface with current destination address.
1036 		 * If none on this machine then drop if strictly routed,
1037 		 * or do nothing if loosely routed.
1038 		 * Record interface address and bring up next address
1039 		 * component.  If strictly routed make sure next
1040 		 * address is on directly accessible net.
1041 		 */
1042 		case IPOPT_LSRR:
1043 		case IPOPT_SSRR:
1044 			if (!ip_dosourceroute) {
1045 				char buf[4*sizeof "123"];
1046 
1047 				strlcpy(buf, inet_ntoa(ip->ip_dst),
1048 				    sizeof buf);
1049 				log(LOG_WARNING,
1050 				    "attempted source route from %s to %s\n",
1051 				    inet_ntoa(ip->ip_src), buf);
1052 				type = ICMP_UNREACH;
1053 				code = ICMP_UNREACH_SRCFAIL;
1054 				goto bad;
1055 			}
1056 			if ((off = cp[IPOPT_OFFSET]) < IPOPT_MINOFF) {
1057 				code = &cp[IPOPT_OFFSET] - (u_char *)ip;
1058 				goto bad;
1059 			}
1060 			ipaddr.sin_addr = ip->ip_dst;
1061 			ia = ifatoia(ifa_ifwithaddr(sintosa(&ipaddr)));
1062 			if (ia == 0) {
1063 				if (opt == IPOPT_SSRR) {
1064 					type = ICMP_UNREACH;
1065 					code = ICMP_UNREACH_SRCFAIL;
1066 					goto bad;
1067 				}
1068 				/*
1069 				 * Loose routing, and not at next destination
1070 				 * yet; nothing to do except forward.
1071 				 */
1072 				break;
1073 			}
1074 			off--;			/* 0 origin */
1075 			if ((off + sizeof(struct in_addr)) > optlen) {
1076 				/*
1077 				 * End of source route.  Should be for us.
1078 				 */
1079 				save_rte(cp, ip->ip_src);
1080 				break;
1081 			}
1082 
1083 			/*
1084 			 * locate outgoing interface
1085 			 */
1086 			bcopy((caddr_t)(cp + off), (caddr_t)&ipaddr.sin_addr,
1087 			    sizeof(ipaddr.sin_addr));
1088 			if (opt == IPOPT_SSRR) {
1089 #define	INA	struct in_ifaddr *
1090 #define	SA	struct sockaddr *
1091 			    if ((ia = (INA)ifa_ifwithdstaddr((SA)&ipaddr)) == 0)
1092 				ia = (INA)ifa_ifwithnet((SA)&ipaddr);
1093 			} else
1094 				ia = ip_rtaddr(ipaddr.sin_addr);
1095 			if (ia == 0) {
1096 				type = ICMP_UNREACH;
1097 				code = ICMP_UNREACH_SRCFAIL;
1098 				goto bad;
1099 			}
1100 			ip->ip_dst = ipaddr.sin_addr;
1101 			bcopy((caddr_t)&ia->ia_addr.sin_addr,
1102 			    (caddr_t)(cp + off), sizeof(struct in_addr));
1103 			cp[IPOPT_OFFSET] += sizeof(struct in_addr);
1104 			/*
1105 			 * Let ip_intr's mcast routing check handle mcast pkts
1106 			 */
1107 			forward = !IN_MULTICAST(ip->ip_dst.s_addr);
1108 			break;
1109 
1110 		case IPOPT_RR:
1111 			if (optlen < IPOPT_OFFSET + sizeof(*cp)) {
1112 				code = &cp[IPOPT_OLEN] - (u_char *)ip;
1113 				goto bad;
1114 			}
1115 			if ((off = cp[IPOPT_OFFSET]) < IPOPT_MINOFF) {
1116 				code = &cp[IPOPT_OFFSET] - (u_char *)ip;
1117 				goto bad;
1118 			}
1119 
1120 			/*
1121 			 * If no space remains, ignore.
1122 			 */
1123 			off--;			/* 0 origin */
1124 			if ((off + sizeof(struct in_addr)) > optlen)
1125 				break;
1126 			bcopy((caddr_t)(&ip->ip_dst), (caddr_t)&ipaddr.sin_addr,
1127 			    sizeof(ipaddr.sin_addr));
1128 			/*
1129 			 * locate outgoing interface; if we're the destination,
1130 			 * use the incoming interface (should be same).
1131 			 */
1132 			if ((ia = (INA)ifa_ifwithaddr((SA)&ipaddr)) == 0 &&
1133 			    (ia = ip_rtaddr(ipaddr.sin_addr)) == 0) {
1134 				type = ICMP_UNREACH;
1135 				code = ICMP_UNREACH_HOST;
1136 				goto bad;
1137 			}
1138 			bcopy((caddr_t)&ia->ia_addr.sin_addr,
1139 			    (caddr_t)(cp + off), sizeof(struct in_addr));
1140 			cp[IPOPT_OFFSET] += sizeof(struct in_addr);
1141 			break;
1142 
1143 		case IPOPT_TS:
1144 			code = cp - (u_char *)ip;
1145 			bcopy(cp, &ipt, sizeof(struct ip_timestamp));
1146 			if (ipt.ipt_ptr < 5 || ipt.ipt_len < 5)
1147 				goto bad;
1148 			if (ipt.ipt_ptr - 1 + sizeof(n_time) > ipt.ipt_len) {
1149 				if (++ipt.ipt_oflw == 0)
1150 					goto bad;
1151 				break;
1152 			}
1153 			bcopy(cp + ipt.ipt_ptr - 1, &sin, sizeof sin);
1154 			switch (ipt.ipt_flg) {
1155 
1156 			case IPOPT_TS_TSONLY:
1157 				break;
1158 
1159 			case IPOPT_TS_TSANDADDR:
1160 				if (ipt.ipt_ptr - 1 + sizeof(n_time) +
1161 				    sizeof(struct in_addr) > ipt.ipt_len)
1162 					goto bad;
1163 				ipaddr.sin_addr = dst;
1164 				ia = (INA)ifaof_ifpforaddr((SA)&ipaddr,
1165 							    m->m_pkthdr.rcvif);
1166 				if (ia == 0)
1167 					continue;
1168 				bcopy((caddr_t)&ia->ia_addr.sin_addr,
1169 				    (caddr_t)&sin, sizeof(struct in_addr));
1170 				ipt.ipt_ptr += sizeof(struct in_addr);
1171 				break;
1172 
1173 			case IPOPT_TS_PRESPEC:
1174 				if (ipt.ipt_ptr - 1 + sizeof(n_time) +
1175 				    sizeof(struct in_addr) > ipt.ipt_len)
1176 					goto bad;
1177 				bcopy((caddr_t)&sin, (caddr_t)&ipaddr.sin_addr,
1178 				    sizeof(struct in_addr));
1179 				if (ifa_ifwithaddr((SA)&ipaddr) == 0)
1180 					continue;
1181 				ipt.ipt_ptr += sizeof(struct in_addr);
1182 				break;
1183 
1184 			default:
1185 				/* XXX can't take &ipt->ipt_flg */
1186 				code = (u_char *)&ipt.ipt_ptr -
1187 				    (u_char *)ip + 1;
1188 				goto bad;
1189 			}
1190 			ntime = iptime();
1191 			bcopy((caddr_t)&ntime, (caddr_t)cp + ipt.ipt_ptr - 1,
1192 			    sizeof(n_time));
1193 			ipt.ipt_ptr += sizeof(n_time);
1194 		}
1195 	}
1196 	if (forward && ipforwarding) {
1197 		ip_forward(m, 1);
1198 		return (1);
1199 	}
1200 	return (0);
1201 bad:
1202 	icmp_error(m, type, code, 0, 0);
1203 	ipstat.ips_badoptions++;
1204 	return (1);
1205 }
1206 
1207 /*
1208  * Given address of next destination (final or next hop),
1209  * return internet address info of interface to be used to get there.
1210  */
1211 struct in_ifaddr *
1212 ip_rtaddr(dst)
1213 	 struct in_addr dst;
1214 {
1215 	register struct sockaddr_in *sin;
1216 
1217 	sin = satosin(&ipforward_rt.ro_dst);
1218 
1219 	if (ipforward_rt.ro_rt == 0 || dst.s_addr != sin->sin_addr.s_addr) {
1220 		if (ipforward_rt.ro_rt) {
1221 			RTFREE(ipforward_rt.ro_rt);
1222 			ipforward_rt.ro_rt = 0;
1223 		}
1224 		sin->sin_family = AF_INET;
1225 		sin->sin_len = sizeof(*sin);
1226 		sin->sin_addr = dst;
1227 
1228 		rtalloc(&ipforward_rt);
1229 	}
1230 	if (ipforward_rt.ro_rt == 0)
1231 		return ((struct in_ifaddr *)0);
1232 	return (ifatoia(ipforward_rt.ro_rt->rt_ifa));
1233 }
1234 
1235 /*
1236  * Save incoming source route for use in replies,
1237  * to be picked up later by ip_srcroute if the receiver is interested.
1238  */
1239 void
1240 save_rte(option, dst)
1241 	u_char *option;
1242 	struct in_addr dst;
1243 {
1244 	unsigned olen;
1245 
1246 	olen = option[IPOPT_OLEN];
1247 #ifdef DIAGNOSTIC
1248 	if (ipprintfs)
1249 		printf("save_rte: olen %d\n", olen);
1250 #endif /* 0 */
1251 	if (olen > sizeof(ip_srcrt) - (1 + sizeof(dst)))
1252 		return;
1253 	bcopy((caddr_t)option, (caddr_t)ip_srcrt.srcopt, olen);
1254 	ip_nhops = (olen - IPOPT_OFFSET - 1) / sizeof(struct in_addr);
1255 	ip_srcrt.dst = dst;
1256 }
1257 
1258 /*
1259  * Check whether we do proxy ARP for this address and we point to ourselves.
1260  * Code shamelessly copied from arplookup().
1261  */
1262 static int
1263 ip_weadvertise(addr)
1264 	u_int32_t addr;
1265 {
1266 	register struct rtentry *rt;
1267 	register struct ifnet *ifp;
1268 	register struct ifaddr *ifa;
1269 	struct sockaddr_inarp sin;
1270 
1271 	sin.sin_len = sizeof(sin);
1272 	sin.sin_family = AF_INET;
1273 	sin.sin_addr.s_addr = addr;
1274 	sin.sin_other = SIN_PROXY;
1275 	rt = rtalloc1(sintosa(&sin), 0);
1276 	if (rt == 0)
1277 		return 0;
1278 
1279 	if ((rt->rt_flags & RTF_GATEWAY) || (rt->rt_flags & RTF_LLINFO) == 0 ||
1280 	    rt->rt_gateway->sa_family != AF_LINK) {
1281 		RTFREE(rt);
1282 		return 0;
1283 	}
1284 
1285 	for (ifp = ifnet.tqh_first; ifp != 0; ifp = ifp->if_list.tqe_next)
1286 		for (ifa = ifp->if_addrlist.tqh_first; ifa != 0;
1287 		    ifa = ifa->ifa_list.tqe_next) {
1288 			if (ifa->ifa_addr->sa_family != rt->rt_gateway->sa_family)
1289 				continue;
1290 
1291 			if (!bcmp(LLADDR((struct sockaddr_dl *)ifa->ifa_addr),
1292 			    LLADDR((struct sockaddr_dl *)rt->rt_gateway),
1293 			    ETHER_ADDR_LEN)) {
1294 				RTFREE(rt);
1295 				return 1;
1296 			}
1297 		}
1298 
1299 	RTFREE(rt);
1300 	return 0;
1301 }
1302 
1303 /*
1304  * Retrieve incoming source route for use in replies,
1305  * in the same form used by setsockopt.
1306  * The first hop is placed before the options, will be removed later.
1307  */
1308 struct mbuf *
1309 ip_srcroute()
1310 {
1311 	register struct in_addr *p, *q;
1312 	register struct mbuf *m;
1313 
1314 	if (ip_nhops == 0)
1315 		return ((struct mbuf *)0);
1316 	m = m_get(M_DONTWAIT, MT_SOOPTS);
1317 	if (m == 0)
1318 		return ((struct mbuf *)0);
1319 
1320 #define OPTSIZ	(sizeof(ip_srcrt.nop) + sizeof(ip_srcrt.srcopt))
1321 
1322 	/* length is (nhops+1)*sizeof(addr) + sizeof(nop + srcrt header) */
1323 	m->m_len = ip_nhops * sizeof(struct in_addr) + sizeof(struct in_addr) +
1324 	    OPTSIZ;
1325 #ifdef DIAGNOSTIC
1326 	if (ipprintfs)
1327 		printf("ip_srcroute: nhops %d mlen %d", ip_nhops, m->m_len);
1328 #endif
1329 
1330 	/*
1331 	 * First save first hop for return route
1332 	 */
1333 	p = &ip_srcrt.route[ip_nhops - 1];
1334 	*(mtod(m, struct in_addr *)) = *p--;
1335 #ifdef DIAGNOSTIC
1336 	if (ipprintfs)
1337 		printf(" hops %x", ntohl(mtod(m, struct in_addr *)->s_addr));
1338 #endif
1339 
1340 	/*
1341 	 * Copy option fields and padding (nop) to mbuf.
1342 	 */
1343 	ip_srcrt.nop = IPOPT_NOP;
1344 	ip_srcrt.srcopt[IPOPT_OFFSET] = IPOPT_MINOFF;
1345 	bcopy((caddr_t)&ip_srcrt.nop,
1346 	    mtod(m, caddr_t) + sizeof(struct in_addr), OPTSIZ);
1347 	q = (struct in_addr *)(mtod(m, caddr_t) +
1348 	    sizeof(struct in_addr) + OPTSIZ);
1349 #undef OPTSIZ
1350 	/*
1351 	 * Record return path as an IP source route,
1352 	 * reversing the path (pointers are now aligned).
1353 	 */
1354 	while (p >= ip_srcrt.route) {
1355 #ifdef DIAGNOSTIC
1356 		if (ipprintfs)
1357 			printf(" %x", ntohl(q->s_addr));
1358 #endif
1359 		*q++ = *p--;
1360 	}
1361 	/*
1362 	 * Last hop goes to final destination.
1363 	 */
1364 	*q = ip_srcrt.dst;
1365 #ifdef DIAGNOSTIC
1366 	if (ipprintfs)
1367 		printf(" %x\n", ntohl(q->s_addr));
1368 #endif
1369 	return (m);
1370 }
1371 
1372 /*
1373  * Strip out IP options, at higher
1374  * level protocol in the kernel.
1375  * Second argument is buffer to which options
1376  * will be moved, and return value is their length.
1377  * XXX should be deleted; last arg currently ignored.
1378  */
1379 void
1380 ip_stripoptions(m, mopt)
1381 	register struct mbuf *m;
1382 	struct mbuf *mopt;
1383 {
1384 	register int i;
1385 	struct ip *ip = mtod(m, struct ip *);
1386 	register caddr_t opts;
1387 	int olen;
1388 
1389 	olen = (ip->ip_hl<<2) - sizeof (struct ip);
1390 	opts = (caddr_t)(ip + 1);
1391 	i = m->m_len - (sizeof (struct ip) + olen);
1392 	bcopy(opts  + olen, opts, (unsigned)i);
1393 	m->m_len -= olen;
1394 	if (m->m_flags & M_PKTHDR)
1395 		m->m_pkthdr.len -= olen;
1396 	ip->ip_hl = sizeof(struct ip) >> 2;
1397 }
1398 
1399 int inetctlerrmap[PRC_NCMDS] = {
1400 	0,		0,		0,		0,
1401 	0,		EMSGSIZE,	EHOSTDOWN,	EHOSTUNREACH,
1402 	EHOSTUNREACH,	EHOSTUNREACH,	ECONNREFUSED,	ECONNREFUSED,
1403 	EMSGSIZE,	EHOSTUNREACH,	0,		0,
1404 	0,		0,		0,		0,
1405 	ENOPROTOOPT
1406 };
1407 
1408 /*
1409  * Forward a packet.  If some error occurs return the sender
1410  * an icmp packet.  Note we can't always generate a meaningful
1411  * icmp message because icmp doesn't have a large enough repertoire
1412  * of codes and types.
1413  *
1414  * If not forwarding, just drop the packet.  This could be confusing
1415  * if ipforwarding was zero but some routing protocol was advancing
1416  * us as a gateway to somewhere.  However, we must let the routing
1417  * protocol deal with that.
1418  *
1419  * The srcrt parameter indicates whether the packet is being forwarded
1420  * via a source route.
1421  */
1422 void
1423 ip_forward(m, srcrt)
1424 	struct mbuf *m;
1425 	int srcrt;
1426 {
1427 	register struct ip *ip = mtod(m, struct ip *);
1428 	register struct sockaddr_in *sin;
1429 	register struct rtentry *rt;
1430 	int error, type = 0, code = 0;
1431 	struct mbuf *mcopy;
1432 	n_long dest;
1433 	struct ifnet *destifp;
1434 #ifdef IPSEC
1435 	struct ifnet dummyifp;
1436 #endif
1437 
1438 	dest = 0;
1439 #ifdef DIAGNOSTIC
1440 	if (ipprintfs)
1441 		printf("forward: src %x dst %x ttl %x\n", ip->ip_src.s_addr,
1442 		    ip->ip_dst.s_addr, ip->ip_ttl);
1443 #endif
1444 	if (m->m_flags & M_BCAST || in_canforward(ip->ip_dst) == 0) {
1445 		ipstat.ips_cantforward++;
1446 		m_freem(m);
1447 		return;
1448 	}
1449 	if (ip->ip_ttl <= IPTTLDEC) {
1450 		icmp_error(m, ICMP_TIMXCEED, ICMP_TIMXCEED_INTRANS, dest, 0);
1451 		return;
1452 	}
1453 	ip->ip_ttl -= IPTTLDEC;
1454 
1455 	sin = satosin(&ipforward_rt.ro_dst);
1456 	if ((rt = ipforward_rt.ro_rt) == 0 ||
1457 	    ip->ip_dst.s_addr != sin->sin_addr.s_addr) {
1458 		if (ipforward_rt.ro_rt) {
1459 			RTFREE(ipforward_rt.ro_rt);
1460 			ipforward_rt.ro_rt = 0;
1461 		}
1462 		sin->sin_family = AF_INET;
1463 		sin->sin_len = sizeof(*sin);
1464 		sin->sin_addr = ip->ip_dst;
1465 
1466 		rtalloc(&ipforward_rt);
1467 		if (ipforward_rt.ro_rt == 0) {
1468 			icmp_error(m, ICMP_UNREACH, ICMP_UNREACH_HOST, dest, 0);
1469 			return;
1470 		}
1471 		rt = ipforward_rt.ro_rt;
1472 	}
1473 
1474 	/*
1475 	 * Save at most 68 bytes of the packet in case
1476 	 * we need to generate an ICMP message to the src.
1477 	 * Pullup to avoid sharing mbuf cluster between m and mcopy.
1478 	 */
1479 	mcopy = m_copym(m, 0, imin(ntohs(ip->ip_len), 68), M_DONTWAIT);
1480 	if (mcopy)
1481 		mcopy = m_pullup(mcopy, ip->ip_hl << 2);
1482 
1483 	/*
1484 	 * If forwarding packet using same interface that it came in on,
1485 	 * perhaps should send a redirect to sender to shortcut a hop.
1486 	 * Only send redirect if source is sending directly to us,
1487 	 * and if packet was not source routed (or has any options).
1488 	 * Also, don't send redirect if forwarding using a default route
1489 	 * or a route modified by a redirect.
1490 	 * Don't send redirect if we advertise destination's arp address
1491 	 * as ours (proxy arp).
1492 	 */
1493 	if (rt->rt_ifp == m->m_pkthdr.rcvif &&
1494 	    (rt->rt_flags & (RTF_DYNAMIC|RTF_MODIFIED)) == 0 &&
1495 	    satosin(rt_key(rt))->sin_addr.s_addr != 0 &&
1496 	    ipsendredirects && !srcrt &&
1497 	    !ip_weadvertise(satosin(rt_key(rt))->sin_addr.s_addr)) {
1498 		if (rt->rt_ifa &&
1499 		    (ip->ip_src.s_addr & ifatoia(rt->rt_ifa)->ia_subnetmask) ==
1500 		    ifatoia(rt->rt_ifa)->ia_subnet) {
1501 		    if (rt->rt_flags & RTF_GATEWAY)
1502 			dest = satosin(rt->rt_gateway)->sin_addr.s_addr;
1503 		    else
1504 			dest = ip->ip_dst.s_addr;
1505 		    /* Router requirements says to only send host redirects */
1506 		    type = ICMP_REDIRECT;
1507 		    code = ICMP_REDIRECT_HOST;
1508 #ifdef DIAGNOSTIC
1509 		    if (ipprintfs)
1510 			printf("redirect (%d) to %x\n", code, (u_int32_t)dest);
1511 #endif
1512 		}
1513 	}
1514 
1515 	error = ip_output(m, (struct mbuf *)0, &ipforward_rt,
1516 	    (IP_FORWARDING | (ip_directedbcast ? IP_ALLOWBROADCAST : 0)),
1517 	    0, (void *)NULL, (void *)NULL);
1518 	if (error)
1519 		ipstat.ips_cantforward++;
1520 	else {
1521 		ipstat.ips_forward++;
1522 		if (type)
1523 			ipstat.ips_redirectsent++;
1524 		else {
1525 			if (mcopy)
1526 				m_freem(mcopy);
1527 			return;
1528 		}
1529 	}
1530 	if (mcopy == NULL)
1531 		return;
1532 	destifp = NULL;
1533 
1534 	switch (error) {
1535 
1536 	case 0:				/* forwarded, but need redirect */
1537 		/* type, code set above */
1538 		break;
1539 
1540 	case ENETUNREACH:		/* shouldn't happen, checked above */
1541 	case EHOSTUNREACH:
1542 	case ENETDOWN:
1543 	case EHOSTDOWN:
1544 	default:
1545 		type = ICMP_UNREACH;
1546 		code = ICMP_UNREACH_HOST;
1547 		break;
1548 
1549 	case EMSGSIZE:
1550 		type = ICMP_UNREACH;
1551 		code = ICMP_UNREACH_NEEDFRAG;
1552 
1553 #ifdef IPSEC
1554 		if (ipforward_rt.ro_rt) {
1555 			struct rtentry *rt = ipforward_rt.ro_rt;
1556 			destifp = ipforward_rt.ro_rt->rt_ifp;
1557 			/*
1558 			 * XXX BUG ALERT
1559 			 * The "dummyifp" code relies upon the fact
1560 			 * that icmp_error() touches only ifp->if_mtu.
1561 			 */
1562 			if (rt->rt_rmx.rmx_mtu) {
1563 				dummyifp.if_mtu = rt->rt_rmx.rmx_mtu;
1564 				destifp = &dummyifp;
1565 			}
1566 		}
1567 #endif /*IPSEC*/
1568 		ipstat.ips_cantfrag++;
1569 		break;
1570 
1571 	case ENOBUFS:
1572 #if 1
1573 		/*
1574 		 * a router should not generate ICMP_SOURCEQUENCH as
1575 		 * required in RFC1812 Requirements for IP Version 4 Routers.
1576 		 * source quench could be a big problem under DoS attacks,
1577 		 * or the underlying interface is rate-limited.
1578 		 */
1579 		if (mcopy)
1580 			m_freem(mcopy);
1581 		return;
1582 #else
1583 		type = ICMP_SOURCEQUENCH;
1584 		code = 0;
1585 		break;
1586 #endif
1587 	}
1588 
1589 	icmp_error(mcopy, type, code, dest, destifp);
1590 }
1591 
1592 int
1593 ip_sysctl(name, namelen, oldp, oldlenp, newp, newlen)
1594 	int *name;
1595 	u_int namelen;
1596 	void *oldp;
1597 	size_t *oldlenp;
1598 	void *newp;
1599 	size_t newlen;
1600 {
1601 	int error;
1602 
1603 	/* All sysctl names at this level are terminal. */
1604 	if (namelen != 1)
1605 		return (ENOTDIR);
1606 
1607 	switch (name[0]) {
1608 	case IPCTL_FORWARDING:
1609 		return (sysctl_int(oldp, oldlenp, newp, newlen, &ipforwarding));
1610 	case IPCTL_SENDREDIRECTS:
1611 		return (sysctl_int(oldp, oldlenp, newp, newlen,
1612 			&ipsendredirects));
1613 	case IPCTL_DEFTTL:
1614 		return (sysctl_int(oldp, oldlenp, newp, newlen, &ip_defttl));
1615 #ifdef notyet
1616 	case IPCTL_DEFMTU:
1617 		return (sysctl_int(oldp, oldlenp, newp, newlen, &ip_mtu));
1618 #endif
1619 	case IPCTL_SOURCEROUTE:
1620 		/*
1621 		 * Don't allow this to change in a secure environment.
1622 		 */
1623 		if (newp && securelevel > 0)
1624 			return (EPERM);
1625 		return (sysctl_int(oldp, oldlenp, newp, newlen,
1626 		    &ip_dosourceroute));
1627 	case IPCTL_DIRECTEDBCAST:
1628 		return (sysctl_int(oldp, oldlenp, newp, newlen,
1629 		    &ip_directedbcast));
1630 	case IPCTL_MTUDISC:
1631 		error = sysctl_int(oldp, oldlenp, newp, newlen,
1632 		    &ip_mtudisc);
1633 		if (ip_mtudisc != 0 && ip_mtudisc_timeout_q == NULL) {
1634 			ip_mtudisc_timeout_q =
1635 			    rt_timer_queue_create(ip_mtudisc_timeout);
1636 		} else if (ip_mtudisc == 0 && ip_mtudisc_timeout_q != NULL) {
1637 			rt_timer_queue_destroy(ip_mtudisc_timeout_q, TRUE);
1638 			Free(ip_mtudisc_timeout_q);
1639 			ip_mtudisc_timeout_q = NULL;
1640 		}
1641 		return error;
1642 	case IPCTL_MTUDISCTIMEOUT:
1643 		error = sysctl_int(oldp, oldlenp, newp, newlen,
1644 		   &ip_mtudisc_timeout);
1645 		if (ip_mtudisc_timeout_q != NULL)
1646 			rt_timer_queue_change(ip_mtudisc_timeout_q,
1647 					      ip_mtudisc_timeout);
1648 		return (error);
1649 	case IPCTL_IPPORT_FIRSTAUTO:
1650 		return (sysctl_int(oldp, oldlenp, newp, newlen,
1651 		    &ipport_firstauto));
1652 	case IPCTL_IPPORT_LASTAUTO:
1653 		return (sysctl_int(oldp, oldlenp, newp, newlen,
1654 		    &ipport_lastauto));
1655 	case IPCTL_IPPORT_HIFIRSTAUTO:
1656 		return (sysctl_int(oldp, oldlenp, newp, newlen,
1657 		    &ipport_hifirstauto));
1658 	case IPCTL_IPPORT_HILASTAUTO:
1659 		return (sysctl_int(oldp, oldlenp, newp, newlen,
1660 		    &ipport_hilastauto));
1661 	case IPCTL_IPPORT_MAXQUEUE:
1662 		return (sysctl_int(oldp, oldlenp, newp, newlen,
1663 		    &ip_maxqueue));
1664 	case IPCTL_ENCDEBUG:
1665 		return (sysctl_int(oldp, oldlenp, newp, newlen, &encdebug));
1666 	case IPCTL_IPSEC_EMBRYONIC_SA_TIMEOUT:
1667 		return (sysctl_int(oldp, oldlenp, newp, newlen,
1668 				   &ipsec_keep_invalid));
1669 	case IPCTL_IPSEC_REQUIRE_PFS:
1670 		return (sysctl_int(oldp, oldlenp, newp, newlen,
1671 				   &ipsec_require_pfs));
1672 	case IPCTL_IPSEC_SOFT_ALLOCATIONS:
1673 		return (sysctl_int(oldp, oldlenp, newp, newlen,
1674 				   &ipsec_soft_allocations));
1675 	case IPCTL_IPSEC_ALLOCATIONS:
1676 		return (sysctl_int(oldp, oldlenp, newp, newlen,
1677 				   &ipsec_exp_allocations));
1678 	case IPCTL_IPSEC_SOFT_BYTES:
1679 		return (sysctl_int(oldp, oldlenp, newp, newlen,
1680 				   &ipsec_soft_bytes));
1681 	case IPCTL_IPSEC_BYTES:
1682 		return (sysctl_int(oldp, oldlenp, newp, newlen,
1683 				   &ipsec_exp_bytes));
1684 	case IPCTL_IPSEC_TIMEOUT:
1685 		return (sysctl_int(oldp, oldlenp, newp, newlen,
1686 				   &ipsec_exp_timeout));
1687 	case IPCTL_IPSEC_SOFT_TIMEOUT:
1688 		return (sysctl_int(oldp, oldlenp, newp, newlen,
1689 				   &ipsec_soft_timeout));
1690 	case IPCTL_IPSEC_SOFT_FIRSTUSE:
1691 		return (sysctl_int(oldp, oldlenp, newp, newlen,
1692 				   &ipsec_soft_first_use));
1693 	case IPCTL_IPSEC_FIRSTUSE:
1694 		return (sysctl_int(oldp, oldlenp, newp, newlen,
1695 				   &ipsec_exp_first_use));
1696 	case IPCTL_IPSEC_ENC_ALGORITHM:
1697 	        return (sysctl_tstring(oldp, oldlenp, newp, newlen,
1698 				       ipsec_def_enc, sizeof(ipsec_def_enc)));
1699 	case IPCTL_IPSEC_AUTH_ALGORITHM:
1700 	        return (sysctl_tstring(oldp, oldlenp, newp, newlen,
1701 				       ipsec_def_auth,
1702 				       sizeof(ipsec_def_auth)));
1703 	case IPCTL_IPSEC_EXPIRE_ACQUIRE:
1704 	        return (sysctl_int(oldp, oldlenp, newp, newlen,
1705 				   &ipsec_expire_acquire));
1706 	case IPCTL_IPSEC_IPCOMP_ALGORITHM:
1707 	        return (sysctl_tstring(oldp, oldlenp, newp, newlen,
1708 				       ipsec_def_comp,
1709 				       sizeof(ipsec_def_comp)));
1710 	default:
1711 		return (EOPNOTSUPP);
1712 	}
1713 	/* NOTREACHED */
1714 }
1715