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