xref: /freebsd/sys/netinet/ip_input.c (revision eea7c61590ae8968b3f1f609cf0bc8633222a94f)
1 /*-
2  * SPDX-License-Identifier: BSD-3-Clause
3  *
4  * Copyright (c) 1982, 1986, 1988, 1993
5  *	The Regents of the University of California.  All rights reserved.
6  *
7  * Redistribution and use in source and binary forms, with or without
8  * modification, are permitted provided that the following conditions
9  * are met:
10  * 1. Redistributions of source code must retain the above copyright
11  *    notice, this list of conditions and the following disclaimer.
12  * 2. Redistributions in binary form must reproduce the above copyright
13  *    notice, this list of conditions and the following disclaimer in the
14  *    documentation and/or other materials provided with the distribution.
15  * 3. Neither the name of the University nor the names of its contributors
16  *    may be used to endorse or promote products derived from this software
17  *    without specific prior written permission.
18  *
19  * THIS SOFTWARE IS PROVIDED BY THE REGENTS AND CONTRIBUTORS ``AS IS'' AND
20  * ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
21  * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE
22  * ARE DISCLAIMED.  IN NO EVENT SHALL THE REGENTS OR CONTRIBUTORS BE LIABLE
23  * FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL
24  * DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS
25  * OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION)
26  * HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT
27  * LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY
28  * OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF
29  * SUCH DAMAGE.
30  *
31  *	@(#)ip_input.c	8.2 (Berkeley) 1/4/94
32  */
33 
34 #include <sys/cdefs.h>
35 __FBSDID("$FreeBSD$");
36 
37 #include "opt_bootp.h"
38 #include "opt_ipstealth.h"
39 #include "opt_ipsec.h"
40 #include "opt_route.h"
41 #include "opt_rss.h"
42 
43 #include <sys/param.h>
44 #include <sys/systm.h>
45 #include <sys/hhook.h>
46 #include <sys/mbuf.h>
47 #include <sys/malloc.h>
48 #include <sys/domain.h>
49 #include <sys/protosw.h>
50 #include <sys/socket.h>
51 #include <sys/time.h>
52 #include <sys/kernel.h>
53 #include <sys/lock.h>
54 #include <sys/rmlock.h>
55 #include <sys/rwlock.h>
56 #include <sys/sdt.h>
57 #include <sys/syslog.h>
58 #include <sys/sysctl.h>
59 
60 #include <net/if.h>
61 #include <net/if_types.h>
62 #include <net/if_var.h>
63 #include <net/if_dl.h>
64 #include <net/pfil.h>
65 #include <net/route.h>
66 #include <net/route/nhop.h>
67 #include <net/netisr.h>
68 #include <net/rss_config.h>
69 #include <net/vnet.h>
70 
71 #include <netinet/in.h>
72 #include <netinet/in_kdtrace.h>
73 #include <netinet/in_systm.h>
74 #include <netinet/in_var.h>
75 #include <netinet/ip.h>
76 #include <netinet/in_fib.h>
77 #include <netinet/in_pcb.h>
78 #include <netinet/ip_var.h>
79 #include <netinet/ip_fw.h>
80 #include <netinet/ip_icmp.h>
81 #include <netinet/ip_options.h>
82 #include <machine/in_cksum.h>
83 #include <netinet/ip_carp.h>
84 #include <netinet/in_rss.h>
85 #include <netinet/ip_mroute.h>
86 
87 #include <netipsec/ipsec_support.h>
88 
89 #include <sys/socketvar.h>
90 
91 #include <security/mac/mac_framework.h>
92 
93 #ifdef CTASSERT
94 CTASSERT(sizeof(struct ip) == 20);
95 #endif
96 
97 /* IP reassembly functions are defined in ip_reass.c. */
98 extern void ipreass_init(void);
99 extern void ipreass_drain(void);
100 extern void ipreass_slowtimo(void);
101 #ifdef VIMAGE
102 extern void ipreass_destroy(void);
103 #endif
104 
105 VNET_DEFINE(int, rsvp_on);
106 
107 VNET_DEFINE(int, ipforwarding);
108 SYSCTL_INT(_net_inet_ip, IPCTL_FORWARDING, forwarding, CTLFLAG_VNET | CTLFLAG_RW,
109     &VNET_NAME(ipforwarding), 0,
110     "Enable IP forwarding between interfaces");
111 
112 /*
113  * Respond with an ICMP host redirect when we forward a packet out of
114  * the same interface on which it was received.  See RFC 792.
115  */
116 VNET_DEFINE(int, ipsendredirects) = 1;
117 SYSCTL_INT(_net_inet_ip, IPCTL_SENDREDIRECTS, redirect, CTLFLAG_VNET | CTLFLAG_RW,
118     &VNET_NAME(ipsendredirects), 0,
119     "Enable sending IP redirects");
120 
121 VNET_DEFINE_STATIC(bool, ip_strong_es) = false;
122 #define	V_ip_strong_es	VNET(ip_strong_es)
123 SYSCTL_BOOL(_net_inet_ip, OID_AUTO, rfc1122_strong_es,
124     CTLFLAG_VNET | CTLFLAG_RW, &VNET_NAME(ip_strong_es), false,
125     "Packet's IP destination address must match address on arrival interface");
126 
127 VNET_DEFINE_STATIC(bool, ip_sav) = true;
128 #define	V_ip_sav	VNET(ip_sav)
129 SYSCTL_BOOL(_net_inet_ip, OID_AUTO, source_address_validation,
130     CTLFLAG_VNET | CTLFLAG_RW, &VNET_NAME(ip_sav), true,
131     "Drop incoming packets with source address that is a local address");
132 
133 VNET_DEFINE(pfil_head_t, inet_pfil_head);	/* Packet filter hooks */
134 
135 static struct netisr_handler ip_nh = {
136 	.nh_name = "ip",
137 	.nh_handler = ip_input,
138 	.nh_proto = NETISR_IP,
139 #ifdef	RSS
140 	.nh_m2cpuid = rss_soft_m2cpuid_v4,
141 	.nh_policy = NETISR_POLICY_CPU,
142 	.nh_dispatch = NETISR_DISPATCH_HYBRID,
143 #else
144 	.nh_policy = NETISR_POLICY_FLOW,
145 #endif
146 };
147 
148 #ifdef	RSS
149 /*
150  * Directly dispatched frames are currently assumed
151  * to have a flowid already calculated.
152  *
153  * It should likely have something that assert it
154  * actually has valid flow details.
155  */
156 static struct netisr_handler ip_direct_nh = {
157 	.nh_name = "ip_direct",
158 	.nh_handler = ip_direct_input,
159 	.nh_proto = NETISR_IP_DIRECT,
160 	.nh_m2cpuid = rss_soft_m2cpuid_v4,
161 	.nh_policy = NETISR_POLICY_CPU,
162 	.nh_dispatch = NETISR_DISPATCH_HYBRID,
163 };
164 #endif
165 
166 extern	struct domain inetdomain;
167 extern	struct protosw inetsw[];
168 u_char	ip_protox[IPPROTO_MAX];
169 VNET_DEFINE(struct in_ifaddrhead, in_ifaddrhead);  /* first inet address */
170 VNET_DEFINE(struct in_ifaddrhashhead *, in_ifaddrhashtbl); /* inet addr hash table  */
171 VNET_DEFINE(u_long, in_ifaddrhmask);		/* mask for hash table */
172 
173 /* Make sure it is safe to use hashinit(9) on CK_LIST. */
174 CTASSERT(sizeof(struct in_ifaddrhashhead) == sizeof(LIST_HEAD(, in_addr)));
175 
176 #ifdef IPCTL_DEFMTU
177 SYSCTL_INT(_net_inet_ip, IPCTL_DEFMTU, mtu, CTLFLAG_RW,
178     &ip_mtu, 0, "Default MTU");
179 #endif
180 
181 #ifdef IPSTEALTH
182 VNET_DEFINE(int, ipstealth);
183 SYSCTL_INT(_net_inet_ip, OID_AUTO, stealth, CTLFLAG_VNET | CTLFLAG_RW,
184     &VNET_NAME(ipstealth), 0,
185     "IP stealth mode, no TTL decrementation on forwarding");
186 #endif
187 
188 /*
189  * IP statistics are stored in the "array" of counter(9)s.
190  */
191 VNET_PCPUSTAT_DEFINE(struct ipstat, ipstat);
192 VNET_PCPUSTAT_SYSINIT(ipstat);
193 SYSCTL_VNET_PCPUSTAT(_net_inet_ip, IPCTL_STATS, stats, struct ipstat, ipstat,
194     "IP statistics (struct ipstat, netinet/ip_var.h)");
195 
196 #ifdef VIMAGE
197 VNET_PCPUSTAT_SYSUNINIT(ipstat);
198 #endif /* VIMAGE */
199 
200 /*
201  * Kernel module interface for updating ipstat.  The argument is an index
202  * into ipstat treated as an array.
203  */
204 void
205 kmod_ipstat_inc(int statnum)
206 {
207 
208 	counter_u64_add(VNET(ipstat)[statnum], 1);
209 }
210 
211 void
212 kmod_ipstat_dec(int statnum)
213 {
214 
215 	counter_u64_add(VNET(ipstat)[statnum], -1);
216 }
217 
218 static int
219 sysctl_netinet_intr_queue_maxlen(SYSCTL_HANDLER_ARGS)
220 {
221 	int error, qlimit;
222 
223 	netisr_getqlimit(&ip_nh, &qlimit);
224 	error = sysctl_handle_int(oidp, &qlimit, 0, req);
225 	if (error || !req->newptr)
226 		return (error);
227 	if (qlimit < 1)
228 		return (EINVAL);
229 	return (netisr_setqlimit(&ip_nh, qlimit));
230 }
231 SYSCTL_PROC(_net_inet_ip, IPCTL_INTRQMAXLEN, intr_queue_maxlen,
232     CTLTYPE_INT | CTLFLAG_RW | CTLFLAG_MPSAFE, 0, 0,
233     sysctl_netinet_intr_queue_maxlen, "I",
234     "Maximum size of the IP input queue");
235 
236 static int
237 sysctl_netinet_intr_queue_drops(SYSCTL_HANDLER_ARGS)
238 {
239 	u_int64_t qdrops_long;
240 	int error, qdrops;
241 
242 	netisr_getqdrops(&ip_nh, &qdrops_long);
243 	qdrops = qdrops_long;
244 	error = sysctl_handle_int(oidp, &qdrops, 0, req);
245 	if (error || !req->newptr)
246 		return (error);
247 	if (qdrops != 0)
248 		return (EINVAL);
249 	netisr_clearqdrops(&ip_nh);
250 	return (0);
251 }
252 
253 SYSCTL_PROC(_net_inet_ip, IPCTL_INTRQDROPS, intr_queue_drops,
254     CTLTYPE_INT | CTLFLAG_RD | CTLFLAG_MPSAFE,
255     0, 0, sysctl_netinet_intr_queue_drops, "I",
256     "Number of packets dropped from the IP input queue");
257 
258 #ifdef	RSS
259 static int
260 sysctl_netinet_intr_direct_queue_maxlen(SYSCTL_HANDLER_ARGS)
261 {
262 	int error, qlimit;
263 
264 	netisr_getqlimit(&ip_direct_nh, &qlimit);
265 	error = sysctl_handle_int(oidp, &qlimit, 0, req);
266 	if (error || !req->newptr)
267 		return (error);
268 	if (qlimit < 1)
269 		return (EINVAL);
270 	return (netisr_setqlimit(&ip_direct_nh, qlimit));
271 }
272 SYSCTL_PROC(_net_inet_ip, IPCTL_INTRDQMAXLEN, intr_direct_queue_maxlen,
273     CTLTYPE_INT | CTLFLAG_RW | CTLFLAG_MPSAFE,
274     0, 0, sysctl_netinet_intr_direct_queue_maxlen,
275     "I", "Maximum size of the IP direct input queue");
276 
277 static int
278 sysctl_netinet_intr_direct_queue_drops(SYSCTL_HANDLER_ARGS)
279 {
280 	u_int64_t qdrops_long;
281 	int error, qdrops;
282 
283 	netisr_getqdrops(&ip_direct_nh, &qdrops_long);
284 	qdrops = qdrops_long;
285 	error = sysctl_handle_int(oidp, &qdrops, 0, req);
286 	if (error || !req->newptr)
287 		return (error);
288 	if (qdrops != 0)
289 		return (EINVAL);
290 	netisr_clearqdrops(&ip_direct_nh);
291 	return (0);
292 }
293 
294 SYSCTL_PROC(_net_inet_ip, IPCTL_INTRDQDROPS, intr_direct_queue_drops,
295     CTLTYPE_INT | CTLFLAG_RD | CTLFLAG_MPSAFE, 0, 0,
296     sysctl_netinet_intr_direct_queue_drops, "I",
297     "Number of packets dropped from the IP direct input queue");
298 #endif	/* RSS */
299 
300 /*
301  * IP initialization: fill in IP protocol switch table.
302  * All protocols not implemented in kernel go to raw IP protocol handler.
303  */
304 static void
305 ip_vnet_init(void *arg __unused)
306 {
307 	struct pfil_head_args args;
308 
309 	CK_STAILQ_INIT(&V_in_ifaddrhead);
310 	V_in_ifaddrhashtbl = hashinit(INADDR_NHASH, M_IFADDR, &V_in_ifaddrhmask);
311 
312 	/* Initialize IP reassembly queue. */
313 	ipreass_init();
314 
315 	/* Initialize packet filter hooks. */
316 	args.pa_version = PFIL_VERSION;
317 	args.pa_flags = PFIL_IN | PFIL_OUT;
318 	args.pa_type = PFIL_TYPE_IP4;
319 	args.pa_headname = PFIL_INET_NAME;
320 	V_inet_pfil_head = pfil_head_register(&args);
321 
322 	if (hhook_head_register(HHOOK_TYPE_IPSEC_IN, AF_INET,
323 	    &V_ipsec_hhh_in[HHOOK_IPSEC_INET],
324 	    HHOOK_WAITOK | HHOOK_HEADISINVNET) != 0)
325 		printf("%s: WARNING: unable to register input helper hook\n",
326 		    __func__);
327 	if (hhook_head_register(HHOOK_TYPE_IPSEC_OUT, AF_INET,
328 	    &V_ipsec_hhh_out[HHOOK_IPSEC_INET],
329 	    HHOOK_WAITOK | HHOOK_HEADISINVNET) != 0)
330 		printf("%s: WARNING: unable to register output helper hook\n",
331 		    __func__);
332 
333 #ifdef VIMAGE
334 	netisr_register_vnet(&ip_nh);
335 #ifdef	RSS
336 	netisr_register_vnet(&ip_direct_nh);
337 #endif
338 #endif
339 }
340 VNET_SYSINIT(ip_vnet_init, SI_SUB_PROTO_DOMAIN, SI_ORDER_FOURTH,
341     ip_vnet_init, NULL);
342 
343 
344 static void
345 ip_init(const void *unused __unused)
346 {
347 	struct protosw *pr;
348 
349 	pr = pffindproto(PF_INET, IPPROTO_RAW, SOCK_RAW);
350 	KASSERT(pr, ("%s: PF_INET not found", __func__));
351 
352 	/* Initialize the entire ip_protox[] array to IPPROTO_RAW. */
353 	for (int i = 0; i < IPPROTO_MAX; i++)
354 		ip_protox[i] = pr - inetsw;
355 	/*
356 	 * Cycle through IP protocols and put them into the appropriate place
357 	 * in ip_protox[].
358 	 */
359 	for (pr = inetdomain.dom_protosw;
360 	    pr < inetdomain.dom_protoswNPROTOSW; pr++)
361 		if (pr->pr_domain->dom_family == PF_INET &&
362 		    pr->pr_protocol && pr->pr_protocol != IPPROTO_RAW) {
363 			/* Be careful to only index valid IP protocols. */
364 			if (pr->pr_protocol < IPPROTO_MAX)
365 				ip_protox[pr->pr_protocol] = pr - inetsw;
366 		}
367 
368 	netisr_register(&ip_nh);
369 #ifdef	RSS
370 	netisr_register(&ip_direct_nh);
371 #endif
372 }
373 SYSINIT(ip_init, SI_SUB_PROTO_DOMAIN, SI_ORDER_THIRD, ip_init, NULL);
374 
375 #ifdef VIMAGE
376 static void
377 ip_destroy(void *unused __unused)
378 {
379 	int error;
380 
381 #ifdef	RSS
382 	netisr_unregister_vnet(&ip_direct_nh);
383 #endif
384 	netisr_unregister_vnet(&ip_nh);
385 
386 	pfil_head_unregister(V_inet_pfil_head);
387 	error = hhook_head_deregister(V_ipsec_hhh_in[HHOOK_IPSEC_INET]);
388 	if (error != 0) {
389 		printf("%s: WARNING: unable to deregister input helper hook "
390 		    "type HHOOK_TYPE_IPSEC_IN, id HHOOK_IPSEC_INET: "
391 		    "error %d returned\n", __func__, error);
392 	}
393 	error = hhook_head_deregister(V_ipsec_hhh_out[HHOOK_IPSEC_INET]);
394 	if (error != 0) {
395 		printf("%s: WARNING: unable to deregister output helper hook "
396 		    "type HHOOK_TYPE_IPSEC_OUT, id HHOOK_IPSEC_INET: "
397 		    "error %d returned\n", __func__, error);
398 	}
399 
400 	/* Remove the IPv4 addresses from all interfaces. */
401 	in_ifscrub_all();
402 
403 	/* Make sure the IPv4 routes are gone as well. */
404 	rib_flush_routes_family(AF_INET);
405 
406 	/* Destroy IP reassembly queue. */
407 	ipreass_destroy();
408 
409 	/* Cleanup in_ifaddr hash table; should be empty. */
410 	hashdestroy(V_in_ifaddrhashtbl, M_IFADDR, V_in_ifaddrhmask);
411 }
412 
413 VNET_SYSUNINIT(ip, SI_SUB_PROTO_DOMAIN, SI_ORDER_THIRD, ip_destroy, NULL);
414 #endif
415 
416 #ifdef	RSS
417 /*
418  * IP direct input routine.
419  *
420  * This is called when reinjecting completed fragments where
421  * all of the previous checking and book-keeping has been done.
422  */
423 void
424 ip_direct_input(struct mbuf *m)
425 {
426 	struct ip *ip;
427 	int hlen;
428 
429 	ip = mtod(m, struct ip *);
430 	hlen = ip->ip_hl << 2;
431 
432 #if defined(IPSEC) || defined(IPSEC_SUPPORT)
433 	if (IPSEC_ENABLED(ipv4)) {
434 		if (IPSEC_INPUT(ipv4, m, hlen, ip->ip_p) != 0)
435 			return;
436 	}
437 #endif /* IPSEC */
438 	IPSTAT_INC(ips_delivered);
439 	(*inetsw[ip_protox[ip->ip_p]].pr_input)(&m, &hlen, ip->ip_p);
440 	return;
441 }
442 #endif
443 
444 /*
445  * Ip input routine.  Checksum and byte swap header.  If fragmented
446  * try to reassemble.  Process options.  Pass to next level.
447  */
448 void
449 ip_input(struct mbuf *m)
450 {
451 	MROUTER_RLOCK_TRACKER;
452 	struct ip *ip = NULL;
453 	struct in_ifaddr *ia = NULL;
454 	struct ifaddr *ifa;
455 	struct ifnet *ifp;
456 	int hlen = 0;
457 	uint16_t sum, ip_len;
458 	int dchg = 0;				/* dest changed after fw */
459 	struct in_addr odst;			/* original dst address */
460 	bool strong_es;
461 
462 	M_ASSERTPKTHDR(m);
463 	NET_EPOCH_ASSERT();
464 
465 	if (m->m_flags & M_FASTFWD_OURS) {
466 		m->m_flags &= ~M_FASTFWD_OURS;
467 		/* Set up some basics that will be used later. */
468 		ip = mtod(m, struct ip *);
469 		hlen = ip->ip_hl << 2;
470 		ip_len = ntohs(ip->ip_len);
471 		goto ours;
472 	}
473 
474 	IPSTAT_INC(ips_total);
475 
476 	if (__predict_false(m->m_pkthdr.len < sizeof(struct ip)))
477 		goto tooshort;
478 
479 	if (m->m_len < sizeof(struct ip)) {
480 		m = m_pullup(m, sizeof(struct ip));
481 		if (__predict_false(m == NULL)) {
482 			IPSTAT_INC(ips_toosmall);
483 			return;
484 		}
485 	}
486 	ip = mtod(m, struct ip *);
487 
488 	if (__predict_false(ip->ip_v != IPVERSION)) {
489 		IPSTAT_INC(ips_badvers);
490 		goto bad;
491 	}
492 
493 	hlen = ip->ip_hl << 2;
494 	if (__predict_false(hlen < sizeof(struct ip))) {	/* minimum header length */
495 		IPSTAT_INC(ips_badhlen);
496 		goto bad;
497 	}
498 	if (hlen > m->m_len) {
499 		m = m_pullup(m, hlen);
500 		if (__predict_false(m == NULL)) {
501 			IPSTAT_INC(ips_badhlen);
502 			return;
503 		}
504 		ip = mtod(m, struct ip *);
505 	}
506 
507 	IP_PROBE(receive, NULL, NULL, ip, m->m_pkthdr.rcvif, ip, NULL);
508 
509 	/* IN_LOOPBACK must not appear on the wire - RFC1122 */
510 	ifp = m->m_pkthdr.rcvif;
511 	if (IN_LOOPBACK(ntohl(ip->ip_dst.s_addr)) ||
512 	    IN_LOOPBACK(ntohl(ip->ip_src.s_addr))) {
513 		if ((ifp->if_flags & IFF_LOOPBACK) == 0) {
514 			IPSTAT_INC(ips_badaddr);
515 			goto bad;
516 		}
517 	}
518 
519 	if (m->m_pkthdr.csum_flags & CSUM_IP_CHECKED) {
520 		sum = !(m->m_pkthdr.csum_flags & CSUM_IP_VALID);
521 	} else {
522 		if (hlen == sizeof(struct ip)) {
523 			sum = in_cksum_hdr(ip);
524 		} else {
525 			sum = in_cksum(m, hlen);
526 		}
527 	}
528 	if (__predict_false(sum)) {
529 		IPSTAT_INC(ips_badsum);
530 		goto bad;
531 	}
532 
533 #ifdef ALTQ
534 	if (altq_input != NULL && (*altq_input)(m, AF_INET) == 0)
535 		/* packet is dropped by traffic conditioner */
536 		return;
537 #endif
538 
539 	ip_len = ntohs(ip->ip_len);
540 	if (__predict_false(ip_len < hlen)) {
541 		IPSTAT_INC(ips_badlen);
542 		goto bad;
543 	}
544 
545 	/*
546 	 * Check that the amount of data in the buffers
547 	 * is as at least much as the IP header would have us expect.
548 	 * Trim mbufs if longer than we expect.
549 	 * Drop packet if shorter than we expect.
550 	 */
551 	if (__predict_false(m->m_pkthdr.len < ip_len)) {
552 tooshort:
553 		IPSTAT_INC(ips_tooshort);
554 		goto bad;
555 	}
556 	if (m->m_pkthdr.len > ip_len) {
557 		if (m->m_len == m->m_pkthdr.len) {
558 			m->m_len = ip_len;
559 			m->m_pkthdr.len = ip_len;
560 		} else
561 			m_adj(m, ip_len - m->m_pkthdr.len);
562 	}
563 
564 	/*
565 	 * Try to forward the packet, but if we fail continue.
566 	 * ip_tryforward() may generate redirects these days.
567 	 * XXX the logic below falling through to normal processing
568 	 * if redirects are required should be revisited as well.
569 	 * ip_tryforward() does inbound and outbound packet firewall
570 	 * processing. If firewall has decided that destination becomes
571 	 * our local address, it sets M_FASTFWD_OURS flag. In this
572 	 * case skip another inbound firewall processing and update
573 	 * ip pointer.
574 	 */
575 	if (V_ipforwarding != 0
576 #if defined(IPSEC) || defined(IPSEC_SUPPORT)
577 	    && (!IPSEC_ENABLED(ipv4) ||
578 	    IPSEC_CAPS(ipv4, m, IPSEC_CAP_OPERABLE) == 0)
579 #endif
580 	    ) {
581 		/*
582 		 * ip_dooptions() was run so we can ignore the source route (or
583 		 * any IP options case) case for redirects in ip_tryforward().
584 		 */
585 		if ((m = ip_tryforward(m)) == NULL)
586 			return;
587 		if (m->m_flags & M_FASTFWD_OURS) {
588 			m->m_flags &= ~M_FASTFWD_OURS;
589 			ip = mtod(m, struct ip *);
590 			goto ours;
591 		}
592 	}
593 
594 #if defined(IPSEC) || defined(IPSEC_SUPPORT)
595 	/*
596 	 * Bypass packet filtering for packets previously handled by IPsec.
597 	 */
598 	if (IPSEC_ENABLED(ipv4) &&
599 	    IPSEC_CAPS(ipv4, m, IPSEC_CAP_BYPASS_FILTER) != 0)
600 			goto passin;
601 #endif
602 
603 	/*
604 	 * Run through list of hooks for input packets.
605 	 *
606 	 * NB: Beware of the destination address changing (e.g.
607 	 *     by NAT rewriting).  When this happens, tell
608 	 *     ip_forward to do the right thing.
609 	 */
610 
611 	/* Jump over all PFIL processing if hooks are not active. */
612 	if (!PFIL_HOOKED_IN(V_inet_pfil_head))
613 		goto passin;
614 
615 	odst = ip->ip_dst;
616 	if (pfil_run_hooks(V_inet_pfil_head, &m, ifp, PFIL_IN, NULL) !=
617 	    PFIL_PASS)
618 		return;
619 	if (m == NULL)			/* consumed by filter */
620 		return;
621 
622 	ip = mtod(m, struct ip *);
623 	dchg = (odst.s_addr != ip->ip_dst.s_addr);
624 
625 	if (m->m_flags & M_FASTFWD_OURS) {
626 		m->m_flags &= ~M_FASTFWD_OURS;
627 		goto ours;
628 	}
629 	if (m->m_flags & M_IP_NEXTHOP) {
630 		if (m_tag_find(m, PACKET_TAG_IPFORWARD, NULL) != NULL) {
631 			/*
632 			 * Directly ship the packet on.  This allows
633 			 * forwarding packets originally destined to us
634 			 * to some other directly connected host.
635 			 */
636 			ip_forward(m, 1);
637 			return;
638 		}
639 	}
640 passin:
641 
642 	/*
643 	 * Process options and, if not destined for us,
644 	 * ship it on.  ip_dooptions returns 1 when an
645 	 * error was detected (causing an icmp message
646 	 * to be sent and the original packet to be freed).
647 	 */
648 	if (hlen > sizeof (struct ip) && ip_dooptions(m, 0))
649 		return;
650 
651         /* greedy RSVP, snatches any PATH packet of the RSVP protocol and no
652          * matter if it is destined to another node, or whether it is
653          * a multicast one, RSVP wants it! and prevents it from being forwarded
654          * anywhere else. Also checks if the rsvp daemon is running before
655 	 * grabbing the packet.
656          */
657 	if (ip->ip_p == IPPROTO_RSVP && V_rsvp_on)
658 		goto ours;
659 
660 	/*
661 	 * Check our list of addresses, to see if the packet is for us.
662 	 * If we don't have any addresses, assume any unicast packet
663 	 * we receive might be for us (and let the upper layers deal
664 	 * with it).
665 	 */
666 	if (CK_STAILQ_EMPTY(&V_in_ifaddrhead) &&
667 	    (m->m_flags & (M_MCAST|M_BCAST)) == 0)
668 		goto ours;
669 
670 	/*
671 	 * Enable a consistency check between the destination address
672 	 * and the arrival interface for a unicast packet (the RFC 1122
673 	 * strong ES model) with a list of additional predicates:
674 	 * - if IP forwarding is disabled
675 	 * - the packet is not locally generated
676 	 * - the packet is not subject to 'ipfw fwd'
677 	 * - Interface is not running CARP. If the packet got here, we already
678 	 *   checked it with carp_iamatch() and carp_forus().
679 	 */
680 	strong_es = V_ip_strong_es && (V_ipforwarding == 0) &&
681 	    ((ifp->if_flags & IFF_LOOPBACK) == 0) &&
682 	    ifp->if_carp == NULL && (dchg == 0);
683 
684 	/*
685 	 * Check for exact addresses in the hash bucket.
686 	 */
687 	CK_LIST_FOREACH(ia, INADDR_HASH(ip->ip_dst.s_addr), ia_hash) {
688 		if (IA_SIN(ia)->sin_addr.s_addr != ip->ip_dst.s_addr)
689 			continue;
690 
691 		/*
692 		 * net.inet.ip.rfc1122_strong_es: the address matches, verify
693 		 * that the packet arrived via the correct interface.
694 		 */
695 		if (__predict_false(strong_es && ia->ia_ifp != ifp)) {
696 			IPSTAT_INC(ips_badaddr);
697 			goto bad;
698 		}
699 
700 		/*
701 		 * net.inet.ip.source_address_validation: drop incoming
702 		 * packets that pretend to be ours.
703 		 */
704 		if (V_ip_sav && !(ifp->if_flags & IFF_LOOPBACK) &&
705 		    __predict_false(in_localip_fib(ip->ip_src, ifp->if_fib))) {
706 			IPSTAT_INC(ips_badaddr);
707 			goto bad;
708 		}
709 
710 		counter_u64_add(ia->ia_ifa.ifa_ipackets, 1);
711 		counter_u64_add(ia->ia_ifa.ifa_ibytes, m->m_pkthdr.len);
712 		goto ours;
713 	}
714 
715 	/*
716 	 * Check for broadcast addresses.
717 	 *
718 	 * Only accept broadcast packets that arrive via the matching
719 	 * interface.  Reception of forwarded directed broadcasts would
720 	 * be handled via ip_forward() and ether_output() with the loopback
721 	 * into the stack for SIMPLEX interfaces handled by ether_output().
722 	 */
723 	if (ifp->if_flags & IFF_BROADCAST) {
724 		CK_STAILQ_FOREACH(ifa, &ifp->if_addrhead, ifa_link) {
725 			if (ifa->ifa_addr->sa_family != AF_INET)
726 				continue;
727 			ia = ifatoia(ifa);
728 			if (satosin(&ia->ia_broadaddr)->sin_addr.s_addr ==
729 			    ip->ip_dst.s_addr) {
730 				counter_u64_add(ia->ia_ifa.ifa_ipackets, 1);
731 				counter_u64_add(ia->ia_ifa.ifa_ibytes,
732 				    m->m_pkthdr.len);
733 				goto ours;
734 			}
735 #ifdef BOOTP_COMPAT
736 			if (IA_SIN(ia)->sin_addr.s_addr == INADDR_ANY) {
737 				counter_u64_add(ia->ia_ifa.ifa_ipackets, 1);
738 				counter_u64_add(ia->ia_ifa.ifa_ibytes,
739 				    m->m_pkthdr.len);
740 				goto ours;
741 			}
742 #endif
743 		}
744 		ia = NULL;
745 	}
746 	if (IN_MULTICAST(ntohl(ip->ip_dst.s_addr))) {
747 		MROUTER_RLOCK();
748 		/*
749 		 * RFC 3927 2.7: Do not forward multicast packets from
750 		 * IN_LINKLOCAL.
751 		 */
752 		if (V_ip_mrouter && !IN_LINKLOCAL(ntohl(ip->ip_src.s_addr))) {
753 			/*
754 			 * If we are acting as a multicast router, all
755 			 * incoming multicast packets are passed to the
756 			 * kernel-level multicast forwarding function.
757 			 * The packet is returned (relatively) intact; if
758 			 * ip_mforward() returns a non-zero value, the packet
759 			 * must be discarded, else it may be accepted below.
760 			 */
761 			if (ip_mforward && ip_mforward(ip, ifp, m, 0) != 0) {
762 				MROUTER_RUNLOCK();
763 				IPSTAT_INC(ips_cantforward);
764 				m_freem(m);
765 				return;
766 			}
767 
768 			/*
769 			 * The process-level routing daemon needs to receive
770 			 * all multicast IGMP packets, whether or not this
771 			 * host belongs to their destination groups.
772 			 */
773 			if (ip->ip_p == IPPROTO_IGMP) {
774 				MROUTER_RUNLOCK();
775 				goto ours;
776 			}
777 			IPSTAT_INC(ips_forward);
778 		}
779 		MROUTER_RUNLOCK();
780 		/*
781 		 * Assume the packet is for us, to avoid prematurely taking
782 		 * a lock on the in_multi hash. Protocols must perform
783 		 * their own filtering and update statistics accordingly.
784 		 */
785 		goto ours;
786 	}
787 	if (ip->ip_dst.s_addr == (u_long)INADDR_BROADCAST)
788 		goto ours;
789 	if (ip->ip_dst.s_addr == INADDR_ANY)
790 		goto ours;
791 	/* RFC 3927 2.7: Do not forward packets to or from IN_LINKLOCAL. */
792 	if (IN_LINKLOCAL(ntohl(ip->ip_dst.s_addr)) ||
793 	    IN_LINKLOCAL(ntohl(ip->ip_src.s_addr))) {
794 		IPSTAT_INC(ips_cantforward);
795 		m_freem(m);
796 		return;
797 	}
798 
799 	/*
800 	 * Not for us; forward if possible and desirable.
801 	 */
802 	if (V_ipforwarding == 0) {
803 		IPSTAT_INC(ips_cantforward);
804 		m_freem(m);
805 	} else {
806 		ip_forward(m, dchg);
807 	}
808 	return;
809 
810 ours:
811 #ifdef IPSTEALTH
812 	/*
813 	 * IPSTEALTH: Process non-routing options only
814 	 * if the packet is destined for us.
815 	 */
816 	if (V_ipstealth && hlen > sizeof (struct ip) && ip_dooptions(m, 1))
817 		return;
818 #endif /* IPSTEALTH */
819 
820 	/*
821 	 * Attempt reassembly; if it succeeds, proceed.
822 	 * ip_reass() will return a different mbuf.
823 	 */
824 	if (ip->ip_off & htons(IP_MF | IP_OFFMASK)) {
825 		/* XXXGL: shouldn't we save & set m_flags? */
826 		m = ip_reass(m);
827 		if (m == NULL)
828 			return;
829 		ip = mtod(m, struct ip *);
830 		/* Get the header length of the reassembled packet */
831 		hlen = ip->ip_hl << 2;
832 	}
833 
834 #if defined(IPSEC) || defined(IPSEC_SUPPORT)
835 	if (IPSEC_ENABLED(ipv4)) {
836 		if (IPSEC_INPUT(ipv4, m, hlen, ip->ip_p) != 0)
837 			return;
838 	}
839 #endif /* IPSEC */
840 
841 	/*
842 	 * Switch out to protocol's input routine.
843 	 */
844 	IPSTAT_INC(ips_delivered);
845 
846 	(*inetsw[ip_protox[ip->ip_p]].pr_input)(&m, &hlen, ip->ip_p);
847 	return;
848 bad:
849 	m_freem(m);
850 }
851 
852 /*
853  * IP timer processing;
854  * if a timer expires on a reassembly
855  * queue, discard it.
856  */
857 void
858 ip_slowtimo(void)
859 {
860 	VNET_ITERATOR_DECL(vnet_iter);
861 
862 	VNET_LIST_RLOCK_NOSLEEP();
863 	VNET_FOREACH(vnet_iter) {
864 		CURVNET_SET(vnet_iter);
865 		ipreass_slowtimo();
866 		CURVNET_RESTORE();
867 	}
868 	VNET_LIST_RUNLOCK_NOSLEEP();
869 }
870 
871 void
872 ip_drain(void)
873 {
874 	VNET_ITERATOR_DECL(vnet_iter);
875 
876 	VNET_LIST_RLOCK_NOSLEEP();
877 	VNET_FOREACH(vnet_iter) {
878 		CURVNET_SET(vnet_iter);
879 		ipreass_drain();
880 		CURVNET_RESTORE();
881 	}
882 	VNET_LIST_RUNLOCK_NOSLEEP();
883 }
884 
885 /*
886  * The protocol to be inserted into ip_protox[] must be already registered
887  * in inetsw[], either statically or through pf_proto_register().
888  */
889 int
890 ipproto_register(short ipproto)
891 {
892 	struct protosw *pr;
893 
894 	/* Sanity checks. */
895 	if (ipproto <= 0 || ipproto >= IPPROTO_MAX)
896 		return (EPROTONOSUPPORT);
897 
898 	/*
899 	 * The protocol slot must not be occupied by another protocol
900 	 * already.  An index pointing to IPPROTO_RAW is unused.
901 	 */
902 	pr = pffindproto(PF_INET, IPPROTO_RAW, SOCK_RAW);
903 	if (pr == NULL)
904 		return (EPFNOSUPPORT);
905 	if (ip_protox[ipproto] != pr - inetsw)	/* IPPROTO_RAW */
906 		return (EEXIST);
907 
908 	/* Find the protocol position in inetsw[] and set the index. */
909 	for (pr = inetdomain.dom_protosw;
910 	     pr < inetdomain.dom_protoswNPROTOSW; pr++) {
911 		if (pr->pr_domain->dom_family == PF_INET &&
912 		    pr->pr_protocol && pr->pr_protocol == ipproto) {
913 			ip_protox[pr->pr_protocol] = pr - inetsw;
914 			return (0);
915 		}
916 	}
917 	return (EPROTONOSUPPORT);
918 }
919 
920 int
921 ipproto_unregister(short ipproto)
922 {
923 	struct protosw *pr;
924 
925 	/* Sanity checks. */
926 	if (ipproto <= 0 || ipproto >= IPPROTO_MAX)
927 		return (EPROTONOSUPPORT);
928 
929 	/* Check if the protocol was indeed registered. */
930 	pr = pffindproto(PF_INET, IPPROTO_RAW, SOCK_RAW);
931 	if (pr == NULL)
932 		return (EPFNOSUPPORT);
933 	if (ip_protox[ipproto] == pr - inetsw)  /* IPPROTO_RAW */
934 		return (ENOENT);
935 
936 	/* Reset the protocol slot to IPPROTO_RAW. */
937 	ip_protox[ipproto] = pr - inetsw;
938 	return (0);
939 }
940 
941 u_char inetctlerrmap[PRC_NCMDS] = {
942 	0,		0,		0,		0,
943 	0,		EMSGSIZE,	EHOSTDOWN,	EHOSTUNREACH,
944 	EHOSTUNREACH,	EHOSTUNREACH,	ECONNREFUSED,	ECONNREFUSED,
945 	EMSGSIZE,	EHOSTUNREACH,	0,		0,
946 	0,		0,		EHOSTUNREACH,	0,
947 	ENOPROTOOPT,	ECONNREFUSED
948 };
949 
950 /*
951  * Forward a packet.  If some error occurs return the sender
952  * an icmp packet.  Note we can't always generate a meaningful
953  * icmp message because icmp doesn't have a large enough repertoire
954  * of codes and types.
955  *
956  * If not forwarding, just drop the packet.  This could be confusing
957  * if ipforwarding was zero but some routing protocol was advancing
958  * us as a gateway to somewhere.  However, we must let the routing
959  * protocol deal with that.
960  *
961  * The srcrt parameter indicates whether the packet is being forwarded
962  * via a source route.
963  */
964 void
965 ip_forward(struct mbuf *m, int srcrt)
966 {
967 	struct ip *ip = mtod(m, struct ip *);
968 	struct in_ifaddr *ia;
969 	struct mbuf *mcopy;
970 	struct sockaddr_in *sin;
971 	struct in_addr dest;
972 	struct route ro;
973 	uint32_t flowid;
974 	int error, type = 0, code = 0, mtu = 0;
975 
976 	NET_EPOCH_ASSERT();
977 
978 	if (m->m_flags & (M_BCAST|M_MCAST) || in_canforward(ip->ip_dst) == 0) {
979 		IPSTAT_INC(ips_cantforward);
980 		m_freem(m);
981 		return;
982 	}
983 	if (
984 #ifdef IPSTEALTH
985 	    V_ipstealth == 0 &&
986 #endif
987 	    ip->ip_ttl <= IPTTLDEC) {
988 		icmp_error(m, ICMP_TIMXCEED, ICMP_TIMXCEED_INTRANS, 0, 0);
989 		return;
990 	}
991 
992 	bzero(&ro, sizeof(ro));
993 	sin = (struct sockaddr_in *)&ro.ro_dst;
994 	sin->sin_family = AF_INET;
995 	sin->sin_len = sizeof(*sin);
996 	sin->sin_addr = ip->ip_dst;
997 	flowid = m->m_pkthdr.flowid;
998 	ro.ro_nh = fib4_lookup(M_GETFIB(m), ip->ip_dst, 0, NHR_REF, flowid);
999 	if (ro.ro_nh != NULL) {
1000 		ia = ifatoia(ro.ro_nh->nh_ifa);
1001 	} else
1002 		ia = NULL;
1003 	/*
1004 	 * Save the IP header and at most 8 bytes of the payload,
1005 	 * in case we need to generate an ICMP message to the src.
1006 	 *
1007 	 * XXX this can be optimized a lot by saving the data in a local
1008 	 * buffer on the stack (72 bytes at most), and only allocating the
1009 	 * mbuf if really necessary. The vast majority of the packets
1010 	 * are forwarded without having to send an ICMP back (either
1011 	 * because unnecessary, or because rate limited), so we are
1012 	 * really we are wasting a lot of work here.
1013 	 *
1014 	 * We don't use m_copym() because it might return a reference
1015 	 * to a shared cluster. Both this function and ip_output()
1016 	 * assume exclusive access to the IP header in `m', so any
1017 	 * data in a cluster may change before we reach icmp_error().
1018 	 */
1019 	mcopy = m_gethdr(M_NOWAIT, m->m_type);
1020 	if (mcopy != NULL && !m_dup_pkthdr(mcopy, m, M_NOWAIT)) {
1021 		/*
1022 		 * It's probably ok if the pkthdr dup fails (because
1023 		 * the deep copy of the tag chain failed), but for now
1024 		 * be conservative and just discard the copy since
1025 		 * code below may some day want the tags.
1026 		 */
1027 		m_free(mcopy);
1028 		mcopy = NULL;
1029 	}
1030 	if (mcopy != NULL) {
1031 		mcopy->m_len = min(ntohs(ip->ip_len), M_TRAILINGSPACE(mcopy));
1032 		mcopy->m_pkthdr.len = mcopy->m_len;
1033 		m_copydata(m, 0, mcopy->m_len, mtod(mcopy, caddr_t));
1034 	}
1035 #ifdef IPSTEALTH
1036 	if (V_ipstealth == 0)
1037 #endif
1038 		ip->ip_ttl -= IPTTLDEC;
1039 #if defined(IPSEC) || defined(IPSEC_SUPPORT)
1040 	if (IPSEC_ENABLED(ipv4)) {
1041 		if ((error = IPSEC_FORWARD(ipv4, m)) != 0) {
1042 			/* mbuf consumed by IPsec */
1043 			RO_NHFREE(&ro);
1044 			m_freem(mcopy);
1045 			if (error != EINPROGRESS)
1046 				IPSTAT_INC(ips_cantforward);
1047 			return;
1048 		}
1049 		/* No IPsec processing required */
1050 	}
1051 #endif /* IPSEC */
1052 	/*
1053 	 * If forwarding packet using same interface that it came in on,
1054 	 * perhaps should send a redirect to sender to shortcut a hop.
1055 	 * Only send redirect if source is sending directly to us,
1056 	 * and if packet was not source routed (or has any options).
1057 	 * Also, don't send redirect if forwarding using a default route
1058 	 * or a route modified by a redirect.
1059 	 */
1060 	dest.s_addr = 0;
1061 	if (!srcrt && V_ipsendredirects &&
1062 	    ia != NULL && ia->ia_ifp == m->m_pkthdr.rcvif) {
1063 		struct nhop_object *nh;
1064 
1065 		nh = ro.ro_nh;
1066 
1067 		if (nh != NULL && ((nh->nh_flags & (NHF_REDIRECT|NHF_DEFAULT)) == 0)) {
1068 			struct in_ifaddr *nh_ia = (struct in_ifaddr *)(nh->nh_ifa);
1069 			u_long src = ntohl(ip->ip_src.s_addr);
1070 
1071 			if (nh_ia != NULL &&
1072 			    (src & nh_ia->ia_subnetmask) == nh_ia->ia_subnet) {
1073 				/* Router requirements says to only send host redirects */
1074 				type = ICMP_REDIRECT;
1075 				code = ICMP_REDIRECT_HOST;
1076 				if (nh->nh_flags & NHF_GATEWAY) {
1077 				    if (nh->gw_sa.sa_family == AF_INET)
1078 					dest.s_addr = nh->gw4_sa.sin_addr.s_addr;
1079 				    else /* Do not redirect in case gw is AF_INET6 */
1080 					type = 0;
1081 				} else
1082 					dest.s_addr = ip->ip_dst.s_addr;
1083 			}
1084 		}
1085 	}
1086 
1087 	error = ip_output(m, NULL, &ro, IP_FORWARDING, NULL, NULL);
1088 
1089 	if (error == EMSGSIZE && ro.ro_nh)
1090 		mtu = ro.ro_nh->nh_mtu;
1091 	RO_NHFREE(&ro);
1092 
1093 	if (error)
1094 		IPSTAT_INC(ips_cantforward);
1095 	else {
1096 		IPSTAT_INC(ips_forward);
1097 		if (type)
1098 			IPSTAT_INC(ips_redirectsent);
1099 		else {
1100 			if (mcopy)
1101 				m_freem(mcopy);
1102 			return;
1103 		}
1104 	}
1105 	if (mcopy == NULL)
1106 		return;
1107 
1108 	switch (error) {
1109 	case 0:				/* forwarded, but need redirect */
1110 		/* type, code set above */
1111 		break;
1112 
1113 	case ENETUNREACH:
1114 	case EHOSTUNREACH:
1115 	case ENETDOWN:
1116 	case EHOSTDOWN:
1117 	default:
1118 		type = ICMP_UNREACH;
1119 		code = ICMP_UNREACH_HOST;
1120 		break;
1121 
1122 	case EMSGSIZE:
1123 		type = ICMP_UNREACH;
1124 		code = ICMP_UNREACH_NEEDFRAG;
1125 		/*
1126 		 * If the MTU was set before make sure we are below the
1127 		 * interface MTU.
1128 		 * If the MTU wasn't set before use the interface mtu or
1129 		 * fall back to the next smaller mtu step compared to the
1130 		 * current packet size.
1131 		 */
1132 		if (mtu != 0) {
1133 			if (ia != NULL)
1134 				mtu = min(mtu, ia->ia_ifp->if_mtu);
1135 		} else {
1136 			if (ia != NULL)
1137 				mtu = ia->ia_ifp->if_mtu;
1138 			else
1139 				mtu = ip_next_mtu(ntohs(ip->ip_len), 0);
1140 		}
1141 		IPSTAT_INC(ips_cantfrag);
1142 		break;
1143 
1144 	case ENOBUFS:
1145 	case EACCES:			/* ipfw denied packet */
1146 		m_freem(mcopy);
1147 		return;
1148 	}
1149 	icmp_error(mcopy, type, code, dest.s_addr, mtu);
1150 }
1151 
1152 #define	CHECK_SO_CT(sp, ct) \
1153     (((sp->so_options & SO_TIMESTAMP) && (sp->so_ts_clock == ct)) ? 1 : 0)
1154 
1155 void
1156 ip_savecontrol(struct inpcb *inp, struct mbuf **mp, struct ip *ip,
1157     struct mbuf *m)
1158 {
1159 	bool stamped;
1160 
1161 	stamped = false;
1162 	if ((inp->inp_socket->so_options & SO_BINTIME) ||
1163 	    CHECK_SO_CT(inp->inp_socket, SO_TS_BINTIME)) {
1164 		struct bintime boottimebin, bt;
1165 		struct timespec ts1;
1166 
1167 		if ((m->m_flags & (M_PKTHDR | M_TSTMP)) == (M_PKTHDR |
1168 		    M_TSTMP)) {
1169 			mbuf_tstmp2timespec(m, &ts1);
1170 			timespec2bintime(&ts1, &bt);
1171 			getboottimebin(&boottimebin);
1172 			bintime_add(&bt, &boottimebin);
1173 		} else {
1174 			bintime(&bt);
1175 		}
1176 		*mp = sbcreatecontrol((caddr_t)&bt, sizeof(bt),
1177 		    SCM_BINTIME, SOL_SOCKET);
1178 		if (*mp != NULL) {
1179 			mp = &(*mp)->m_next;
1180 			stamped = true;
1181 		}
1182 	}
1183 	if (CHECK_SO_CT(inp->inp_socket, SO_TS_REALTIME_MICRO)) {
1184 		struct bintime boottimebin, bt1;
1185 		struct timespec ts1;
1186 		struct timeval tv;
1187 
1188 		if ((m->m_flags & (M_PKTHDR | M_TSTMP)) == (M_PKTHDR |
1189 		    M_TSTMP)) {
1190 			mbuf_tstmp2timespec(m, &ts1);
1191 			timespec2bintime(&ts1, &bt1);
1192 			getboottimebin(&boottimebin);
1193 			bintime_add(&bt1, &boottimebin);
1194 			bintime2timeval(&bt1, &tv);
1195 		} else {
1196 			microtime(&tv);
1197 		}
1198 		*mp = sbcreatecontrol((caddr_t)&tv, sizeof(tv),
1199 		    SCM_TIMESTAMP, SOL_SOCKET);
1200 		if (*mp != NULL) {
1201 			mp = &(*mp)->m_next;
1202 			stamped = true;
1203 		}
1204 	} else if (CHECK_SO_CT(inp->inp_socket, SO_TS_REALTIME)) {
1205 		struct bintime boottimebin;
1206 		struct timespec ts, ts1;
1207 
1208 		if ((m->m_flags & (M_PKTHDR | M_TSTMP)) == (M_PKTHDR |
1209 		    M_TSTMP)) {
1210 			mbuf_tstmp2timespec(m, &ts);
1211 			getboottimebin(&boottimebin);
1212 			bintime2timespec(&boottimebin, &ts1);
1213 			timespecadd(&ts, &ts1, &ts);
1214 		} else {
1215 			nanotime(&ts);
1216 		}
1217 		*mp = sbcreatecontrol((caddr_t)&ts, sizeof(ts),
1218 		    SCM_REALTIME, SOL_SOCKET);
1219 		if (*mp != NULL) {
1220 			mp = &(*mp)->m_next;
1221 			stamped = true;
1222 		}
1223 	} else if (CHECK_SO_CT(inp->inp_socket, SO_TS_MONOTONIC)) {
1224 		struct timespec ts;
1225 
1226 		if ((m->m_flags & (M_PKTHDR | M_TSTMP)) == (M_PKTHDR |
1227 		    M_TSTMP))
1228 			mbuf_tstmp2timespec(m, &ts);
1229 		else
1230 			nanouptime(&ts);
1231 		*mp = sbcreatecontrol((caddr_t)&ts, sizeof(ts),
1232 		    SCM_MONOTONIC, SOL_SOCKET);
1233 		if (*mp != NULL) {
1234 			mp = &(*mp)->m_next;
1235 			stamped = true;
1236 		}
1237 	}
1238 	if (stamped && (m->m_flags & (M_PKTHDR | M_TSTMP)) == (M_PKTHDR |
1239 	    M_TSTMP)) {
1240 		struct sock_timestamp_info sti;
1241 
1242 		bzero(&sti, sizeof(sti));
1243 		sti.st_info_flags = ST_INFO_HW;
1244 		if ((m->m_flags & M_TSTMP_HPREC) != 0)
1245 			sti.st_info_flags |= ST_INFO_HW_HPREC;
1246 		*mp = sbcreatecontrol((caddr_t)&sti, sizeof(sti), SCM_TIME_INFO,
1247 		    SOL_SOCKET);
1248 		if (*mp != NULL)
1249 			mp = &(*mp)->m_next;
1250 	}
1251 	if (inp->inp_flags & INP_RECVDSTADDR) {
1252 		*mp = sbcreatecontrol((caddr_t)&ip->ip_dst,
1253 		    sizeof(struct in_addr), IP_RECVDSTADDR, IPPROTO_IP);
1254 		if (*mp)
1255 			mp = &(*mp)->m_next;
1256 	}
1257 	if (inp->inp_flags & INP_RECVTTL) {
1258 		*mp = sbcreatecontrol((caddr_t)&ip->ip_ttl,
1259 		    sizeof(u_char), IP_RECVTTL, IPPROTO_IP);
1260 		if (*mp)
1261 			mp = &(*mp)->m_next;
1262 	}
1263 #ifdef notyet
1264 	/* XXX
1265 	 * Moving these out of udp_input() made them even more broken
1266 	 * than they already were.
1267 	 */
1268 	/* options were tossed already */
1269 	if (inp->inp_flags & INP_RECVOPTS) {
1270 		*mp = sbcreatecontrol((caddr_t)opts_deleted_above,
1271 		    sizeof(struct in_addr), IP_RECVOPTS, IPPROTO_IP);
1272 		if (*mp)
1273 			mp = &(*mp)->m_next;
1274 	}
1275 	/* ip_srcroute doesn't do what we want here, need to fix */
1276 	if (inp->inp_flags & INP_RECVRETOPTS) {
1277 		*mp = sbcreatecontrol((caddr_t)ip_srcroute(m),
1278 		    sizeof(struct in_addr), IP_RECVRETOPTS, IPPROTO_IP);
1279 		if (*mp)
1280 			mp = &(*mp)->m_next;
1281 	}
1282 #endif
1283 	if (inp->inp_flags & INP_RECVIF) {
1284 		struct ifnet *ifp;
1285 		struct sdlbuf {
1286 			struct sockaddr_dl sdl;
1287 			u_char	pad[32];
1288 		} sdlbuf;
1289 		struct sockaddr_dl *sdp;
1290 		struct sockaddr_dl *sdl2 = &sdlbuf.sdl;
1291 
1292 		if ((ifp = m->m_pkthdr.rcvif)) {
1293 			sdp = (struct sockaddr_dl *)ifp->if_addr->ifa_addr;
1294 			/*
1295 			 * Change our mind and don't try copy.
1296 			 */
1297 			if (sdp->sdl_family != AF_LINK ||
1298 			    sdp->sdl_len > sizeof(sdlbuf)) {
1299 				goto makedummy;
1300 			}
1301 			bcopy(sdp, sdl2, sdp->sdl_len);
1302 		} else {
1303 makedummy:
1304 			sdl2->sdl_len =
1305 			    offsetof(struct sockaddr_dl, sdl_data[0]);
1306 			sdl2->sdl_family = AF_LINK;
1307 			sdl2->sdl_index = 0;
1308 			sdl2->sdl_nlen = sdl2->sdl_alen = sdl2->sdl_slen = 0;
1309 		}
1310 		*mp = sbcreatecontrol((caddr_t)sdl2, sdl2->sdl_len,
1311 		    IP_RECVIF, IPPROTO_IP);
1312 		if (*mp)
1313 			mp = &(*mp)->m_next;
1314 	}
1315 	if (inp->inp_flags & INP_RECVTOS) {
1316 		*mp = sbcreatecontrol((caddr_t)&ip->ip_tos,
1317 		    sizeof(u_char), IP_RECVTOS, IPPROTO_IP);
1318 		if (*mp)
1319 			mp = &(*mp)->m_next;
1320 	}
1321 
1322 	if (inp->inp_flags2 & INP_RECVFLOWID) {
1323 		uint32_t flowid, flow_type;
1324 
1325 		flowid = m->m_pkthdr.flowid;
1326 		flow_type = M_HASHTYPE_GET(m);
1327 
1328 		/*
1329 		 * XXX should handle the failure of one or the
1330 		 * other - don't populate both?
1331 		 */
1332 		*mp = sbcreatecontrol((caddr_t) &flowid,
1333 		    sizeof(uint32_t), IP_FLOWID, IPPROTO_IP);
1334 		if (*mp)
1335 			mp = &(*mp)->m_next;
1336 		*mp = sbcreatecontrol((caddr_t) &flow_type,
1337 		    sizeof(uint32_t), IP_FLOWTYPE, IPPROTO_IP);
1338 		if (*mp)
1339 			mp = &(*mp)->m_next;
1340 	}
1341 
1342 #ifdef	RSS
1343 	if (inp->inp_flags2 & INP_RECVRSSBUCKETID) {
1344 		uint32_t flowid, flow_type;
1345 		uint32_t rss_bucketid;
1346 
1347 		flowid = m->m_pkthdr.flowid;
1348 		flow_type = M_HASHTYPE_GET(m);
1349 
1350 		if (rss_hash2bucket(flowid, flow_type, &rss_bucketid) == 0) {
1351 			*mp = sbcreatecontrol((caddr_t) &rss_bucketid,
1352 			   sizeof(uint32_t), IP_RSSBUCKETID, IPPROTO_IP);
1353 			if (*mp)
1354 				mp = &(*mp)->m_next;
1355 		}
1356 	}
1357 #endif
1358 }
1359 
1360 /*
1361  * XXXRW: Multicast routing code in ip_mroute.c is generally MPSAFE, but the
1362  * ip_rsvp and ip_rsvp_on variables need to be interlocked with rsvp_on
1363  * locking.  This code remains in ip_input.c as ip_mroute.c is optionally
1364  * compiled.
1365  */
1366 VNET_DEFINE_STATIC(int, ip_rsvp_on);
1367 VNET_DEFINE(struct socket *, ip_rsvpd);
1368 
1369 #define	V_ip_rsvp_on		VNET(ip_rsvp_on)
1370 
1371 int
1372 ip_rsvp_init(struct socket *so)
1373 {
1374 
1375 	if (so->so_type != SOCK_RAW ||
1376 	    so->so_proto->pr_protocol != IPPROTO_RSVP)
1377 		return EOPNOTSUPP;
1378 
1379 	if (V_ip_rsvpd != NULL)
1380 		return EADDRINUSE;
1381 
1382 	V_ip_rsvpd = so;
1383 	/*
1384 	 * This may seem silly, but we need to be sure we don't over-increment
1385 	 * the RSVP counter, in case something slips up.
1386 	 */
1387 	if (!V_ip_rsvp_on) {
1388 		V_ip_rsvp_on = 1;
1389 		V_rsvp_on++;
1390 	}
1391 
1392 	return 0;
1393 }
1394 
1395 int
1396 ip_rsvp_done(void)
1397 {
1398 
1399 	V_ip_rsvpd = NULL;
1400 	/*
1401 	 * This may seem silly, but we need to be sure we don't over-decrement
1402 	 * the RSVP counter, in case something slips up.
1403 	 */
1404 	if (V_ip_rsvp_on) {
1405 		V_ip_rsvp_on = 0;
1406 		V_rsvp_on--;
1407 	}
1408 	return 0;
1409 }
1410 
1411 int
1412 rsvp_input(struct mbuf **mp, int *offp, int proto)
1413 {
1414 	struct mbuf *m;
1415 
1416 	m = *mp;
1417 	*mp = NULL;
1418 
1419 	if (rsvp_input_p) { /* call the real one if loaded */
1420 		*mp = m;
1421 		rsvp_input_p(mp, offp, proto);
1422 		return (IPPROTO_DONE);
1423 	}
1424 
1425 	/* Can still get packets with rsvp_on = 0 if there is a local member
1426 	 * of the group to which the RSVP packet is addressed.  But in this
1427 	 * case we want to throw the packet away.
1428 	 */
1429 
1430 	if (!V_rsvp_on) {
1431 		m_freem(m);
1432 		return (IPPROTO_DONE);
1433 	}
1434 
1435 	if (V_ip_rsvpd != NULL) {
1436 		*mp = m;
1437 		rip_input(mp, offp, proto);
1438 		return (IPPROTO_DONE);
1439 	}
1440 	/* Drop the packet */
1441 	m_freem(m);
1442 	return (IPPROTO_DONE);
1443 }
1444