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