xref: /xnu-8020.121.3/bsd/netinet/ip_input.c (revision fdd8201d7b966f0c3ea610489d29bd841d358941)
1 /*
2  * Copyright (c) 2000-2021 Apple Inc. All rights reserved.
3  *
4  * @APPLE_OSREFERENCE_LICENSE_HEADER_START@
5  *
6  * This file contains Original Code and/or Modifications of Original Code
7  * as defined in and that are subject to the Apple Public Source License
8  * Version 2.0 (the 'License'). You may not use this file except in
9  * compliance with the License. The rights granted to you under the License
10  * may not be used to create, or enable the creation or redistribution of,
11  * unlawful or unlicensed copies of an Apple operating system, or to
12  * circumvent, violate, or enable the circumvention or violation of, any
13  * terms of an Apple operating system software license agreement.
14  *
15  * Please obtain a copy of the License at
16  * http://www.opensource.apple.com/apsl/ and read it before using this file.
17  *
18  * The Original Code and all software distributed under the License are
19  * distributed on an 'AS IS' basis, WITHOUT WARRANTY OF ANY KIND, EITHER
20  * EXPRESS OR IMPLIED, AND APPLE HEREBY DISCLAIMS ALL SUCH WARRANTIES,
21  * INCLUDING WITHOUT LIMITATION, ANY WARRANTIES OF MERCHANTABILITY,
22  * FITNESS FOR A PARTICULAR PURPOSE, QUIET ENJOYMENT OR NON-INFRINGEMENT.
23  * Please see the License for the specific language governing rights and
24  * limitations under the License.
25  *
26  * @APPLE_OSREFERENCE_LICENSE_HEADER_END@
27  */
28 /*
29  * Copyright (c) 1982, 1986, 1988, 1993
30  *	The Regents of the University of California.  All rights reserved.
31  *
32  * Redistribution and use in source and binary forms, with or without
33  * modification, are permitted provided that the following conditions
34  * are met:
35  * 1. Redistributions of source code must retain the above copyright
36  *    notice, this list of conditions and the following disclaimer.
37  * 2. Redistributions in binary form must reproduce the above copyright
38  *    notice, this list of conditions and the following disclaimer in the
39  *    documentation and/or other materials provided with the distribution.
40  * 3. All advertising materials mentioning features or use of this software
41  *    must display the following acknowledgement:
42  *	This product includes software developed by the University of
43  *	California, Berkeley and its contributors.
44  * 4. Neither the name of the University nor the names of its contributors
45  *    may be used to endorse or promote products derived from this software
46  *    without specific prior written permission.
47  *
48  * THIS SOFTWARE IS PROVIDED BY THE REGENTS AND CONTRIBUTORS ``AS IS'' AND
49  * ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
50  * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE
51  * ARE DISCLAIMED.  IN NO EVENT SHALL THE REGENTS OR CONTRIBUTORS BE LIABLE
52  * FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL
53  * DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS
54  * OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION)
55  * HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT
56  * LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY
57  * OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF
58  * SUCH DAMAGE.
59  *
60  *	@(#)ip_input.c	8.2 (Berkeley) 1/4/94
61  */
62 /*
63  * NOTICE: This file was modified by SPARTA, Inc. in 2007 to introduce
64  * support for mandatory and extensible security protections.  This notice
65  * is included in support of clause 2.2 (b) of the Apple Public License,
66  * Version 2.0.
67  */
68 
69 #define _IP_VHL
70 
71 #include <sys/param.h>
72 #include <sys/systm.h>
73 #include <sys/mbuf.h>
74 #include <sys/malloc.h>
75 #include <sys/domain.h>
76 #include <sys/protosw.h>
77 #include <sys/socket.h>
78 #include <sys/time.h>
79 #include <sys/kernel.h>
80 #include <sys/syslog.h>
81 #include <sys/sysctl.h>
82 #include <sys/mcache.h>
83 #include <sys/socketvar.h>
84 #include <sys/kdebug.h>
85 #include <mach/mach_time.h>
86 #include <mach/sdt.h>
87 
88 #include <machine/endian.h>
89 #include <dev/random/randomdev.h>
90 
91 #include <kern/queue.h>
92 #include <kern/locks.h>
93 #include <libkern/OSAtomic.h>
94 
95 #include <pexpert/pexpert.h>
96 
97 #include <net/if.h>
98 #include <net/if_var.h>
99 #include <net/if_dl.h>
100 #include <net/route.h>
101 #include <net/kpi_protocol.h>
102 #include <net/ntstat.h>
103 #include <net/dlil.h>
104 #include <net/classq/classq.h>
105 #include <net/net_perf.h>
106 #include <net/init.h>
107 #if PF
108 #include <net/pfvar.h>
109 #endif /* PF */
110 #include <net/if_ports_used.h>
111 
112 #include <netinet/in.h>
113 #include <netinet/in_systm.h>
114 #include <netinet/in_var.h>
115 #include <netinet/in_arp.h>
116 #include <netinet/ip.h>
117 #include <netinet/in_pcb.h>
118 #include <netinet/ip_var.h>
119 #include <netinet/ip_icmp.h>
120 #include <netinet/kpi_ipfilter_var.h>
121 #include <netinet/udp.h>
122 #include <netinet/udp_var.h>
123 #include <netinet/bootp.h>
124 
125 #if DUMMYNET
126 #include <netinet/ip_dummynet.h>
127 #endif /* DUMMYNET */
128 
129 #if IPSEC
130 #include <netinet6/ipsec.h>
131 #include <netkey/key.h>
132 #endif /* IPSEC */
133 
134 #include <os/log.h>
135 
136 #define DBG_LAYER_BEG           NETDBG_CODE(DBG_NETIP, 0)
137 #define DBG_LAYER_END           NETDBG_CODE(DBG_NETIP, 2)
138 #define DBG_FNC_IP_INPUT        NETDBG_CODE(DBG_NETIP, (2 << 8))
139 
140 #if IPSEC
141 extern int ipsec_bypass;
142 #endif /* IPSEC */
143 
144 MBUFQ_HEAD(fq_head);
145 
146 static int frag_timeout_run;            /* frag timer is scheduled to run */
147 static void frag_timeout(void *);
148 static void frag_sched_timeout(void);
149 
150 static struct ipq *ipq_alloc(int);
151 static void ipq_free(struct ipq *);
152 static void ipq_updateparams(void);
153 static void ip_input_second_pass(struct mbuf *, struct ifnet *,
154     int, int, struct ip_fw_in_args *);
155 
156 static LCK_GRP_DECLARE(ipqlock_grp, "ipqlock");
157 static LCK_MTX_DECLARE(ipqlock, &ipqlock_grp);
158 
159 
160 /* Packet reassembly stuff */
161 #define IPREASS_NHASH_LOG2      6
162 #define IPREASS_NHASH           (1 << IPREASS_NHASH_LOG2)
163 #define IPREASS_HMASK           (IPREASS_NHASH - 1)
164 #define IPREASS_HASH(x, y) \
165 	(((((x) & 0xF) | ((((x) >> 8) & 0xF) << 4)) ^ (y)) & IPREASS_HMASK)
166 
167 /* IP fragment reassembly queues (protected by ipqlock) */
168 static TAILQ_HEAD(ipqhead, ipq) ipq[IPREASS_NHASH]; /* ip reassembly queues */
169 static int maxnipq;                     /* max packets in reass queues */
170 static u_int32_t maxfragsperpacket;     /* max frags/packet in reass queues */
171 static u_int32_t nipq;                  /* # of packets in reass queues */
172 static u_int32_t ipq_limit;             /* ipq allocation limit */
173 static u_int32_t ipq_count;             /* current # of allocated ipq's */
174 
175 static int sysctl_ipforwarding SYSCTL_HANDLER_ARGS;
176 static int sysctl_maxnipq SYSCTL_HANDLER_ARGS;
177 static int sysctl_maxfragsperpacket SYSCTL_HANDLER_ARGS;
178 
179 #if (DEBUG || DEVELOPMENT)
180 static int sysctl_reset_ip_input_stats SYSCTL_HANDLER_ARGS;
181 static int sysctl_ip_input_measure_bins SYSCTL_HANDLER_ARGS;
182 static int sysctl_ip_input_getperf SYSCTL_HANDLER_ARGS;
183 #endif /* (DEBUG || DEVELOPMENT) */
184 
185 int ipforwarding = 0;
186 SYSCTL_PROC(_net_inet_ip, IPCTL_FORWARDING, forwarding,
187     CTLTYPE_INT | CTLFLAG_RW | CTLFLAG_LOCKED, &ipforwarding, 0,
188     sysctl_ipforwarding, "I", "Enable IP forwarding between interfaces");
189 
190 static int ipsendredirects = 1; /* XXX */
191 SYSCTL_INT(_net_inet_ip, IPCTL_SENDREDIRECTS, redirect,
192     CTLFLAG_RW | CTLFLAG_LOCKED, &ipsendredirects, 0,
193     "Enable sending IP redirects");
194 
195 int ip_defttl = IPDEFTTL;
196 SYSCTL_INT(_net_inet_ip, IPCTL_DEFTTL, ttl, CTLFLAG_RW | CTLFLAG_LOCKED,
197     &ip_defttl, 0, "Maximum TTL on IP packets");
198 
199 static int ip_dosourceroute = 0;
200 SYSCTL_INT(_net_inet_ip, IPCTL_SOURCEROUTE, sourceroute,
201     CTLFLAG_RW | CTLFLAG_LOCKED, &ip_dosourceroute, 0,
202     "Enable forwarding source routed IP packets");
203 
204 static int ip_acceptsourceroute = 0;
205 SYSCTL_INT(_net_inet_ip, IPCTL_ACCEPTSOURCEROUTE, accept_sourceroute,
206     CTLFLAG_RW | CTLFLAG_LOCKED, &ip_acceptsourceroute, 0,
207     "Enable accepting source routed IP packets");
208 
209 static int ip_sendsourcequench = 0;
210 SYSCTL_INT(_net_inet_ip, OID_AUTO, sendsourcequench,
211     CTLFLAG_RW | CTLFLAG_LOCKED, &ip_sendsourcequench, 0,
212     "Enable the transmission of source quench packets");
213 
214 SYSCTL_PROC(_net_inet_ip, OID_AUTO, maxfragpackets,
215     CTLTYPE_INT | CTLFLAG_RW | CTLFLAG_LOCKED, &maxnipq, 0, sysctl_maxnipq,
216     "I", "Maximum number of IPv4 fragment reassembly queue entries");
217 
218 SYSCTL_UINT(_net_inet_ip, OID_AUTO, fragpackets, CTLFLAG_RD | CTLFLAG_LOCKED,
219     &nipq, 0, "Current number of IPv4 fragment reassembly queue entries");
220 
221 SYSCTL_PROC(_net_inet_ip, OID_AUTO, maxfragsperpacket,
222     CTLTYPE_INT | CTLFLAG_RW | CTLFLAG_LOCKED, &maxfragsperpacket, 0,
223     sysctl_maxfragsperpacket, "I",
224     "Maximum number of IPv4 fragments allowed per packet");
225 
226 static uint32_t ip_adj_clear_hwcksum = 0;
227 SYSCTL_UINT(_net_inet_ip, OID_AUTO, adj_clear_hwcksum,
228     CTLFLAG_RW | CTLFLAG_LOCKED, &ip_adj_clear_hwcksum, 0,
229     "Invalidate hwcksum info when adjusting length");
230 
231 static uint32_t ip_adj_partial_sum = 1;
232 SYSCTL_UINT(_net_inet_ip, OID_AUTO, adj_partial_sum,
233     CTLFLAG_RW | CTLFLAG_LOCKED, &ip_adj_partial_sum, 0,
234     "Perform partial sum adjustment of trailing bytes at IP layer");
235 
236 /*
237  * ip_checkinterface controls the receive side of the models for multihoming
238  * that are discussed in RFC 1122.
239  *
240  * ip_checkinterface values are:
241  *  IP_CHECKINTERFACE_WEAK_ES:
242  *	This corresponds to the Weak End-System model where incoming packets from
243  *	any interface are accepted provided the destination address of the incoming packet
244  *	is assigned to some interface.
245  *
246  *  IP_CHECKINTERFACE_HYBRID_ES:
247  *	The Hybrid End-System model use the Strong End-System for tunnel interfaces
248  *	(ipsec and utun) and the weak End-System model for other interfaces families.
249  *	This prevents a rogue middle box to probe for signs of TCP connections
250  *	that use the tunnel interface.
251  *
252  *  IP_CHECKINTERFACE_STRONG_ES:
253  *	The Strong model model requires the packet arrived on an interface that
254  *	is assigned the destination address of the packet.
255  *
256  * Since the routing table and transmit implementation do not implement the Strong ES model,
257  * setting this to a value different from IP_CHECKINTERFACE_WEAK_ES may lead to unexpected results.
258  *
259  * When forwarding is enabled, the system reverts to the Weak ES model as a router
260  * is expected by design to receive packets from several interfaces to the same address.
261  *
262  * XXX - ip_checkinterface currently must be set to IP_CHECKINTERFACE_WEAK_ES if you use ipnat
263  * to translate the destination address to another local interface.
264  *
265  * XXX - ip_checkinterface must be set to IP_CHECKINTERFACE_WEAK_ES if you add IP aliases
266  * to the loopback interface instead of the interface where the
267  * packets for those addresses are received.
268  */
269 #define IP_CHECKINTERFACE_WEAK_ES       0
270 #define IP_CHECKINTERFACE_HYBRID_ES     1
271 #define IP_CHECKINTERFACE_STRONG_ES     2
272 
273 static int ip_checkinterface = IP_CHECKINTERFACE_HYBRID_ES;
274 
275 static int sysctl_ip_checkinterface SYSCTL_HANDLER_ARGS;
276 SYSCTL_PROC(_net_inet_ip, OID_AUTO, check_interface,
277     CTLTYPE_INT | CTLFLAG_RW | CTLFLAG_LOCKED,
278     0, 0, sysctl_ip_checkinterface, "I", "Verify packet arrives on correct interface");
279 
280 #if (DEBUG || DEVELOPMENT)
281 #define IP_CHECK_IF_DEBUG 1
282 #else
283 #define IP_CHECK_IF_DEBUG 0
284 #endif /* (DEBUG || DEVELOPMENT) */
285 static int ip_checkinterface_debug = IP_CHECK_IF_DEBUG;
286 SYSCTL_INT(_net_inet_ip, OID_AUTO, checkinterface_debug, CTLFLAG_RW | CTLFLAG_LOCKED,
287     &ip_checkinterface_debug, IP_CHECK_IF_DEBUG, "");
288 
289 static int ip_chaining = 1;
290 SYSCTL_INT(_net_inet_ip, OID_AUTO, rx_chaining, CTLFLAG_RW | CTLFLAG_LOCKED,
291     &ip_chaining, 1, "Do receive side ip address based chaining");
292 
293 static int ip_chainsz = 6;
294 SYSCTL_INT(_net_inet_ip, OID_AUTO, rx_chainsz, CTLFLAG_RW | CTLFLAG_LOCKED,
295     &ip_chainsz, 1, "IP receive side max chaining");
296 
297 #if (DEBUG || DEVELOPMENT)
298 static int ip_input_measure = 0;
299 SYSCTL_PROC(_net_inet_ip, OID_AUTO, input_perf,
300     CTLTYPE_INT | CTLFLAG_RW | CTLFLAG_LOCKED,
301     &ip_input_measure, 0, sysctl_reset_ip_input_stats, "I", "Do time measurement");
302 
303 static uint64_t ip_input_measure_bins = 0;
304 SYSCTL_PROC(_net_inet_ip, OID_AUTO, input_perf_bins,
305     CTLTYPE_QUAD | CTLFLAG_RW | CTLFLAG_LOCKED, &ip_input_measure_bins, 0,
306     sysctl_ip_input_measure_bins, "I",
307     "bins for chaining performance data histogram");
308 
309 static net_perf_t net_perf;
310 SYSCTL_PROC(_net_inet_ip, OID_AUTO, input_perf_data,
311     CTLTYPE_STRUCT | CTLFLAG_RD | CTLFLAG_LOCKED,
312     0, 0, sysctl_ip_input_getperf, "S,net_perf",
313     "IP input performance data (struct net_perf, net/net_perf.h)");
314 #endif /* (DEBUG || DEVELOPMENT) */
315 
316 #if DIAGNOSTIC
317 static int ipprintfs = 0;
318 #endif
319 
320 struct protosw *ip_protox[IPPROTO_MAX];
321 
322 static LCK_GRP_DECLARE(in_ifaddr_rwlock_grp, "in_ifaddr_rwlock");
323 LCK_RW_DECLARE(in_ifaddr_rwlock, &in_ifaddr_rwlock_grp);
324 
325 /* Protected by in_ifaddr_rwlock */
326 struct in_ifaddrhead in_ifaddrhead;             /* first inet address */
327 struct in_ifaddrhashhead *in_ifaddrhashtbl;     /* inet addr hash table  */
328 
329 #define INADDR_NHASH    61
330 static u_int32_t inaddr_nhash;                  /* hash table size */
331 static u_int32_t inaddr_hashp;                  /* next largest prime */
332 
333 static int ip_getstat SYSCTL_HANDLER_ARGS;
334 struct ipstat ipstat;
335 SYSCTL_PROC(_net_inet_ip, IPCTL_STATS, stats,
336     CTLTYPE_STRUCT | CTLFLAG_RD | CTLFLAG_LOCKED,
337     0, 0, ip_getstat, "S,ipstat",
338     "IP statistics (struct ipstat, netinet/ip_var.h)");
339 
340 #if IPCTL_DEFMTU
341 SYSCTL_INT(_net_inet_ip, IPCTL_DEFMTU, mtu, CTLFLAG_RW | CTLFLAG_LOCKED,
342     &ip_mtu, 0, "Default MTU");
343 #endif /* IPCTL_DEFMTU */
344 
345 #if IPSTEALTH
346 static int      ipstealth = 0;
347 SYSCTL_INT(_net_inet_ip, OID_AUTO, stealth, CTLFLAG_RW | CTLFLAG_LOCKED,
348     &ipstealth, 0, "");
349 #endif /* IPSTEALTH */
350 
351 #if DUMMYNET
352 ip_dn_io_t *ip_dn_io_ptr;
353 #endif /* DUMMYNET */
354 
355 SYSCTL_NODE(_net_inet_ip, OID_AUTO, linklocal,
356     CTLFLAG_RW | CTLFLAG_LOCKED, 0, "link local");
357 
358 struct ip_linklocal_stat ip_linklocal_stat;
359 SYSCTL_STRUCT(_net_inet_ip_linklocal, OID_AUTO, stat,
360     CTLFLAG_RD | CTLFLAG_LOCKED, &ip_linklocal_stat, ip_linklocal_stat,
361     "Number of link local packets with TTL less than 255");
362 
363 SYSCTL_NODE(_net_inet_ip_linklocal, OID_AUTO, in,
364     CTLFLAG_RW | CTLFLAG_LOCKED, 0, "link local input");
365 
366 int ip_linklocal_in_allowbadttl = 1;
367 SYSCTL_INT(_net_inet_ip_linklocal_in, OID_AUTO, allowbadttl,
368     CTLFLAG_RW | CTLFLAG_LOCKED, &ip_linklocal_in_allowbadttl, 0,
369     "Allow incoming link local packets with TTL less than 255");
370 
371 
372 /*
373  * We need to save the IP options in case a protocol wants to respond
374  * to an incoming packet over the same route if the packet got here
375  * using IP source routing.  This allows connection establishment and
376  * maintenance when the remote end is on a network that is not known
377  * to us.
378  */
379 static int      ip_nhops = 0;
380 static  struct ip_srcrt {
381 	struct  in_addr dst;                    /* final destination */
382 	char    nop;                            /* one NOP to align */
383 	char    srcopt[IPOPT_OFFSET + 1];       /* OPTVAL, OLEN and OFFSET */
384 	struct  in_addr route[MAX_IPOPTLEN / sizeof(struct in_addr)];
385 } ip_srcrt;
386 
387 static void in_ifaddrhashtbl_init(void);
388 static void save_rte(u_char *, struct in_addr);
389 static int ip_dooptions(struct mbuf *, int, struct sockaddr_in *);
390 static void ip_forward(struct mbuf *, int, struct sockaddr_in *);
391 static void frag_freef(struct ipqhead *, struct ipq *);
392 static struct mbuf *ip_reass(struct mbuf *);
393 static void ip_fwd_route_copyout(struct ifnet *, struct route *);
394 static void ip_fwd_route_copyin(struct ifnet *, struct route *);
395 static inline u_short ip_cksum(struct mbuf *, int);
396 
397 /*
398  * On platforms which require strict alignment (currently for anything but
399  * i386 or x86_64), check if the IP header pointer is 32-bit aligned; if not,
400  * copy the contents of the mbuf chain into a new chain, and free the original
401  * one.  Create some head room in the first mbuf of the new chain, in case
402  * it's needed later on.
403  */
404 #if defined(__i386__) || defined(__x86_64__)
405 #define IP_HDR_ALIGNMENT_FIXUP(_m, _ifp, _action) do { } while (0)
406 #else /* !__i386__ && !__x86_64__ */
407 #define IP_HDR_ALIGNMENT_FIXUP(_m, _ifp, _action) do {                  \
408 	if (!IP_HDR_ALIGNED_P(mtod(_m, caddr_t))) {                     \
409 	        struct mbuf *_n;                                        \
410 	        struct ifnet *__ifp = (_ifp);                           \
411 	        atomic_add_64(&(__ifp)->if_alignerrs, 1);               \
412 	        if (((_m)->m_flags & M_PKTHDR) &&                       \
413 	            (_m)->m_pkthdr.pkt_hdr != NULL)                     \
414 	                (_m)->m_pkthdr.pkt_hdr = NULL;                  \
415 	        _n = m_defrag_offset(_m, max_linkhdr, M_NOWAIT);        \
416 	        if (_n == NULL) {                                       \
417 	                atomic_add_32(&ipstat.ips_toosmall, 1);         \
418 	                m_freem(_m);                                    \
419 	                (_m) = NULL;                                    \
420 	                _action;                                        \
421 	        } else {                                                \
422 	                VERIFY(_n != (_m));                             \
423 	                (_m) = _n;                                      \
424 	        }                                                       \
425 	}                                                               \
426 } while (0)
427 #endif /* !__i386__ && !__x86_64__ */
428 
429 
430 typedef enum ip_check_if_result {
431 	IP_CHECK_IF_NONE = 0,
432 	IP_CHECK_IF_OURS = 1,
433 	IP_CHECK_IF_DROP = 2,
434 	IP_CHECK_IF_FORWARD = 3
435 } ip_check_if_result_t;
436 
437 static ip_check_if_result_t ip_input_check_interface(struct mbuf **, struct ip *, struct ifnet *);
438 
439 /*
440  * GRE input handler function, settable via ip_gre_register_input() for PPTP.
441  */
442 static gre_input_func_t gre_input_func;
443 
444 static void
ip_init_delayed(void)445 ip_init_delayed(void)
446 {
447 	struct ifreq ifr;
448 	int error;
449 	struct sockaddr_in *sin;
450 
451 	bzero(&ifr, sizeof(ifr));
452 	strlcpy(ifr.ifr_name, "lo0", sizeof(ifr.ifr_name));
453 	sin = (struct sockaddr_in *)(void *)&ifr.ifr_addr;
454 	sin->sin_len = sizeof(struct sockaddr_in);
455 	sin->sin_family = AF_INET;
456 	sin->sin_addr.s_addr = htonl(INADDR_LOOPBACK);
457 	error = in_control(NULL, SIOCSIFADDR, (caddr_t)&ifr, lo_ifp, kernproc);
458 	if (error) {
459 		printf("%s: failed to initialise lo0's address, error=%d\n",
460 		    __func__, error);
461 	}
462 }
463 
464 /*
465  * IP initialization: fill in IP protocol switch table.
466  * All protocols not implemented in kernel go to raw IP protocol handler.
467  */
468 void
ip_init(struct protosw * pp,struct domain * dp)469 ip_init(struct protosw *pp, struct domain *dp)
470 {
471 	static int ip_initialized = 0;
472 	struct protosw *pr;
473 	struct timeval tv;
474 	int i;
475 
476 	domain_proto_mtx_lock_assert_held();
477 	VERIFY((pp->pr_flags & (PR_INITIALIZED | PR_ATTACHED)) == PR_ATTACHED);
478 
479 	/* ipq_alloc() uses mbufs for IP fragment queue structures */
480 	_CASSERT(sizeof(struct ipq) <= _MLEN);
481 
482 	/*
483 	 * Some ioctls (e.g. SIOCAIFADDR) use ifaliasreq struct, which is
484 	 * interchangeable with in_aliasreq; they must have the same size.
485 	 */
486 	_CASSERT(sizeof(struct ifaliasreq) == sizeof(struct in_aliasreq));
487 
488 	if (ip_initialized) {
489 		return;
490 	}
491 	ip_initialized = 1;
492 
493 	in_ifaddr_init();
494 
495 	TAILQ_INIT(&in_ifaddrhead);
496 	in_ifaddrhashtbl_init();
497 
498 	ip_moptions_init();
499 
500 	pr = pffindproto_locked(PF_INET, IPPROTO_RAW, SOCK_RAW);
501 	if (pr == NULL) {
502 		panic("%s: Unable to find [PF_INET,IPPROTO_RAW,SOCK_RAW]",
503 		    __func__);
504 		/* NOTREACHED */
505 	}
506 
507 	/* Initialize the entire ip_protox[] array to IPPROTO_RAW. */
508 	for (i = 0; i < IPPROTO_MAX; i++) {
509 		ip_protox[i] = pr;
510 	}
511 	/*
512 	 * Cycle through IP protocols and put them into the appropriate place
513 	 * in ip_protox[], skipping protocols IPPROTO_{IP,RAW}.
514 	 */
515 	VERIFY(dp == inetdomain && dp->dom_family == PF_INET);
516 	TAILQ_FOREACH(pr, &dp->dom_protosw, pr_entry) {
517 		VERIFY(pr->pr_domain == dp);
518 		if (pr->pr_protocol != 0 && pr->pr_protocol != IPPROTO_RAW) {
519 			/* Be careful to only index valid IP protocols. */
520 			if (pr->pr_protocol < IPPROTO_MAX) {
521 				ip_protox[pr->pr_protocol] = pr;
522 			}
523 		}
524 	}
525 
526 	lck_mtx_lock(&ipqlock);
527 	/* Initialize IP reassembly queue. */
528 	for (i = 0; i < IPREASS_NHASH; i++) {
529 		TAILQ_INIT(&ipq[i]);
530 	}
531 
532 	maxnipq = nmbclusters / 32;
533 	maxfragsperpacket = 128; /* enough for 64k in 512 byte fragments */
534 	ipq_updateparams();
535 	lck_mtx_unlock(&ipqlock);
536 
537 	getmicrotime(&tv);
538 	ip_id = (u_short)(RandomULong() ^ tv.tv_usec);
539 
540 	PE_parse_boot_argn("ip_checkinterface", &i, sizeof(i));
541 	switch (i) {
542 	case IP_CHECKINTERFACE_WEAK_ES:
543 	case IP_CHECKINTERFACE_HYBRID_ES:
544 	case IP_CHECKINTERFACE_STRONG_ES:
545 		ip_checkinterface = i;
546 		break;
547 	default:
548 		break;
549 	}
550 
551 	arp_init();
552 	net_init_add(ip_init_delayed);
553 }
554 
555 /*
556  * Initialize IPv4 source address hash table.
557  */
558 static void
in_ifaddrhashtbl_init(void)559 in_ifaddrhashtbl_init(void)
560 {
561 	int i, k, p;
562 
563 	if (in_ifaddrhashtbl != NULL) {
564 		return;
565 	}
566 
567 	PE_parse_boot_argn("inaddr_nhash", &inaddr_nhash,
568 	    sizeof(inaddr_nhash));
569 	if (inaddr_nhash == 0) {
570 		inaddr_nhash = INADDR_NHASH;
571 	}
572 
573 	in_ifaddrhashtbl = zalloc_permanent(
574 		inaddr_nhash * sizeof(*in_ifaddrhashtbl),
575 		ZALIGN_PTR);
576 
577 	/*
578 	 * Generate the next largest prime greater than inaddr_nhash.
579 	 */
580 	k = (inaddr_nhash % 2 == 0) ? inaddr_nhash + 1 : inaddr_nhash + 2;
581 	for (;;) {
582 		p = 1;
583 		for (i = 3; i * i <= k; i += 2) {
584 			if (k % i == 0) {
585 				p = 0;
586 			}
587 		}
588 		if (p == 1) {
589 			break;
590 		}
591 		k += 2;
592 	}
593 	inaddr_hashp = k;
594 }
595 
596 u_int32_t
inaddr_hashval(u_int32_t key)597 inaddr_hashval(u_int32_t key)
598 {
599 	/*
600 	 * The hash index is the computed prime times the key modulo
601 	 * the hash size, as documented in "Introduction to Algorithms"
602 	 * (Cormen, Leiserson, Rivest).
603 	 */
604 	if (inaddr_nhash > 1) {
605 		return (key * inaddr_hashp) % inaddr_nhash;
606 	} else {
607 		return 0;
608 	}
609 }
610 
611 __private_extern__ void
ip_proto_dispatch_in(struct mbuf * m,int hlen,u_int8_t proto,ipfilter_t inject_ipfref)612 ip_proto_dispatch_in(struct mbuf *m, int hlen, u_int8_t proto,
613     ipfilter_t inject_ipfref)
614 {
615 	struct ipfilter *filter;
616 	int seen = (inject_ipfref == NULL);
617 	int     changed_header = 0;
618 	struct ip *ip;
619 	void (*pr_input)(struct mbuf *, int len);
620 
621 	if (!TAILQ_EMPTY(&ipv4_filters)) {
622 		ipf_ref();
623 		TAILQ_FOREACH(filter, &ipv4_filters, ipf_link) {
624 			if (seen == 0) {
625 				if ((struct ipfilter *)inject_ipfref == filter) {
626 					seen = 1;
627 				}
628 			} else if (filter->ipf_filter.ipf_input) {
629 				errno_t result;
630 
631 				if (changed_header == 0) {
632 					/*
633 					 * Perform IP header alignment fixup,
634 					 * if needed, before passing packet
635 					 * into filter(s).
636 					 */
637 					IP_HDR_ALIGNMENT_FIXUP(m,
638 					    m->m_pkthdr.rcvif, ipf_unref());
639 
640 					/* ipf_unref() already called */
641 					if (m == NULL) {
642 						return;
643 					}
644 
645 					changed_header = 1;
646 					ip = mtod(m, struct ip *);
647 					ip->ip_len = htons(ip->ip_len + (uint16_t)hlen);
648 					ip->ip_off = htons(ip->ip_off);
649 					ip->ip_sum = 0;
650 					ip->ip_sum = ip_cksum_hdr_in(m, hlen);
651 				}
652 				result = filter->ipf_filter.ipf_input(
653 					filter->ipf_filter.cookie, (mbuf_t *)&m,
654 					hlen, proto);
655 				if (result == EJUSTRETURN) {
656 					ipf_unref();
657 					return;
658 				}
659 				if (result != 0) {
660 					ipf_unref();
661 					m_freem(m);
662 					return;
663 				}
664 			}
665 		}
666 		ipf_unref();
667 	}
668 
669 	/* Perform IP header alignment fixup (post-filters), if needed */
670 	IP_HDR_ALIGNMENT_FIXUP(m, m->m_pkthdr.rcvif, return );
671 
672 	ip = mtod(m, struct ip *);
673 
674 	if (changed_header) {
675 		ip->ip_len = ntohs(ip->ip_len) - (u_short)hlen;
676 		ip->ip_off = ntohs(ip->ip_off);
677 	}
678 
679 	/*
680 	 * If there isn't a specific lock for the protocol
681 	 * we're about to call, use the generic lock for AF_INET.
682 	 * otherwise let the protocol deal with its own locking
683 	 */
684 	if ((pr_input = ip_protox[ip->ip_p]->pr_input) == NULL) {
685 		m_freem(m);
686 	} else if (!(ip_protox[ip->ip_p]->pr_flags & PR_PROTOLOCK)) {
687 		lck_mtx_lock(inet_domain_mutex);
688 		pr_input(m, hlen);
689 		lck_mtx_unlock(inet_domain_mutex);
690 	} else {
691 		pr_input(m, hlen);
692 	}
693 }
694 
695 struct pktchain_elm {
696 	struct mbuf     *pkte_head;
697 	struct mbuf     *pkte_tail;
698 	struct in_addr  pkte_saddr;
699 	struct in_addr  pkte_daddr;
700 	uint16_t        pkte_npkts;
701 	uint16_t        pkte_proto;
702 	uint32_t        pkte_nbytes;
703 };
704 
705 typedef struct pktchain_elm pktchain_elm_t;
706 
707 /* Store upto PKTTBL_SZ unique flows on the stack */
708 #define PKTTBL_SZ       7
709 
710 static struct mbuf *
ip_chain_insert(struct mbuf * packet,pktchain_elm_t * tbl)711 ip_chain_insert(struct mbuf *packet, pktchain_elm_t *tbl)
712 {
713 	struct ip*      ip;
714 	int             pkttbl_idx = 0;
715 
716 	ip = mtod(packet, struct ip*);
717 
718 	/* reusing the hash function from inaddr_hashval */
719 	pkttbl_idx = inaddr_hashval(ntohl(ip->ip_src.s_addr)) % PKTTBL_SZ;
720 	if (tbl[pkttbl_idx].pkte_head == NULL) {
721 		tbl[pkttbl_idx].pkte_head = packet;
722 		tbl[pkttbl_idx].pkte_saddr.s_addr = ip->ip_src.s_addr;
723 		tbl[pkttbl_idx].pkte_daddr.s_addr = ip->ip_dst.s_addr;
724 		tbl[pkttbl_idx].pkte_proto = ip->ip_p;
725 	} else {
726 		if ((ip->ip_dst.s_addr == tbl[pkttbl_idx].pkte_daddr.s_addr) &&
727 		    (ip->ip_src.s_addr == tbl[pkttbl_idx].pkte_saddr.s_addr) &&
728 		    (ip->ip_p == tbl[pkttbl_idx].pkte_proto)) {
729 		} else {
730 			return packet;
731 		}
732 	}
733 	if (tbl[pkttbl_idx].pkte_tail != NULL) {
734 		mbuf_setnextpkt(tbl[pkttbl_idx].pkte_tail, packet);
735 	}
736 
737 	tbl[pkttbl_idx].pkte_tail = packet;
738 	tbl[pkttbl_idx].pkte_npkts += 1;
739 	tbl[pkttbl_idx].pkte_nbytes += packet->m_pkthdr.len;
740 	return NULL;
741 }
742 
743 /* args is a dummy variable here for backward compatibility */
744 static void
ip_input_second_pass_loop_tbl(pktchain_elm_t * tbl,struct ip_fw_in_args * args)745 ip_input_second_pass_loop_tbl(pktchain_elm_t *tbl, struct ip_fw_in_args *args)
746 {
747 	int i = 0;
748 
749 	for (i = 0; i < PKTTBL_SZ; i++) {
750 		if (tbl[i].pkte_head != NULL) {
751 			struct mbuf *m = tbl[i].pkte_head;
752 			ip_input_second_pass(m, m->m_pkthdr.rcvif,
753 			    tbl[i].pkte_npkts, tbl[i].pkte_nbytes, args);
754 
755 			if (tbl[i].pkte_npkts > 2) {
756 				ipstat.ips_rxc_chainsz_gt2++;
757 			}
758 			if (tbl[i].pkte_npkts > 4) {
759 				ipstat.ips_rxc_chainsz_gt4++;
760 			}
761 #if (DEBUG || DEVELOPMENT)
762 			if (ip_input_measure) {
763 				net_perf_histogram(&net_perf, tbl[i].pkte_npkts);
764 			}
765 #endif /* (DEBUG || DEVELOPMENT) */
766 			tbl[i].pkte_head = tbl[i].pkte_tail = NULL;
767 			tbl[i].pkte_npkts = 0;
768 			tbl[i].pkte_nbytes = 0;
769 			/* no need to initialize address and protocol in tbl */
770 		}
771 	}
772 }
773 
774 static void
ip_input_cpout_args(struct ip_fw_in_args * args,struct ip_fw_args * args1,boolean_t * done_init)775 ip_input_cpout_args(struct ip_fw_in_args *args, struct ip_fw_args *args1,
776     boolean_t *done_init)
777 {
778 	if (*done_init == FALSE) {
779 		bzero(args1, sizeof(struct ip_fw_args));
780 		*done_init = TRUE;
781 	}
782 	args1->fwa_pf_rule = args->fwai_pf_rule;
783 }
784 
785 static void
ip_input_cpin_args(struct ip_fw_args * args1,struct ip_fw_in_args * args)786 ip_input_cpin_args(struct ip_fw_args *args1, struct ip_fw_in_args *args)
787 {
788 	args->fwai_pf_rule = args1->fwa_pf_rule;
789 }
790 
791 typedef enum {
792 	IPINPUT_DOCHAIN = 0,
793 	IPINPUT_DONTCHAIN,
794 	IPINPUT_FREED,
795 	IPINPUT_DONE
796 } ipinput_chain_ret_t;
797 
798 static void
ip_input_update_nstat(struct ifnet * ifp,struct in_addr src_ip,u_int32_t packets,u_int32_t bytes)799 ip_input_update_nstat(struct ifnet *ifp, struct in_addr src_ip,
800     u_int32_t packets, u_int32_t bytes)
801 {
802 	if (nstat_collect) {
803 		struct rtentry *rt = ifnet_cached_rtlookup_inet(ifp,
804 		    src_ip);
805 		if (rt != NULL) {
806 			nstat_route_rx(rt, packets, bytes, 0);
807 			rtfree(rt);
808 		}
809 	}
810 }
811 
812 static void
ip_input_dispatch_chain(struct mbuf * m)813 ip_input_dispatch_chain(struct mbuf *m)
814 {
815 	struct mbuf *tmp_mbuf = m;
816 	struct mbuf *nxt_mbuf = NULL;
817 	struct ip *ip = NULL;
818 	unsigned int hlen;
819 
820 	ip = mtod(tmp_mbuf, struct ip *);
821 	hlen = IP_VHL_HL(ip->ip_vhl) << 2;
822 	while (tmp_mbuf != NULL) {
823 		nxt_mbuf = mbuf_nextpkt(tmp_mbuf);
824 		mbuf_setnextpkt(tmp_mbuf, NULL);
825 		ip_proto_dispatch_in(tmp_mbuf, hlen, ip->ip_p, 0);
826 		tmp_mbuf = nxt_mbuf;
827 		if (tmp_mbuf) {
828 			ip = mtod(tmp_mbuf, struct ip *);
829 			/* first mbuf of chain already has adjusted ip_len */
830 			hlen = IP_VHL_HL(ip->ip_vhl) << 2;
831 			ip->ip_len -= hlen;
832 		}
833 	}
834 }
835 
836 static void
ip_input_setdst_chain(struct mbuf * m,uint16_t ifindex,struct in_ifaddr * ia)837 ip_input_setdst_chain(struct mbuf *m, uint16_t ifindex, struct in_ifaddr *ia)
838 {
839 	struct mbuf *tmp_mbuf = m;
840 
841 	while (tmp_mbuf != NULL) {
842 		ip_setdstifaddr_info(tmp_mbuf, ifindex, ia);
843 		tmp_mbuf = mbuf_nextpkt(tmp_mbuf);
844 	}
845 }
846 
847 static void
ip_input_adjust(struct mbuf * m,struct ip * ip,struct ifnet * inifp)848 ip_input_adjust(struct mbuf *m, struct ip *ip, struct ifnet *inifp)
849 {
850 	boolean_t adjust = TRUE;
851 
852 	ASSERT(m_pktlen(m) > ip->ip_len);
853 
854 	/*
855 	 * Invalidate hardware checksum info if ip_adj_clear_hwcksum
856 	 * is set; useful to handle buggy drivers.  Note that this
857 	 * should not be enabled by default, as we may get here due
858 	 * to link-layer padding.
859 	 */
860 	if (ip_adj_clear_hwcksum &&
861 	    (m->m_pkthdr.csum_flags & CSUM_DATA_VALID) &&
862 	    !(inifp->if_flags & IFF_LOOPBACK) &&
863 	    !(m->m_pkthdr.pkt_flags & PKTF_LOOP)) {
864 		m->m_pkthdr.csum_flags &= ~CSUM_DATA_VALID;
865 		m->m_pkthdr.csum_data = 0;
866 		ipstat.ips_adj_hwcsum_clr++;
867 	}
868 
869 	/*
870 	 * If partial checksum information is available, subtract
871 	 * out the partial sum of postpended extraneous bytes, and
872 	 * update the checksum metadata accordingly.  By doing it
873 	 * here, the upper layer transport only needs to adjust any
874 	 * prepended extraneous bytes (else it will do both.)
875 	 */
876 	if (ip_adj_partial_sum &&
877 	    (m->m_pkthdr.csum_flags & (CSUM_DATA_VALID | CSUM_PARTIAL)) ==
878 	    (CSUM_DATA_VALID | CSUM_PARTIAL)) {
879 		m->m_pkthdr.csum_rx_val = m_adj_sum16(m,
880 		    m->m_pkthdr.csum_rx_start, m->m_pkthdr.csum_rx_start,
881 		    (ip->ip_len - m->m_pkthdr.csum_rx_start),
882 		    m->m_pkthdr.csum_rx_val);
883 	} else if ((m->m_pkthdr.csum_flags &
884 	    (CSUM_DATA_VALID | CSUM_PARTIAL)) ==
885 	    (CSUM_DATA_VALID | CSUM_PARTIAL)) {
886 		/*
887 		 * If packet has partial checksum info and we decided not
888 		 * to subtract the partial sum of postpended extraneous
889 		 * bytes here (not the default case), leave that work to
890 		 * be handled by the other layers.  For now, only TCP, UDP
891 		 * layers are capable of dealing with this.  For all other
892 		 * protocols (including fragments), trim and ditch the
893 		 * partial sum as those layers might not implement partial
894 		 * checksumming (or adjustment) at all.
895 		 */
896 		if ((ip->ip_off & (IP_MF | IP_OFFMASK)) == 0 &&
897 		    (ip->ip_p == IPPROTO_TCP || ip->ip_p == IPPROTO_UDP)) {
898 			adjust = FALSE;
899 		} else {
900 			m->m_pkthdr.csum_flags &= ~CSUM_DATA_VALID;
901 			m->m_pkthdr.csum_data = 0;
902 			ipstat.ips_adj_hwcsum_clr++;
903 		}
904 	}
905 
906 	if (adjust) {
907 		ipstat.ips_adj++;
908 		if (m->m_len == m->m_pkthdr.len) {
909 			m->m_len = ip->ip_len;
910 			m->m_pkthdr.len = ip->ip_len;
911 		} else {
912 			m_adj(m, ip->ip_len - m->m_pkthdr.len);
913 		}
914 	}
915 }
916 
917 /*
918  * First pass does all essential packet validation and places on a per flow
919  * queue for doing operations that have same outcome for all packets of a flow.
920  */
921 static ipinput_chain_ret_t
ip_input_first_pass(struct mbuf * m,struct ip_fw_in_args * args,struct mbuf ** modm)922 ip_input_first_pass(struct mbuf *m, struct ip_fw_in_args *args, struct mbuf **modm)
923 {
924 	struct ip       *ip;
925 	struct ifnet    *inifp;
926 	unsigned int    hlen;
927 	int             retval = IPINPUT_DOCHAIN;
928 	int             len = 0;
929 	struct in_addr  src_ip;
930 #if DUMMYNET
931 	struct m_tag            *copy;
932 	struct m_tag            *p;
933 	boolean_t               delete = FALSE;
934 	struct ip_fw_args       args1;
935 	boolean_t               init = FALSE;
936 #endif /* DUMMYNET */
937 	ipfilter_t inject_filter_ref = NULL;
938 
939 	/* Check if the mbuf is still valid after interface filter processing */
940 	MBUF_INPUT_CHECK(m, m->m_pkthdr.rcvif);
941 	inifp = mbuf_pkthdr_rcvif(m);
942 	VERIFY(inifp != NULL);
943 
944 	/* Perform IP header alignment fixup, if needed */
945 	IP_HDR_ALIGNMENT_FIXUP(m, inifp, goto bad);
946 
947 	m->m_pkthdr.pkt_flags &= ~PKTF_FORWARDED;
948 
949 #if DUMMYNET
950 	/*
951 	 * Don't bother searching for tag(s) if there's none.
952 	 */
953 	if (SLIST_EMPTY(&m->m_pkthdr.tags)) {
954 		goto ipfw_tags_done;
955 	}
956 
957 	/* Grab info from mtags prepended to the chain */
958 	p = m_tag_first(m);
959 	while (p) {
960 		if (p->m_tag_id == KERNEL_MODULE_TAG_ID) {
961 			if (p->m_tag_type == KERNEL_TAG_TYPE_DUMMYNET) {
962 				struct dn_pkt_tag *dn_tag;
963 
964 				dn_tag = (struct dn_pkt_tag *)(p + 1);
965 				args->fwai_pf_rule = dn_tag->dn_pf_rule;
966 				delete = TRUE;
967 			}
968 
969 			if (delete) {
970 				copy = p;
971 				p = m_tag_next(m, p);
972 				m_tag_delete(m, copy);
973 			} else {
974 				p = m_tag_next(m, p);
975 			}
976 		} else {
977 			p = m_tag_next(m, p);
978 		}
979 	}
980 
981 #if DIAGNOSTIC
982 	if (m == NULL || !(m->m_flags & M_PKTHDR)) {
983 		panic("ip_input no HDR");
984 	}
985 #endif
986 
987 	if (args->fwai_pf_rule) {
988 		/* dummynet already filtered us */
989 		ip = mtod(m, struct ip *);
990 		hlen = IP_VHL_HL(ip->ip_vhl) << 2;
991 		inject_filter_ref = ipf_get_inject_filter(m);
992 		if (args->fwai_pf_rule) {
993 			goto check_with_pf;
994 		}
995 	}
996 ipfw_tags_done:
997 #endif /* DUMMYNET */
998 
999 	/*
1000 	 * No need to process packet twice if we've already seen it.
1001 	 */
1002 	if (!SLIST_EMPTY(&m->m_pkthdr.tags)) {
1003 		inject_filter_ref = ipf_get_inject_filter(m);
1004 	}
1005 	if (inject_filter_ref != NULL) {
1006 		ip = mtod(m, struct ip *);
1007 		hlen = IP_VHL_HL(ip->ip_vhl) << 2;
1008 
1009 		DTRACE_IP6(receive, struct mbuf *, m, struct inpcb *, NULL,
1010 		    struct ip *, ip, struct ifnet *, inifp,
1011 		    struct ip *, ip, struct ip6_hdr *, NULL);
1012 
1013 		ip->ip_len = ntohs(ip->ip_len) - (u_short)hlen;
1014 		ip->ip_off = ntohs(ip->ip_off);
1015 		ip_proto_dispatch_in(m, hlen, ip->ip_p, inject_filter_ref);
1016 		return IPINPUT_DONE;
1017 	}
1018 
1019 	if (__improbable(m->m_pkthdr.pkt_flags & PKTF_WAKE_PKT)) {
1020 		if_ports_used_match_mbuf(inifp, PF_INET, m);
1021 	}
1022 
1023 	if (m->m_pkthdr.len < sizeof(struct ip)) {
1024 		OSAddAtomic(1, &ipstat.ips_total);
1025 		OSAddAtomic(1, &ipstat.ips_tooshort);
1026 		m_freem(m);
1027 		return IPINPUT_FREED;
1028 	}
1029 
1030 	if (m->m_len < sizeof(struct ip) &&
1031 	    (m = m_pullup(m, sizeof(struct ip))) == NULL) {
1032 		OSAddAtomic(1, &ipstat.ips_total);
1033 		OSAddAtomic(1, &ipstat.ips_toosmall);
1034 		return IPINPUT_FREED;
1035 	}
1036 
1037 	ip = mtod(m, struct ip *);
1038 	*modm = m;
1039 
1040 	KERNEL_DEBUG(DBG_LAYER_BEG, ip->ip_dst.s_addr, ip->ip_src.s_addr,
1041 	    ip->ip_p, ip->ip_off, ip->ip_len);
1042 
1043 	if (IP_VHL_V(ip->ip_vhl) != IPVERSION) {
1044 		OSAddAtomic(1, &ipstat.ips_total);
1045 		OSAddAtomic(1, &ipstat.ips_badvers);
1046 		KERNEL_DEBUG(DBG_LAYER_END, 0, 0, 0, 0, 0);
1047 		m_freem(m);
1048 		return IPINPUT_FREED;
1049 	}
1050 
1051 	hlen = IP_VHL_HL(ip->ip_vhl) << 2;
1052 	if (hlen < sizeof(struct ip)) {
1053 		OSAddAtomic(1, &ipstat.ips_total);
1054 		OSAddAtomic(1, &ipstat.ips_badhlen);
1055 		KERNEL_DEBUG(DBG_LAYER_END, 0, 0, 0, 0, 0);
1056 		m_freem(m);
1057 		return IPINPUT_FREED;
1058 	}
1059 
1060 	if (hlen > m->m_len) {
1061 		if ((m = m_pullup(m, hlen)) == NULL) {
1062 			OSAddAtomic(1, &ipstat.ips_total);
1063 			OSAddAtomic(1, &ipstat.ips_badhlen);
1064 			KERNEL_DEBUG(DBG_LAYER_END, 0, 0, 0, 0, 0);
1065 			return IPINPUT_FREED;
1066 		}
1067 		ip = mtod(m, struct ip *);
1068 		*modm = m;
1069 	}
1070 
1071 	/* 127/8 must not appear on wire - RFC1122 */
1072 	if ((ntohl(ip->ip_dst.s_addr) >> IN_CLASSA_NSHIFT) == IN_LOOPBACKNET ||
1073 	    (ntohl(ip->ip_src.s_addr) >> IN_CLASSA_NSHIFT) == IN_LOOPBACKNET) {
1074 		/*
1075 		 * Allow for the following exceptions:
1076 		 *
1077 		 *   1. If the packet was sent to loopback (i.e. rcvif
1078 		 *      would have been set earlier at output time.)
1079 		 *
1080 		 *   2. If the packet was sent out on loopback from a local
1081 		 *      source address which belongs to a non-loopback
1082 		 *      interface (i.e. rcvif may not necessarily be a
1083 		 *      loopback interface, hence the test for PKTF_LOOP.)
1084 		 *      Unlike IPv6, there is no interface scope ID, and
1085 		 *      therefore we don't care so much about PKTF_IFINFO.
1086 		 */
1087 		if (!(inifp->if_flags & IFF_LOOPBACK) &&
1088 		    !(m->m_pkthdr.pkt_flags & PKTF_LOOP)) {
1089 			OSAddAtomic(1, &ipstat.ips_total);
1090 			OSAddAtomic(1, &ipstat.ips_badaddr);
1091 			KERNEL_DEBUG(DBG_LAYER_END, 0, 0, 0, 0, 0);
1092 			m_freem(m);
1093 			return IPINPUT_FREED;
1094 		}
1095 	}
1096 
1097 	/* IPv4 Link-Local Addresses as defined in RFC3927 */
1098 	if ((IN_LINKLOCAL(ntohl(ip->ip_dst.s_addr)) ||
1099 	    IN_LINKLOCAL(ntohl(ip->ip_src.s_addr)))) {
1100 		ip_linklocal_stat.iplls_in_total++;
1101 		if (ip->ip_ttl != MAXTTL) {
1102 			OSAddAtomic(1, &ip_linklocal_stat.iplls_in_badttl);
1103 			/* Silently drop link local traffic with bad TTL */
1104 			if (!ip_linklocal_in_allowbadttl) {
1105 				OSAddAtomic(1, &ipstat.ips_total);
1106 				KERNEL_DEBUG(DBG_LAYER_END, 0, 0, 0, 0, 0);
1107 				m_freem(m);
1108 				return IPINPUT_FREED;
1109 			}
1110 		}
1111 	}
1112 
1113 	if (ip_cksum(m, hlen)) {
1114 		OSAddAtomic(1, &ipstat.ips_total);
1115 		KERNEL_DEBUG(DBG_LAYER_END, 0, 0, 0, 0, 0);
1116 		m_freem(m);
1117 		return IPINPUT_FREED;
1118 	}
1119 
1120 	DTRACE_IP6(receive, struct mbuf *, m, struct inpcb *, NULL,
1121 	    struct ip *, ip, struct ifnet *, inifp,
1122 	    struct ip *, ip, struct ip6_hdr *, NULL);
1123 
1124 	/*
1125 	 * Convert fields to host representation.
1126 	 */
1127 #if BYTE_ORDER != BIG_ENDIAN
1128 	NTOHS(ip->ip_len);
1129 #endif
1130 
1131 	if (ip->ip_len < hlen) {
1132 		OSAddAtomic(1, &ipstat.ips_total);
1133 		OSAddAtomic(1, &ipstat.ips_badlen);
1134 		KERNEL_DEBUG(DBG_LAYER_END, 0, 0, 0, 0, 0);
1135 		m_freem(m);
1136 		return IPINPUT_FREED;
1137 	}
1138 
1139 #if BYTE_ORDER != BIG_ENDIAN
1140 	NTOHS(ip->ip_off);
1141 #endif
1142 
1143 	/*
1144 	 * Check that the amount of data in the buffers
1145 	 * is as at least much as the IP header would have us expect.
1146 	 * Trim mbufs if longer than we expect.
1147 	 * Drop packet if shorter than we expect.
1148 	 */
1149 	if (m->m_pkthdr.len < ip->ip_len) {
1150 		OSAddAtomic(1, &ipstat.ips_total);
1151 		OSAddAtomic(1, &ipstat.ips_tooshort);
1152 		KERNEL_DEBUG(DBG_LAYER_END, 0, 0, 0, 0, 0);
1153 		m_freem(m);
1154 		return IPINPUT_FREED;
1155 	}
1156 
1157 	if (m->m_pkthdr.len > ip->ip_len) {
1158 		ip_input_adjust(m, ip, inifp);
1159 	}
1160 
1161 	/* for netstat route statistics */
1162 	src_ip = ip->ip_src;
1163 	len = m->m_pkthdr.len;
1164 
1165 #if DUMMYNET
1166 check_with_pf:
1167 #endif /* DUMMYNET */
1168 #if PF
1169 	/* Invoke inbound packet filter */
1170 	if (PF_IS_ENABLED) {
1171 		int error;
1172 		ip_input_cpout_args(args, &args1, &init);
1173 		ip = mtod(m, struct ip *);
1174 		src_ip = ip->ip_src;
1175 
1176 #if DUMMYNET
1177 		error = pf_af_hook(inifp, NULL, &m, AF_INET, TRUE, &args1);
1178 #else
1179 		error = pf_af_hook(inifp, NULL, &m, AF_INET, TRUE, NULL);
1180 #endif /* DUMMYNET */
1181 		if (error != 0 || m == NULL) {
1182 			if (m != NULL) {
1183 				panic("%s: unexpected packet %p",
1184 				    __func__, m);
1185 				/* NOTREACHED */
1186 			}
1187 			/* Already freed by callee */
1188 			ip_input_update_nstat(inifp, src_ip, 1, len);
1189 			KERNEL_DEBUG(DBG_LAYER_END, 0, 0, 0, 0, 0);
1190 			OSAddAtomic(1, &ipstat.ips_total);
1191 			return IPINPUT_FREED;
1192 		}
1193 		ip = mtod(m, struct ip *);
1194 		hlen = IP_VHL_HL(ip->ip_vhl) << 2;
1195 		*modm = m;
1196 		ip_input_cpin_args(&args1, args);
1197 	}
1198 #endif /* PF */
1199 
1200 #if IPSEC
1201 	if (ipsec_bypass == 0 && ipsec_gethist(m, NULL)) {
1202 		retval = IPINPUT_DONTCHAIN; /* XXX scope for chaining here? */
1203 		goto pass;
1204 	}
1205 #endif
1206 
1207 #if IPSEC
1208 pass:
1209 #endif
1210 	/*
1211 	 * Process options and, if not destined for us,
1212 	 * ship it on.  ip_dooptions returns 1 when an
1213 	 * error was detected (causing an icmp message
1214 	 * to be sent and the original packet to be freed).
1215 	 */
1216 	ip_nhops = 0;           /* for source routed packets */
1217 	if (hlen > sizeof(struct ip) && ip_dooptions(m, 0, NULL)) {
1218 		src_ip = ip->ip_src;
1219 		ip_input_update_nstat(inifp, src_ip, 1, len);
1220 		KERNEL_DEBUG(DBG_LAYER_END, 0, 0, 0, 0, 0);
1221 		OSAddAtomic(1, &ipstat.ips_total);
1222 		return IPINPUT_FREED;
1223 	}
1224 
1225 	/*
1226 	 * Don't chain fragmented packets
1227 	 */
1228 	if (ip->ip_off & ~(IP_DF | IP_RF)) {
1229 		return IPINPUT_DONTCHAIN;
1230 	}
1231 
1232 	/* Allow DHCP/BootP responses through */
1233 	if ((inifp->if_eflags & IFEF_AUTOCONFIGURING) &&
1234 	    hlen == sizeof(struct ip) && ip->ip_p == IPPROTO_UDP) {
1235 		struct udpiphdr *ui;
1236 
1237 		if (m->m_len < sizeof(struct udpiphdr) &&
1238 		    (m = m_pullup(m, sizeof(struct udpiphdr))) == NULL) {
1239 			OSAddAtomic(1, &udpstat.udps_hdrops);
1240 			KERNEL_DEBUG(DBG_LAYER_END, 0, 0, 0, 0, 0);
1241 			OSAddAtomic(1, &ipstat.ips_total);
1242 			return IPINPUT_FREED;
1243 		}
1244 		*modm = m;
1245 		ui = mtod(m, struct udpiphdr *);
1246 		if (ntohs(ui->ui_dport) == IPPORT_BOOTPC) {
1247 			ip_setdstifaddr_info(m, inifp->if_index, NULL);
1248 			return IPINPUT_DONTCHAIN;
1249 		}
1250 	}
1251 
1252 	/* Avoid chaining raw sockets as ipsec checks occur later for them */
1253 	if (ip_protox[ip->ip_p]->pr_flags & PR_LASTHDR) {
1254 		return IPINPUT_DONTCHAIN;
1255 	}
1256 
1257 	return retval;
1258 #if !defined(__i386__) && !defined(__x86_64__)
1259 bad:
1260 	m_freem(m);
1261 	return IPINPUT_FREED;
1262 #endif
1263 }
1264 
1265 /*
1266  * Because the call to m_pullup() may freem the mbuf, the function frees the mbuf packet
1267  * chain before it return IP_CHECK_IF_DROP
1268  */
1269 static ip_check_if_result_t
ip_input_check_interface(struct mbuf ** mp,struct ip * ip,struct ifnet * inifp)1270 ip_input_check_interface(struct mbuf **mp, struct ip *ip, struct ifnet *inifp)
1271 {
1272 	struct mbuf *m = *mp;
1273 	struct in_ifaddr *ia = NULL;
1274 	struct in_ifaddr *best_ia = NULL;
1275 	struct ifnet *match_ifp = NULL;
1276 	ip_check_if_result_t result = IP_CHECK_IF_NONE;
1277 
1278 	/*
1279 	 * Host broadcast and all network broadcast addresses are always a match
1280 	 */
1281 	if (ip->ip_dst.s_addr == (u_int32_t)INADDR_BROADCAST ||
1282 	    ip->ip_dst.s_addr == INADDR_ANY) {
1283 		ip_input_setdst_chain(m, inifp->if_index, NULL);
1284 		return IP_CHECK_IF_OURS;
1285 	}
1286 
1287 	/*
1288 	 * Check for a match in the hash bucket.
1289 	 */
1290 	lck_rw_lock_shared(&in_ifaddr_rwlock);
1291 	TAILQ_FOREACH(ia, INADDR_HASH(ip->ip_dst.s_addr), ia_hash) {
1292 		if (IA_SIN(ia)->sin_addr.s_addr == ip->ip_dst.s_addr) {
1293 			best_ia = ia;
1294 			match_ifp = best_ia->ia_ifp;
1295 
1296 			if (ia->ia_ifp == inifp || (inifp->if_flags & IFF_LOOPBACK) ||
1297 			    (m->m_pkthdr.pkt_flags & PKTF_LOOP)) {
1298 				/*
1299 				 * A locally originated packet or packet from the loopback
1300 				 * interface is always an exact interface address match
1301 				 */
1302 				match_ifp = inifp;
1303 				break;
1304 			}
1305 			/*
1306 			 * Continue the loop in case there's a exact match with another
1307 			 * interface
1308 			 */
1309 		}
1310 	}
1311 	if (best_ia != NULL) {
1312 		if (match_ifp != inifp && ipforwarding == 0 &&
1313 		    ((ip_checkinterface == IP_CHECKINTERFACE_HYBRID_ES &&
1314 		    (match_ifp->if_family == IFNET_FAMILY_IPSEC ||
1315 		    match_ifp->if_family == IFNET_FAMILY_UTUN)) ||
1316 		    ip_checkinterface == IP_CHECKINTERFACE_STRONG_ES)) {
1317 			/*
1318 			 * Drop when interface address check is strict and forwarding
1319 			 * is disabled
1320 			 */
1321 			result = IP_CHECK_IF_DROP;
1322 		} else {
1323 			result = IP_CHECK_IF_OURS;
1324 			ip_input_setdst_chain(m, 0, best_ia);
1325 		}
1326 	}
1327 	lck_rw_done(&in_ifaddr_rwlock);
1328 
1329 	if (result == IP_CHECK_IF_NONE && (inifp->if_flags & IFF_BROADCAST)) {
1330 		/*
1331 		 * Check for broadcast addresses.
1332 		 *
1333 		 * Only accept broadcast packets that arrive via the matching
1334 		 * interface.  Reception of forwarded directed broadcasts would be
1335 		 * handled via ip_forward() and ether_frameout() with the loopback
1336 		 * into the stack for SIMPLEX interfaces handled by ether_frameout().
1337 		 */
1338 		struct ifaddr *ifa;
1339 
1340 		ifnet_lock_shared(inifp);
1341 		TAILQ_FOREACH(ifa, &inifp->if_addrhead, ifa_link) {
1342 			if (ifa->ifa_addr->sa_family != AF_INET) {
1343 				continue;
1344 			}
1345 			ia = ifatoia(ifa);
1346 			if (satosin(&ia->ia_broadaddr)->sin_addr.s_addr == ip->ip_dst.s_addr ||
1347 			    ia->ia_netbroadcast.s_addr == ip->ip_dst.s_addr) {
1348 				ip_input_setdst_chain(m, 0, ia);
1349 				result = IP_CHECK_IF_OURS;
1350 				match_ifp = inifp;
1351 				break;
1352 			}
1353 		}
1354 		ifnet_lock_done(inifp);
1355 	}
1356 
1357 	/* Allow DHCP/BootP responses through */
1358 	if (result == IP_CHECK_IF_NONE && (inifp->if_eflags & IFEF_AUTOCONFIGURING) &&
1359 	    ip->ip_p == IPPROTO_UDP && (IP_VHL_HL(ip->ip_vhl) << 2) == sizeof(struct ip)) {
1360 		struct udpiphdr *ui;
1361 
1362 		if (m->m_len < sizeof(struct udpiphdr)) {
1363 			if ((m = m_pullup(m, sizeof(struct udpiphdr))) == NULL) {
1364 				OSAddAtomic(1, &udpstat.udps_hdrops);
1365 				*mp = NULL;
1366 				return IP_CHECK_IF_DROP;
1367 			}
1368 			/*
1369 			 * m_pullup can return a different mbuf
1370 			 */
1371 			*mp = m;
1372 			ip = mtod(m, struct ip *);
1373 		}
1374 		ui = mtod(m, struct udpiphdr *);
1375 		if (ntohs(ui->ui_dport) == IPPORT_BOOTPC) {
1376 			ip_input_setdst_chain(m, inifp->if_index, NULL);
1377 			result = IP_CHECK_IF_OURS;
1378 			match_ifp = inifp;
1379 		}
1380 	}
1381 
1382 	if (result == IP_CHECK_IF_NONE) {
1383 		if (ipforwarding == 0) {
1384 			result = IP_CHECK_IF_DROP;
1385 		} else {
1386 			result = IP_CHECK_IF_FORWARD;
1387 			ip_input_setdst_chain(m, inifp->if_index, NULL);
1388 		}
1389 	}
1390 
1391 	if (result == IP_CHECK_IF_OURS && match_ifp != inifp) {
1392 		ipstat.ips_rcv_if_weak_match++;
1393 
1394 		/*  Logging is too noisy when forwarding is enabled */
1395 		if (ip_checkinterface_debug != 0 && ipforwarding == 0) {
1396 			char src_str[MAX_IPv4_STR_LEN];
1397 			char dst_str[MAX_IPv4_STR_LEN];
1398 
1399 			inet_ntop(AF_INET, &ip->ip_src, src_str, sizeof(src_str));
1400 			inet_ntop(AF_INET, &ip->ip_dst, dst_str, sizeof(dst_str));
1401 			os_log_info(OS_LOG_DEFAULT,
1402 			    "%s: weak ES interface match to %s for packet from %s to %s proto %u received via %s",
1403 			    __func__, best_ia->ia_ifp->if_xname, src_str, dst_str, ip->ip_p, inifp->if_xname);
1404 		}
1405 	} else if (result == IP_CHECK_IF_DROP) {
1406 		if (ip_checkinterface_debug > 0) {
1407 			char src_str[MAX_IPv4_STR_LEN];
1408 			char dst_str[MAX_IPv4_STR_LEN];
1409 
1410 			inet_ntop(AF_INET, &ip->ip_src, src_str, sizeof(src_str));
1411 			inet_ntop(AF_INET, &ip->ip_dst, dst_str, sizeof(dst_str));
1412 			os_log(OS_LOG_DEFAULT,
1413 			    "%s: no interface match for packet from %s to %s proto %u received via %s",
1414 			    __func__, src_str, dst_str, ip->ip_p, inifp->if_xname);
1415 		}
1416 		struct mbuf *tmp_mbuf = m;
1417 		while (tmp_mbuf != NULL) {
1418 			ipstat.ips_rcv_if_no_match++;
1419 			tmp_mbuf = tmp_mbuf->m_nextpkt;
1420 		}
1421 		m_freem_list(m);
1422 		*mp = NULL;
1423 	}
1424 
1425 	return result;
1426 }
1427 
1428 static void
ip_input_second_pass(struct mbuf * m,struct ifnet * inifp,int npkts_in_chain,int bytes_in_chain,struct ip_fw_in_args * args)1429 ip_input_second_pass(struct mbuf *m, struct ifnet *inifp,
1430     int npkts_in_chain, int bytes_in_chain, struct ip_fw_in_args *args)
1431 {
1432 	struct mbuf             *tmp_mbuf = NULL;
1433 	unsigned int            hlen;
1434 
1435 #pragma unused (args)
1436 
1437 	struct ip *ip = mtod(m, struct ip *);
1438 	hlen = IP_VHL_HL(ip->ip_vhl) << 2;
1439 
1440 	OSAddAtomic(npkts_in_chain, &ipstat.ips_total);
1441 
1442 	/*
1443 	 * Naively assume we can attribute inbound data to the route we would
1444 	 * use to send to this destination. Asymmetric routing breaks this
1445 	 * assumption, but it still allows us to account for traffic from
1446 	 * a remote node in the routing table.
1447 	 * this has a very significant performance impact so we bypass
1448 	 * if nstat_collect is disabled. We may also bypass if the
1449 	 * protocol is tcp in the future because tcp will have a route that
1450 	 * we can use to attribute the data to. That does mean we would not
1451 	 * account for forwarded tcp traffic.
1452 	 */
1453 	ip_input_update_nstat(inifp, ip->ip_src, npkts_in_chain,
1454 	    bytes_in_chain);
1455 
1456 	/*
1457 	 * Check our list of addresses, to see if the packet is for us.
1458 	 * If we don't have any addresses, assume any unicast packet
1459 	 * we receive might be for us (and let the upper layers deal
1460 	 * with it).
1461 	 */
1462 	tmp_mbuf = m;
1463 	if (TAILQ_EMPTY(&in_ifaddrhead)) {
1464 		while (tmp_mbuf != NULL) {
1465 			if (!(tmp_mbuf->m_flags & (M_MCAST | M_BCAST))) {
1466 				ip_setdstifaddr_info(tmp_mbuf, inifp->if_index,
1467 				    NULL);
1468 			}
1469 			tmp_mbuf = mbuf_nextpkt(tmp_mbuf);
1470 		}
1471 		goto ours;
1472 	}
1473 
1474 	/*
1475 	 * Enable a consistency check between the destination address
1476 	 * and the arrival interface for a unicast packet (the RFC 1122
1477 	 * strong ES model) if IP forwarding is disabled and the packet
1478 	 * is not locally generated
1479 	 *
1480 	 * XXX - Checking also should be disabled if the destination
1481 	 * address is ipnat'ed to a different interface.
1482 	 *
1483 	 * XXX - Checking is incompatible with IP aliases added
1484 	 * to the loopback interface instead of the interface where
1485 	 * the packets are received.
1486 	 */
1487 	if (!IN_MULTICAST(ntohl(ip->ip_dst.s_addr))) {
1488 		ip_check_if_result_t ip_check_if_result = IP_CHECK_IF_NONE;
1489 
1490 		ip_check_if_result = ip_input_check_interface(&m, ip, inifp);
1491 		ASSERT(ip_check_if_result != IP_CHECK_IF_NONE);
1492 		if (ip_check_if_result == IP_CHECK_IF_OURS) {
1493 			goto ours;
1494 		} else if (ip_check_if_result == IP_CHECK_IF_DROP) {
1495 			return;
1496 		}
1497 	} else {
1498 		struct in_multi *inm;
1499 		/*
1500 		 * See if we belong to the destination multicast group on the
1501 		 * arrival interface.
1502 		 */
1503 		in_multihead_lock_shared();
1504 		IN_LOOKUP_MULTI(&ip->ip_dst, inifp, inm);
1505 		in_multihead_lock_done();
1506 		if (inm == NULL) {
1507 			OSAddAtomic(npkts_in_chain, &ipstat.ips_notmember);
1508 			m_freem_list(m);
1509 			KERNEL_DEBUG(DBG_LAYER_END, 0, 0, 0, 0, 0);
1510 			return;
1511 		}
1512 		ip_input_setdst_chain(m, inifp->if_index, NULL);
1513 		INM_REMREF(inm);
1514 		goto ours;
1515 	}
1516 
1517 	tmp_mbuf = m;
1518 	struct mbuf *nxt_mbuf = NULL;
1519 	while (tmp_mbuf != NULL) {
1520 		nxt_mbuf = mbuf_nextpkt(tmp_mbuf);
1521 		/*
1522 		 * Not for us; forward if possible and desirable.
1523 		 */
1524 		mbuf_setnextpkt(tmp_mbuf, NULL);
1525 		if (ipforwarding == 0) {
1526 			OSAddAtomic(1, &ipstat.ips_cantforward);
1527 			m_freem(tmp_mbuf);
1528 		} else {
1529 			ip_forward(tmp_mbuf, 0, NULL);
1530 		}
1531 		tmp_mbuf = nxt_mbuf;
1532 	}
1533 	KERNEL_DEBUG(DBG_LAYER_END, 0, 0, 0, 0, 0);
1534 	return;
1535 ours:
1536 	ip = mtod(m, struct ip *); /* in case it changed */
1537 	/*
1538 	 * If offset is set, must reassemble.
1539 	 */
1540 	if (ip->ip_off & ~(IP_DF | IP_RF)) {
1541 		VERIFY(npkts_in_chain == 1);
1542 		m = ip_reass(m);
1543 		if (m == NULL) {
1544 			return;
1545 		}
1546 		ip = mtod(m, struct ip *);
1547 		/* Get the header length of the reassembled packet */
1548 		hlen = IP_VHL_HL(ip->ip_vhl) << 2;
1549 	}
1550 
1551 	/*
1552 	 * Further protocols expect the packet length to be w/o the
1553 	 * IP header.
1554 	 */
1555 	ip->ip_len -= hlen;
1556 
1557 #if IPSEC
1558 	/*
1559 	 * enforce IPsec policy checking if we are seeing last header.
1560 	 * note that we do not visit this with protocols with pcb layer
1561 	 * code - like udp/tcp/raw ip.
1562 	 */
1563 	if (ipsec_bypass == 0 && (ip_protox[ip->ip_p]->pr_flags & PR_LASTHDR)) {
1564 		VERIFY(npkts_in_chain == 1);
1565 		if (ipsec4_in_reject(m, NULL)) {
1566 			IPSEC_STAT_INCREMENT(ipsecstat.in_polvio);
1567 			goto bad;
1568 		}
1569 	}
1570 #endif /* IPSEC */
1571 
1572 	/*
1573 	 * Switch out to protocol's input routine.
1574 	 */
1575 	OSAddAtomic(npkts_in_chain, &ipstat.ips_delivered);
1576 
1577 	ip_input_dispatch_chain(m);
1578 
1579 	KERNEL_DEBUG(DBG_LAYER_END, 0, 0, 0, 0, 0);
1580 	return;
1581 bad:
1582 	KERNEL_DEBUG(DBG_LAYER_END, 0, 0, 0, 0, 0);
1583 	m_freem(m);
1584 }
1585 
1586 void
ip_input_process_list(struct mbuf * packet_list)1587 ip_input_process_list(struct mbuf *packet_list)
1588 {
1589 	pktchain_elm_t  pktchain_tbl[PKTTBL_SZ];
1590 
1591 	struct mbuf     *packet = NULL;
1592 	struct mbuf     *modm = NULL; /* modified mbuf */
1593 	int             retval = 0;
1594 #if (DEBUG || DEVELOPMENT)
1595 	struct timeval start_tv;
1596 #endif /* (DEBUG || DEVELOPMENT) */
1597 	int     num_pkts = 0;
1598 	int chain = 0;
1599 	struct ip_fw_in_args       args;
1600 
1601 	if (ip_chaining == 0) {
1602 		struct mbuf *m = packet_list;
1603 #if (DEBUG || DEVELOPMENT)
1604 		if (ip_input_measure) {
1605 			net_perf_start_time(&net_perf, &start_tv);
1606 		}
1607 #endif /* (DEBUG || DEVELOPMENT) */
1608 
1609 		while (m) {
1610 			packet_list = mbuf_nextpkt(m);
1611 			mbuf_setnextpkt(m, NULL);
1612 			ip_input(m);
1613 			m = packet_list;
1614 			num_pkts++;
1615 		}
1616 #if (DEBUG || DEVELOPMENT)
1617 		if (ip_input_measure) {
1618 			net_perf_measure_time(&net_perf, &start_tv, num_pkts);
1619 		}
1620 #endif /* (DEBUG || DEVELOPMENT) */
1621 		return;
1622 	}
1623 #if (DEBUG || DEVELOPMENT)
1624 	if (ip_input_measure) {
1625 		net_perf_start_time(&net_perf, &start_tv);
1626 	}
1627 #endif /* (DEBUG || DEVELOPMENT) */
1628 
1629 	bzero(&pktchain_tbl, sizeof(pktchain_tbl));
1630 restart_list_process:
1631 	chain = 0;
1632 	for (packet = packet_list; packet; packet = packet_list) {
1633 		m_add_crumb(packet, PKT_CRUMB_IP_INPUT);
1634 
1635 		packet_list = mbuf_nextpkt(packet);
1636 		mbuf_setnextpkt(packet, NULL);
1637 
1638 		num_pkts++;
1639 		modm = NULL;
1640 		bzero(&args, sizeof(args));
1641 
1642 		retval = ip_input_first_pass(packet, &args, &modm);
1643 
1644 		if (retval == IPINPUT_DOCHAIN) {
1645 			if (modm) {
1646 				packet = modm;
1647 			}
1648 			packet = ip_chain_insert(packet, &pktchain_tbl[0]);
1649 			if (packet == NULL) {
1650 				ipstat.ips_rxc_chained++;
1651 				chain++;
1652 				if (chain > ip_chainsz) {
1653 					break;
1654 				}
1655 			} else {
1656 				ipstat.ips_rxc_collisions++;
1657 				break;
1658 			}
1659 		} else if (retval == IPINPUT_DONTCHAIN) {
1660 			/* in order to preserve order, exit from chaining */
1661 			if (modm) {
1662 				packet = modm;
1663 			}
1664 			ipstat.ips_rxc_notchain++;
1665 			break;
1666 		} else {
1667 			/* packet was freed or delivered, do nothing. */
1668 		}
1669 	}
1670 
1671 	/* do second pass here for pktchain_tbl */
1672 	if (chain) {
1673 		ip_input_second_pass_loop_tbl(&pktchain_tbl[0], &args);
1674 	}
1675 
1676 	if (packet) {
1677 		/*
1678 		 * equivalent update in chaining case if performed in
1679 		 * ip_input_second_pass_loop_tbl().
1680 		 */
1681 #if (DEBUG || DEVELOPMENT)
1682 		if (ip_input_measure) {
1683 			net_perf_histogram(&net_perf, 1);
1684 		}
1685 #endif /* (DEBUG || DEVELOPMENT) */
1686 		ip_input_second_pass(packet, packet->m_pkthdr.rcvif,
1687 		    1, packet->m_pkthdr.len, &args);
1688 	}
1689 
1690 	if (packet_list) {
1691 		goto restart_list_process;
1692 	}
1693 
1694 #if (DEBUG || DEVELOPMENT)
1695 	if (ip_input_measure) {
1696 		net_perf_measure_time(&net_perf, &start_tv, num_pkts);
1697 	}
1698 #endif /* (DEBUG || DEVELOPMENT) */
1699 }
1700 /*
1701  * Ip input routine.  Checksum and byte swap header.  If fragmented
1702  * try to reassemble.  Process options.  Pass to next level.
1703  */
1704 void
ip_input(struct mbuf * m)1705 ip_input(struct mbuf *m)
1706 {
1707 	struct ip *ip;
1708 	unsigned int hlen;
1709 	u_short sum = 0;
1710 #if DUMMYNET
1711 	struct ip_fw_args args;
1712 	struct m_tag    *tag;
1713 #endif
1714 	ipfilter_t inject_filter_ref = NULL;
1715 	struct ifnet *inifp;
1716 
1717 	/* Check if the mbuf is still valid after interface filter processing */
1718 	MBUF_INPUT_CHECK(m, m->m_pkthdr.rcvif);
1719 	inifp = m->m_pkthdr.rcvif;
1720 	VERIFY(inifp != NULL);
1721 
1722 	m_add_crumb(m, PKT_CRUMB_IP_INPUT);
1723 
1724 	ipstat.ips_rxc_notlist++;
1725 
1726 	/* Perform IP header alignment fixup, if needed */
1727 	IP_HDR_ALIGNMENT_FIXUP(m, inifp, goto bad);
1728 
1729 	m->m_pkthdr.pkt_flags &= ~PKTF_FORWARDED;
1730 
1731 #if DUMMYNET
1732 	bzero(&args, sizeof(struct ip_fw_args));
1733 
1734 	/*
1735 	 * Don't bother searching for tag(s) if there's none.
1736 	 */
1737 	if (SLIST_EMPTY(&m->m_pkthdr.tags)) {
1738 		goto ipfw_tags_done;
1739 	}
1740 
1741 	/* Grab info from mtags prepended to the chain */
1742 	if ((tag = m_tag_locate(m, KERNEL_MODULE_TAG_ID,
1743 	    KERNEL_TAG_TYPE_DUMMYNET, NULL)) != NULL) {
1744 		struct dn_pkt_tag *dn_tag;
1745 
1746 		dn_tag = (struct dn_pkt_tag *)(tag + 1);
1747 		args.fwa_pf_rule = dn_tag->dn_pf_rule;
1748 
1749 		m_tag_delete(m, tag);
1750 	}
1751 
1752 #if DIAGNOSTIC
1753 	if (m == NULL || !(m->m_flags & M_PKTHDR)) {
1754 		panic("ip_input no HDR");
1755 	}
1756 #endif
1757 
1758 	if (args.fwa_pf_rule) {
1759 		/* dummynet already filtered us */
1760 		ip = mtod(m, struct ip *);
1761 		hlen = IP_VHL_HL(ip->ip_vhl) << 2;
1762 		inject_filter_ref = ipf_get_inject_filter(m);
1763 		if (args.fwa_pf_rule) {
1764 			goto check_with_pf;
1765 		}
1766 	}
1767 ipfw_tags_done:
1768 #endif /* DUMMYNET */
1769 
1770 	/*
1771 	 * No need to process packet twice if we've already seen it.
1772 	 */
1773 	if (!SLIST_EMPTY(&m->m_pkthdr.tags)) {
1774 		inject_filter_ref = ipf_get_inject_filter(m);
1775 	}
1776 	if (inject_filter_ref != NULL) {
1777 		ip = mtod(m, struct ip *);
1778 		hlen = IP_VHL_HL(ip->ip_vhl) << 2;
1779 
1780 		DTRACE_IP6(receive, struct mbuf *, m, struct inpcb *, NULL,
1781 		    struct ip *, ip, struct ifnet *, inifp,
1782 		    struct ip *, ip, struct ip6_hdr *, NULL);
1783 
1784 		ip->ip_len = ntohs(ip->ip_len) - (u_short)hlen;
1785 		ip->ip_off = ntohs(ip->ip_off);
1786 		ip_proto_dispatch_in(m, hlen, ip->ip_p, inject_filter_ref);
1787 		return;
1788 	}
1789 
1790 	if (__improbable(m->m_pkthdr.pkt_flags & PKTF_WAKE_PKT)) {
1791 		if_ports_used_match_mbuf(inifp, PF_INET, m);
1792 	}
1793 
1794 	OSAddAtomic(1, &ipstat.ips_total);
1795 	if (m->m_pkthdr.len < sizeof(struct ip)) {
1796 		goto tooshort;
1797 	}
1798 
1799 	if (m->m_len < sizeof(struct ip) &&
1800 	    (m = m_pullup(m, sizeof(struct ip))) == NULL) {
1801 		OSAddAtomic(1, &ipstat.ips_toosmall);
1802 		return;
1803 	}
1804 	ip = mtod(m, struct ip *);
1805 
1806 	KERNEL_DEBUG(DBG_LAYER_BEG, ip->ip_dst.s_addr, ip->ip_src.s_addr,
1807 	    ip->ip_p, ip->ip_off, ip->ip_len);
1808 
1809 	if (IP_VHL_V(ip->ip_vhl) != IPVERSION) {
1810 		OSAddAtomic(1, &ipstat.ips_badvers);
1811 		goto bad;
1812 	}
1813 
1814 	hlen = IP_VHL_HL(ip->ip_vhl) << 2;
1815 	if (hlen < sizeof(struct ip)) {         /* minimum header length */
1816 		OSAddAtomic(1, &ipstat.ips_badhlen);
1817 		goto bad;
1818 	}
1819 	if (hlen > m->m_len) {
1820 		if ((m = m_pullup(m, hlen)) == NULL) {
1821 			OSAddAtomic(1, &ipstat.ips_badhlen);
1822 			return;
1823 		}
1824 		ip = mtod(m, struct ip *);
1825 	}
1826 
1827 	/* 127/8 must not appear on wire - RFC1122 */
1828 	if ((ntohl(ip->ip_dst.s_addr) >> IN_CLASSA_NSHIFT) == IN_LOOPBACKNET ||
1829 	    (ntohl(ip->ip_src.s_addr) >> IN_CLASSA_NSHIFT) == IN_LOOPBACKNET) {
1830 		/*
1831 		 * Allow for the following exceptions:
1832 		 *
1833 		 *   1. If the packet was sent to loopback (i.e. rcvif
1834 		 *	would have been set earlier at output time.)
1835 		 *
1836 		 *   2. If the packet was sent out on loopback from a local
1837 		 *	source address which belongs to a non-loopback
1838 		 *	interface (i.e. rcvif may not necessarily be a
1839 		 *	loopback interface, hence the test for PKTF_LOOP.)
1840 		 *	Unlike IPv6, there is no interface scope ID, and
1841 		 *	therefore we don't care so much about PKTF_IFINFO.
1842 		 */
1843 		if (!(inifp->if_flags & IFF_LOOPBACK) &&
1844 		    !(m->m_pkthdr.pkt_flags & PKTF_LOOP)) {
1845 			OSAddAtomic(1, &ipstat.ips_badaddr);
1846 			goto bad;
1847 		}
1848 	}
1849 
1850 	/* IPv4 Link-Local Addresses as defined in RFC3927 */
1851 	if ((IN_LINKLOCAL(ntohl(ip->ip_dst.s_addr)) ||
1852 	    IN_LINKLOCAL(ntohl(ip->ip_src.s_addr)))) {
1853 		ip_linklocal_stat.iplls_in_total++;
1854 		if (ip->ip_ttl != MAXTTL) {
1855 			OSAddAtomic(1, &ip_linklocal_stat.iplls_in_badttl);
1856 			/* Silently drop link local traffic with bad TTL */
1857 			if (!ip_linklocal_in_allowbadttl) {
1858 				goto bad;
1859 			}
1860 		}
1861 	}
1862 
1863 	sum = ip_cksum(m, hlen);
1864 	if (sum) {
1865 		goto bad;
1866 	}
1867 
1868 	DTRACE_IP6(receive, struct mbuf *, m, struct inpcb *, NULL,
1869 	    struct ip *, ip, struct ifnet *, inifp,
1870 	    struct ip *, ip, struct ip6_hdr *, NULL);
1871 
1872 	/*
1873 	 * Naively assume we can attribute inbound data to the route we would
1874 	 * use to send to this destination. Asymmetric routing breaks this
1875 	 * assumption, but it still allows us to account for traffic from
1876 	 * a remote node in the routing table.
1877 	 * this has a very significant performance impact so we bypass
1878 	 * if nstat_collect is disabled. We may also bypass if the
1879 	 * protocol is tcp in the future because tcp will have a route that
1880 	 * we can use to attribute the data to. That does mean we would not
1881 	 * account for forwarded tcp traffic.
1882 	 */
1883 	if (nstat_collect) {
1884 		struct rtentry *rt =
1885 		    ifnet_cached_rtlookup_inet(inifp, ip->ip_src);
1886 		if (rt != NULL) {
1887 			nstat_route_rx(rt, 1, m->m_pkthdr.len, 0);
1888 			rtfree(rt);
1889 		}
1890 	}
1891 
1892 	/*
1893 	 * Convert fields to host representation.
1894 	 */
1895 #if BYTE_ORDER != BIG_ENDIAN
1896 	NTOHS(ip->ip_len);
1897 #endif
1898 
1899 	if (ip->ip_len < hlen) {
1900 		OSAddAtomic(1, &ipstat.ips_badlen);
1901 		goto bad;
1902 	}
1903 
1904 #if BYTE_ORDER != BIG_ENDIAN
1905 	NTOHS(ip->ip_off);
1906 #endif
1907 	/*
1908 	 * Check that the amount of data in the buffers
1909 	 * is as at least much as the IP header would have us expect.
1910 	 * Trim mbufs if longer than we expect.
1911 	 * Drop packet if shorter than we expect.
1912 	 */
1913 	if (m->m_pkthdr.len < ip->ip_len) {
1914 tooshort:
1915 		OSAddAtomic(1, &ipstat.ips_tooshort);
1916 		goto bad;
1917 	}
1918 	if (m->m_pkthdr.len > ip->ip_len) {
1919 		ip_input_adjust(m, ip, inifp);
1920 	}
1921 
1922 #if DUMMYNET
1923 check_with_pf:
1924 #endif
1925 #if PF
1926 	/* Invoke inbound packet filter */
1927 	if (PF_IS_ENABLED) {
1928 		int error;
1929 #if DUMMYNET
1930 		error = pf_af_hook(inifp, NULL, &m, AF_INET, TRUE, &args);
1931 #else
1932 		error = pf_af_hook(inifp, NULL, &m, AF_INET, TRUE, NULL);
1933 #endif /* DUMMYNET */
1934 		if (error != 0 || m == NULL) {
1935 			if (m != NULL) {
1936 				panic("%s: unexpected packet %p",
1937 				    __func__, m);
1938 				/* NOTREACHED */
1939 			}
1940 			/* Already freed by callee */
1941 			return;
1942 		}
1943 		ip = mtod(m, struct ip *);
1944 		hlen = IP_VHL_HL(ip->ip_vhl) << 2;
1945 	}
1946 #endif /* PF */
1947 
1948 #if IPSEC
1949 	if (ipsec_bypass == 0 && ipsec_gethist(m, NULL)) {
1950 		goto pass;
1951 	}
1952 #endif
1953 
1954 pass:
1955 	/*
1956 	 * Process options and, if not destined for us,
1957 	 * ship it on.  ip_dooptions returns 1 when an
1958 	 * error was detected (causing an icmp message
1959 	 * to be sent and the original packet to be freed).
1960 	 */
1961 	ip_nhops = 0;           /* for source routed packets */
1962 	if (hlen > sizeof(struct ip) && ip_dooptions(m, 0, NULL)) {
1963 		return;
1964 	}
1965 
1966 	/*
1967 	 * Check our list of addresses, to see if the packet is for us.
1968 	 * If we don't have any addresses, assume any unicast packet
1969 	 * we receive might be for us (and let the upper layers deal
1970 	 * with it).
1971 	 */
1972 	if (TAILQ_EMPTY(&in_ifaddrhead) && !(m->m_flags & (M_MCAST | M_BCAST))) {
1973 		ip_setdstifaddr_info(m, inifp->if_index, NULL);
1974 		goto ours;
1975 	}
1976 
1977 	/*
1978 	 * Enable a consistency check between the destination address
1979 	 * and the arrival interface for a unicast packet (the RFC 1122
1980 	 * strong ES model) if IP forwarding is disabled and the packet
1981 	 * is not locally generated and the packet is not subject to
1982 	 * 'ipfw fwd'.
1983 	 *
1984 	 * XXX - Checking also should be disabled if the destination
1985 	 * address is ipnat'ed to a different interface.
1986 	 *
1987 	 * XXX - Checking is incompatible with IP aliases added
1988 	 * to the loopback interface instead of the interface where
1989 	 * the packets are received.
1990 	 */
1991 	if (!IN_MULTICAST(ntohl(ip->ip_dst.s_addr))) {
1992 		ip_check_if_result_t check_if_result = IP_CHECK_IF_NONE;
1993 
1994 		check_if_result = ip_input_check_interface(&m, ip, inifp);
1995 		ASSERT(check_if_result != IP_CHECK_IF_NONE);
1996 		if (check_if_result == IP_CHECK_IF_OURS) {
1997 			goto ours;
1998 		} else if (check_if_result == IP_CHECK_IF_DROP) {
1999 			return;
2000 		}
2001 	} else {
2002 		struct in_multi *inm;
2003 		/*
2004 		 * See if we belong to the destination multicast group on the
2005 		 * arrival interface.
2006 		 */
2007 		in_multihead_lock_shared();
2008 		IN_LOOKUP_MULTI(&ip->ip_dst, inifp, inm);
2009 		in_multihead_lock_done();
2010 		if (inm == NULL) {
2011 			OSAddAtomic(1, &ipstat.ips_notmember);
2012 			m_freem(m);
2013 			return;
2014 		}
2015 		ip_setdstifaddr_info(m, inifp->if_index, NULL);
2016 		INM_REMREF(inm);
2017 		goto ours;
2018 	}
2019 
2020 	/*
2021 	 * Not for us; forward if possible and desirable.
2022 	 */
2023 	if (ipforwarding == 0) {
2024 		OSAddAtomic(1, &ipstat.ips_cantforward);
2025 		m_freem(m);
2026 	} else {
2027 		ip_forward(m, 0, NULL);
2028 	}
2029 	return;
2030 
2031 ours:
2032 	/*
2033 	 * If offset or IP_MF are set, must reassemble.
2034 	 */
2035 	if (ip->ip_off & ~(IP_DF | IP_RF)) {
2036 		m = ip_reass(m);
2037 		if (m == NULL) {
2038 			return;
2039 		}
2040 		ip = mtod(m, struct ip *);
2041 		/* Get the header length of the reassembled packet */
2042 		hlen = IP_VHL_HL(ip->ip_vhl) << 2;
2043 	}
2044 
2045 	/*
2046 	 * Further protocols expect the packet length to be w/o the
2047 	 * IP header.
2048 	 */
2049 	ip->ip_len -= hlen;
2050 
2051 
2052 #if IPSEC
2053 	/*
2054 	 * enforce IPsec policy checking if we are seeing last header.
2055 	 * note that we do not visit this with protocols with pcb layer
2056 	 * code - like udp/tcp/raw ip.
2057 	 */
2058 	if (ipsec_bypass == 0 && (ip_protox[ip->ip_p]->pr_flags & PR_LASTHDR)) {
2059 		if (ipsec4_in_reject(m, NULL)) {
2060 			IPSEC_STAT_INCREMENT(ipsecstat.in_polvio);
2061 			goto bad;
2062 		}
2063 	}
2064 #endif /* IPSEC */
2065 
2066 	/*
2067 	 * Switch out to protocol's input routine.
2068 	 */
2069 	OSAddAtomic(1, &ipstat.ips_delivered);
2070 
2071 	ip_proto_dispatch_in(m, hlen, ip->ip_p, 0);
2072 	return;
2073 
2074 bad:
2075 	KERNEL_DEBUG(DBG_LAYER_END, 0, 0, 0, 0, 0);
2076 	m_freem(m);
2077 }
2078 
2079 static void
ipq_updateparams(void)2080 ipq_updateparams(void)
2081 {
2082 	LCK_MTX_ASSERT(&ipqlock, LCK_MTX_ASSERT_OWNED);
2083 	/*
2084 	 * -1 for unlimited allocation.
2085 	 */
2086 	if (maxnipq < 0) {
2087 		ipq_limit = 0;
2088 	}
2089 	/*
2090 	 * Positive number for specific bound.
2091 	 */
2092 	if (maxnipq > 0) {
2093 		ipq_limit = maxnipq;
2094 	}
2095 	/*
2096 	 * Zero specifies no further fragment queue allocation -- set the
2097 	 * bound very low, but rely on implementation elsewhere to actually
2098 	 * prevent allocation and reclaim current queues.
2099 	 */
2100 	if (maxnipq == 0) {
2101 		ipq_limit = 1;
2102 	}
2103 	/*
2104 	 * Arm the purge timer if not already and if there's work to do
2105 	 */
2106 	frag_sched_timeout();
2107 }
2108 
2109 static int
2110 sysctl_maxnipq SYSCTL_HANDLER_ARGS
2111 {
2112 #pragma unused(arg1, arg2)
2113 	int error, i;
2114 
2115 	lck_mtx_lock(&ipqlock);
2116 	i = maxnipq;
2117 	error = sysctl_handle_int(oidp, &i, 0, req);
2118 	if (error || req->newptr == USER_ADDR_NULL) {
2119 		goto done;
2120 	}
2121 	/* impose bounds */
2122 	if (i < -1 || i > (nmbclusters / 4)) {
2123 		error = EINVAL;
2124 		goto done;
2125 	}
2126 	maxnipq = i;
2127 	ipq_updateparams();
2128 done:
2129 	lck_mtx_unlock(&ipqlock);
2130 	return error;
2131 }
2132 
2133 static int
2134 sysctl_maxfragsperpacket SYSCTL_HANDLER_ARGS
2135 {
2136 #pragma unused(arg1, arg2)
2137 	int error, i;
2138 
2139 	lck_mtx_lock(&ipqlock);
2140 	i = maxfragsperpacket;
2141 	error = sysctl_handle_int(oidp, &i, 0, req);
2142 	if (error || req->newptr == USER_ADDR_NULL) {
2143 		goto done;
2144 	}
2145 	maxfragsperpacket = i;
2146 	ipq_updateparams();     /* see if we need to arm timer */
2147 done:
2148 	lck_mtx_unlock(&ipqlock);
2149 	return error;
2150 }
2151 
2152 /*
2153  * Take incoming datagram fragment and try to reassemble it into
2154  * whole datagram.  If a chain for reassembly of this datagram already
2155  * exists, then it is given as fp; otherwise have to make a chain.
2156  *
2157  * The IP header is *NOT* adjusted out of iplen (but in host byte order).
2158  */
2159 static struct mbuf *
ip_reass(struct mbuf * m)2160 ip_reass(struct mbuf *m)
2161 {
2162 	struct ip *ip;
2163 	struct mbuf *p, *q, *nq, *t;
2164 	struct ipq *fp = NULL;
2165 	struct ipqhead *head;
2166 	int i, hlen, next;
2167 	u_int8_t ecn, ecn0;
2168 	uint32_t csum, csum_flags;
2169 	uint16_t hash;
2170 	struct fq_head dfq;
2171 
2172 	MBUFQ_INIT(&dfq);       /* for deferred frees */
2173 
2174 	/* If maxnipq or maxfragsperpacket is 0, never accept fragments. */
2175 	if (maxnipq == 0 || maxfragsperpacket == 0) {
2176 		ipstat.ips_fragments++;
2177 		ipstat.ips_fragdropped++;
2178 		m_freem(m);
2179 		if (nipq > 0) {
2180 			lck_mtx_lock(&ipqlock);
2181 			frag_sched_timeout();   /* purge stale fragments */
2182 			lck_mtx_unlock(&ipqlock);
2183 		}
2184 		return NULL;
2185 	}
2186 
2187 	ip = mtod(m, struct ip *);
2188 	hlen = IP_VHL_HL(ip->ip_vhl) << 2;
2189 
2190 	lck_mtx_lock(&ipqlock);
2191 
2192 	hash = IPREASS_HASH(ip->ip_src.s_addr, ip->ip_id);
2193 	head = &ipq[hash];
2194 
2195 	/*
2196 	 * Look for queue of fragments
2197 	 * of this datagram.
2198 	 */
2199 	TAILQ_FOREACH(fp, head, ipq_list) {
2200 		if (ip->ip_id == fp->ipq_id &&
2201 		    ip->ip_src.s_addr == fp->ipq_src.s_addr &&
2202 		    ip->ip_dst.s_addr == fp->ipq_dst.s_addr &&
2203 		    ip->ip_p == fp->ipq_p) {
2204 			goto found;
2205 		}
2206 	}
2207 
2208 	fp = NULL;
2209 
2210 	/*
2211 	 * Attempt to trim the number of allocated fragment queues if it
2212 	 * exceeds the administrative limit.
2213 	 */
2214 	if ((nipq > (unsigned)maxnipq) && (maxnipq > 0)) {
2215 		/*
2216 		 * drop something from the tail of the current queue
2217 		 * before proceeding further
2218 		 */
2219 		struct ipq *fq = TAILQ_LAST(head, ipqhead);
2220 		if (fq == NULL) {   /* gak */
2221 			for (i = 0; i < IPREASS_NHASH; i++) {
2222 				struct ipq *r = TAILQ_LAST(&ipq[i], ipqhead);
2223 				if (r) {
2224 					ipstat.ips_fragtimeout += r->ipq_nfrags;
2225 					frag_freef(&ipq[i], r);
2226 					break;
2227 				}
2228 			}
2229 		} else {
2230 			ipstat.ips_fragtimeout += fq->ipq_nfrags;
2231 			frag_freef(head, fq);
2232 		}
2233 	}
2234 
2235 found:
2236 	/*
2237 	 * Leverage partial checksum offload for IP fragments.  Narrow down
2238 	 * the scope to cover only UDP without IP options, as that is the
2239 	 * most common case.
2240 	 *
2241 	 * Perform 1's complement adjustment of octets that got included/
2242 	 * excluded in the hardware-calculated checksum value.  Ignore cases
2243 	 * where the value includes the entire IPv4 header span, as the sum
2244 	 * for those octets would already be 0 by the time we get here; IP
2245 	 * has already performed its header checksum validation.  Also take
2246 	 * care of any trailing bytes and subtract out their partial sum.
2247 	 */
2248 	if (ip->ip_p == IPPROTO_UDP && hlen == sizeof(struct ip) &&
2249 	    (m->m_pkthdr.csum_flags &
2250 	    (CSUM_DATA_VALID | CSUM_PARTIAL | CSUM_PSEUDO_HDR)) ==
2251 	    (CSUM_DATA_VALID | CSUM_PARTIAL)) {
2252 		uint32_t start = m->m_pkthdr.csum_rx_start;
2253 		int32_t trailer = (m_pktlen(m) - ip->ip_len);
2254 		uint32_t swbytes = (uint32_t)trailer;
2255 
2256 		csum = m->m_pkthdr.csum_rx_val;
2257 
2258 		ASSERT(trailer >= 0);
2259 		if ((start != 0 && start != hlen) || trailer != 0) {
2260 			uint32_t datalen = ip->ip_len - hlen;
2261 
2262 #if BYTE_ORDER != BIG_ENDIAN
2263 			if (start < hlen) {
2264 				HTONS(ip->ip_len);
2265 				HTONS(ip->ip_off);
2266 			}
2267 #endif /* BYTE_ORDER != BIG_ENDIAN */
2268 			/* callee folds in sum */
2269 			csum = m_adj_sum16(m, start, hlen, datalen, csum);
2270 			if (hlen > start) {
2271 				swbytes += (hlen - start);
2272 			} else {
2273 				swbytes += (start - hlen);
2274 			}
2275 #if BYTE_ORDER != BIG_ENDIAN
2276 			if (start < hlen) {
2277 				NTOHS(ip->ip_off);
2278 				NTOHS(ip->ip_len);
2279 			}
2280 #endif /* BYTE_ORDER != BIG_ENDIAN */
2281 		}
2282 		csum_flags = m->m_pkthdr.csum_flags;
2283 
2284 		if (swbytes != 0) {
2285 			udp_in_cksum_stats(swbytes);
2286 		}
2287 		if (trailer != 0) {
2288 			m_adj(m, -trailer);
2289 		}
2290 	} else {
2291 		csum = 0;
2292 		csum_flags = 0;
2293 	}
2294 
2295 	/* Invalidate checksum */
2296 	m->m_pkthdr.csum_flags &= ~CSUM_DATA_VALID;
2297 
2298 	ipstat.ips_fragments++;
2299 
2300 	/*
2301 	 * Adjust ip_len to not reflect header,
2302 	 * convert offset of this to bytes.
2303 	 */
2304 	ip->ip_len -= hlen;
2305 	if (ip->ip_off & IP_MF) {
2306 		/*
2307 		 * Make sure that fragments have a data length
2308 		 * that's a non-zero multiple of 8 bytes.
2309 		 */
2310 		if (ip->ip_len == 0 || (ip->ip_len & 0x7) != 0) {
2311 			OSAddAtomic(1, &ipstat.ips_toosmall);
2312 			/*
2313 			 * Reassembly queue may have been found if previous
2314 			 * fragments were valid; given that this one is bad,
2315 			 * we need to drop it.  Make sure to set fp to NULL
2316 			 * if not already, since we don't want to decrement
2317 			 * ipq_nfrags as it doesn't include this packet.
2318 			 */
2319 			fp = NULL;
2320 			goto dropfrag;
2321 		}
2322 		m->m_flags |= M_FRAG;
2323 	} else {
2324 		/* Clear the flag in case packet comes from loopback */
2325 		m->m_flags &= ~M_FRAG;
2326 	}
2327 	ip->ip_off <<= 3;
2328 
2329 	m->m_pkthdr.pkt_hdr = ip;
2330 
2331 	/* Previous ip_reass() started here. */
2332 	/*
2333 	 * Presence of header sizes in mbufs
2334 	 * would confuse code below.
2335 	 */
2336 	m->m_data += hlen;
2337 	m->m_len -= hlen;
2338 
2339 	/*
2340 	 * If first fragment to arrive, create a reassembly queue.
2341 	 */
2342 	if (fp == NULL) {
2343 		fp = ipq_alloc(M_DONTWAIT);
2344 		if (fp == NULL) {
2345 			goto dropfrag;
2346 		}
2347 		TAILQ_INSERT_HEAD(head, fp, ipq_list);
2348 		nipq++;
2349 		fp->ipq_nfrags = 1;
2350 		fp->ipq_ttl = IPFRAGTTL;
2351 		fp->ipq_p = ip->ip_p;
2352 		fp->ipq_id = ip->ip_id;
2353 		fp->ipq_src = ip->ip_src;
2354 		fp->ipq_dst = ip->ip_dst;
2355 		fp->ipq_frags = m;
2356 		m->m_nextpkt = NULL;
2357 		/*
2358 		 * If the first fragment has valid checksum offload
2359 		 * info, the rest of fragments are eligible as well.
2360 		 */
2361 		if (csum_flags != 0) {
2362 			fp->ipq_csum = csum;
2363 			fp->ipq_csum_flags = csum_flags;
2364 		}
2365 		m = NULL;       /* nothing to return */
2366 		goto done;
2367 	} else {
2368 		fp->ipq_nfrags++;
2369 	}
2370 
2371 #define GETIP(m)        ((struct ip *)((m)->m_pkthdr.pkt_hdr))
2372 
2373 	/*
2374 	 * Handle ECN by comparing this segment with the first one;
2375 	 * if CE is set, do not lose CE.
2376 	 * drop if CE and not-ECT are mixed for the same packet.
2377 	 */
2378 	ecn = ip->ip_tos & IPTOS_ECN_MASK;
2379 	ecn0 = GETIP(fp->ipq_frags)->ip_tos & IPTOS_ECN_MASK;
2380 	if (ecn == IPTOS_ECN_CE) {
2381 		if (ecn0 == IPTOS_ECN_NOTECT) {
2382 			goto dropfrag;
2383 		}
2384 		if (ecn0 != IPTOS_ECN_CE) {
2385 			GETIP(fp->ipq_frags)->ip_tos |= IPTOS_ECN_CE;
2386 		}
2387 	}
2388 	if (ecn == IPTOS_ECN_NOTECT && ecn0 != IPTOS_ECN_NOTECT) {
2389 		goto dropfrag;
2390 	}
2391 
2392 	/*
2393 	 * Find a segment which begins after this one does.
2394 	 */
2395 	for (p = NULL, q = fp->ipq_frags; q; p = q, q = q->m_nextpkt) {
2396 		if (GETIP(q)->ip_off > ip->ip_off) {
2397 			break;
2398 		}
2399 	}
2400 
2401 	/*
2402 	 * If there is a preceding segment, it may provide some of
2403 	 * our data already.  If so, drop the data from the incoming
2404 	 * segment.  If it provides all of our data, drop us, otherwise
2405 	 * stick new segment in the proper place.
2406 	 *
2407 	 * If some of the data is dropped from the preceding
2408 	 * segment, then it's checksum is invalidated.
2409 	 */
2410 	if (p) {
2411 		i = GETIP(p)->ip_off + GETIP(p)->ip_len - ip->ip_off;
2412 		if (i > 0) {
2413 			if (i >= ip->ip_len) {
2414 				goto dropfrag;
2415 			}
2416 			m_adj(m, i);
2417 			fp->ipq_csum_flags = 0;
2418 			ip->ip_off += i;
2419 			ip->ip_len -= i;
2420 		}
2421 		m->m_nextpkt = p->m_nextpkt;
2422 		p->m_nextpkt = m;
2423 	} else {
2424 		m->m_nextpkt = fp->ipq_frags;
2425 		fp->ipq_frags = m;
2426 	}
2427 
2428 	/*
2429 	 * While we overlap succeeding segments trim them or,
2430 	 * if they are completely covered, dequeue them.
2431 	 */
2432 	for (; q != NULL && ip->ip_off + ip->ip_len > GETIP(q)->ip_off;
2433 	    q = nq) {
2434 		i = (ip->ip_off + ip->ip_len) - GETIP(q)->ip_off;
2435 		if (i < GETIP(q)->ip_len) {
2436 			GETIP(q)->ip_len -= i;
2437 			GETIP(q)->ip_off += i;
2438 			m_adj(q, i);
2439 			fp->ipq_csum_flags = 0;
2440 			break;
2441 		}
2442 		nq = q->m_nextpkt;
2443 		m->m_nextpkt = nq;
2444 		ipstat.ips_fragdropped++;
2445 		fp->ipq_nfrags--;
2446 		/* defer freeing until after lock is dropped */
2447 		MBUFQ_ENQUEUE(&dfq, q);
2448 	}
2449 
2450 	/*
2451 	 * If this fragment contains similar checksum offload info
2452 	 * as that of the existing ones, accumulate checksum.  Otherwise,
2453 	 * invalidate checksum offload info for the entire datagram.
2454 	 */
2455 	if (csum_flags != 0 && csum_flags == fp->ipq_csum_flags) {
2456 		fp->ipq_csum += csum;
2457 	} else if (fp->ipq_csum_flags != 0) {
2458 		fp->ipq_csum_flags = 0;
2459 	}
2460 
2461 
2462 	/*
2463 	 * Check for complete reassembly and perform frag per packet
2464 	 * limiting.
2465 	 *
2466 	 * Frag limiting is performed here so that the nth frag has
2467 	 * a chance to complete the packet before we drop the packet.
2468 	 * As a result, n+1 frags are actually allowed per packet, but
2469 	 * only n will ever be stored. (n = maxfragsperpacket.)
2470 	 *
2471 	 */
2472 	next = 0;
2473 	for (p = NULL, q = fp->ipq_frags; q; p = q, q = q->m_nextpkt) {
2474 		if (GETIP(q)->ip_off != next) {
2475 			if (fp->ipq_nfrags > maxfragsperpacket) {
2476 				ipstat.ips_fragdropped += fp->ipq_nfrags;
2477 				frag_freef(head, fp);
2478 			}
2479 			m = NULL;       /* nothing to return */
2480 			goto done;
2481 		}
2482 		next += GETIP(q)->ip_len;
2483 	}
2484 	/* Make sure the last packet didn't have the IP_MF flag */
2485 	if (p->m_flags & M_FRAG) {
2486 		if (fp->ipq_nfrags > maxfragsperpacket) {
2487 			ipstat.ips_fragdropped += fp->ipq_nfrags;
2488 			frag_freef(head, fp);
2489 		}
2490 		m = NULL;               /* nothing to return */
2491 		goto done;
2492 	}
2493 
2494 	/*
2495 	 * Reassembly is complete.  Make sure the packet is a sane size.
2496 	 */
2497 	q = fp->ipq_frags;
2498 	ip = GETIP(q);
2499 	if (next + (IP_VHL_HL(ip->ip_vhl) << 2) > IP_MAXPACKET) {
2500 		ipstat.ips_toolong++;
2501 		ipstat.ips_fragdropped += fp->ipq_nfrags;
2502 		frag_freef(head, fp);
2503 		m = NULL;               /* nothing to return */
2504 		goto done;
2505 	}
2506 
2507 	/*
2508 	 * Concatenate fragments.
2509 	 */
2510 	m = q;
2511 	t = m->m_next;
2512 	m->m_next = NULL;
2513 	m_cat(m, t);
2514 	nq = q->m_nextpkt;
2515 	q->m_nextpkt = NULL;
2516 	for (q = nq; q != NULL; q = nq) {
2517 		nq = q->m_nextpkt;
2518 		q->m_nextpkt = NULL;
2519 		m_cat(m, q);
2520 	}
2521 
2522 	/*
2523 	 * Store partial hardware checksum info from the fragment queue;
2524 	 * the receive start offset is set to 20 bytes (see code at the
2525 	 * top of this routine.)
2526 	 */
2527 	if (fp->ipq_csum_flags != 0) {
2528 		csum = fp->ipq_csum;
2529 
2530 		ADDCARRY(csum);
2531 
2532 		m->m_pkthdr.csum_rx_val = (uint16_t)csum;
2533 		m->m_pkthdr.csum_rx_start = sizeof(struct ip);
2534 		m->m_pkthdr.csum_flags = fp->ipq_csum_flags;
2535 	} else if ((m->m_pkthdr.rcvif->if_flags & IFF_LOOPBACK) ||
2536 	    (m->m_pkthdr.pkt_flags & PKTF_LOOP)) {
2537 		/* loopback checksums are always OK */
2538 		m->m_pkthdr.csum_data = 0xffff;
2539 		m->m_pkthdr.csum_flags =
2540 		    CSUM_DATA_VALID | CSUM_PSEUDO_HDR |
2541 		    CSUM_IP_CHECKED | CSUM_IP_VALID;
2542 	}
2543 
2544 	/*
2545 	 * Create header for new ip packet by modifying header of first
2546 	 * packet; dequeue and discard fragment reassembly header.
2547 	 * Make header visible.
2548 	 */
2549 	ip->ip_len = (u_short)((IP_VHL_HL(ip->ip_vhl) << 2) + next);
2550 	ip->ip_src = fp->ipq_src;
2551 	ip->ip_dst = fp->ipq_dst;
2552 
2553 	fp->ipq_frags = NULL;   /* return to caller as 'm' */
2554 	frag_freef(head, fp);
2555 	fp = NULL;
2556 
2557 	m->m_len += (IP_VHL_HL(ip->ip_vhl) << 2);
2558 	m->m_data -= (IP_VHL_HL(ip->ip_vhl) << 2);
2559 	/* some debugging cruft by sklower, below, will go away soon */
2560 	if (m->m_flags & M_PKTHDR) {    /* XXX this should be done elsewhere */
2561 		m_fixhdr(m);
2562 	}
2563 	ipstat.ips_reassembled++;
2564 
2565 	/* arm the purge timer if not already and if there's work to do */
2566 	frag_sched_timeout();
2567 	lck_mtx_unlock(&ipqlock);
2568 	/* perform deferred free (if needed) now that lock is dropped */
2569 	if (!MBUFQ_EMPTY(&dfq)) {
2570 		MBUFQ_DRAIN(&dfq);
2571 	}
2572 	VERIFY(MBUFQ_EMPTY(&dfq));
2573 	return m;
2574 
2575 done:
2576 	VERIFY(m == NULL);
2577 	/* arm the purge timer if not already and if there's work to do */
2578 	frag_sched_timeout();
2579 	lck_mtx_unlock(&ipqlock);
2580 	/* perform deferred free (if needed) */
2581 	if (!MBUFQ_EMPTY(&dfq)) {
2582 		MBUFQ_DRAIN(&dfq);
2583 	}
2584 	VERIFY(MBUFQ_EMPTY(&dfq));
2585 	return NULL;
2586 
2587 dropfrag:
2588 	ipstat.ips_fragdropped++;
2589 	if (fp != NULL) {
2590 		fp->ipq_nfrags--;
2591 	}
2592 	/* arm the purge timer if not already and if there's work to do */
2593 	frag_sched_timeout();
2594 	lck_mtx_unlock(&ipqlock);
2595 	m_freem(m);
2596 	/* perform deferred free (if needed) */
2597 	if (!MBUFQ_EMPTY(&dfq)) {
2598 		MBUFQ_DRAIN(&dfq);
2599 	}
2600 	VERIFY(MBUFQ_EMPTY(&dfq));
2601 	return NULL;
2602 #undef GETIP
2603 }
2604 
2605 /*
2606  * Free a fragment reassembly header and all
2607  * associated datagrams.
2608  */
2609 static void
frag_freef(struct ipqhead * fhp,struct ipq * fp)2610 frag_freef(struct ipqhead *fhp, struct ipq *fp)
2611 {
2612 	LCK_MTX_ASSERT(&ipqlock, LCK_MTX_ASSERT_OWNED);
2613 
2614 	fp->ipq_nfrags = 0;
2615 	if (fp->ipq_frags != NULL) {
2616 		m_freem_list(fp->ipq_frags);
2617 		fp->ipq_frags = NULL;
2618 	}
2619 	TAILQ_REMOVE(fhp, fp, ipq_list);
2620 	nipq--;
2621 	ipq_free(fp);
2622 }
2623 
2624 /*
2625  * IP reassembly timer processing
2626  */
2627 static void
frag_timeout(void * arg)2628 frag_timeout(void *arg)
2629 {
2630 #pragma unused(arg)
2631 	struct ipq *fp;
2632 	int i;
2633 
2634 	/*
2635 	 * Update coarse-grained networking timestamp (in sec.); the idea
2636 	 * is to piggy-back on the timeout callout to update the counter
2637 	 * returnable via net_uptime().
2638 	 */
2639 	net_update_uptime();
2640 
2641 	lck_mtx_lock(&ipqlock);
2642 	for (i = 0; i < IPREASS_NHASH; i++) {
2643 		for (fp = TAILQ_FIRST(&ipq[i]); fp;) {
2644 			struct ipq *fpp;
2645 
2646 			fpp = fp;
2647 			fp = TAILQ_NEXT(fp, ipq_list);
2648 			if (--fpp->ipq_ttl == 0) {
2649 				ipstat.ips_fragtimeout += fpp->ipq_nfrags;
2650 				frag_freef(&ipq[i], fpp);
2651 			}
2652 		}
2653 	}
2654 	/*
2655 	 * If we are over the maximum number of fragments
2656 	 * (due to the limit being lowered), drain off
2657 	 * enough to get down to the new limit.
2658 	 */
2659 	if (maxnipq >= 0 && nipq > (unsigned)maxnipq) {
2660 		for (i = 0; i < IPREASS_NHASH; i++) {
2661 			while (nipq > (unsigned)maxnipq &&
2662 			    !TAILQ_EMPTY(&ipq[i])) {
2663 				ipstat.ips_fragdropped +=
2664 				    TAILQ_FIRST(&ipq[i])->ipq_nfrags;
2665 				frag_freef(&ipq[i], TAILQ_FIRST(&ipq[i]));
2666 			}
2667 		}
2668 	}
2669 	/* re-arm the purge timer if there's work to do */
2670 	frag_timeout_run = 0;
2671 	frag_sched_timeout();
2672 	lck_mtx_unlock(&ipqlock);
2673 }
2674 
2675 static void
frag_sched_timeout(void)2676 frag_sched_timeout(void)
2677 {
2678 	LCK_MTX_ASSERT(&ipqlock, LCK_MTX_ASSERT_OWNED);
2679 
2680 	if (!frag_timeout_run && nipq > 0) {
2681 		frag_timeout_run = 1;
2682 		timeout(frag_timeout, NULL, hz);
2683 	}
2684 }
2685 
2686 /*
2687  * Drain off all datagram fragments.
2688  */
2689 static void
frag_drain(void)2690 frag_drain(void)
2691 {
2692 	int i;
2693 
2694 	lck_mtx_lock(&ipqlock);
2695 	for (i = 0; i < IPREASS_NHASH; i++) {
2696 		while (!TAILQ_EMPTY(&ipq[i])) {
2697 			ipstat.ips_fragdropped +=
2698 			    TAILQ_FIRST(&ipq[i])->ipq_nfrags;
2699 			frag_freef(&ipq[i], TAILQ_FIRST(&ipq[i]));
2700 		}
2701 	}
2702 	lck_mtx_unlock(&ipqlock);
2703 }
2704 
2705 static struct ipq *
ipq_alloc(int how)2706 ipq_alloc(int how)
2707 {
2708 	struct mbuf *t;
2709 	struct ipq *fp;
2710 
2711 	/*
2712 	 * See comments in ipq_updateparams().  Keep the count separate
2713 	 * from nipq since the latter represents the elements already
2714 	 * in the reassembly queues.
2715 	 */
2716 	if (ipq_limit > 0 && ipq_count > ipq_limit) {
2717 		return NULL;
2718 	}
2719 
2720 	t = m_get(how, MT_FTABLE);
2721 	if (t != NULL) {
2722 		atomic_add_32(&ipq_count, 1);
2723 		fp = mtod(t, struct ipq *);
2724 		bzero(fp, sizeof(*fp));
2725 	} else {
2726 		fp = NULL;
2727 	}
2728 	return fp;
2729 }
2730 
2731 static void
ipq_free(struct ipq * fp)2732 ipq_free(struct ipq *fp)
2733 {
2734 	(void) m_free(dtom(fp));
2735 	atomic_add_32(&ipq_count, -1);
2736 }
2737 
2738 /*
2739  * Drain callback
2740  */
2741 void
ip_drain(void)2742 ip_drain(void)
2743 {
2744 	frag_drain();           /* fragments */
2745 	in_rtqdrain();          /* protocol cloned routes */
2746 	in_arpdrain(NULL);      /* cloned routes: ARP */
2747 }
2748 
2749 /*
2750  * Do option processing on a datagram,
2751  * possibly discarding it if bad options are encountered,
2752  * or forwarding it if source-routed.
2753  * The pass argument is used when operating in the IPSTEALTH
2754  * mode to tell what options to process:
2755  * [LS]SRR (pass 0) or the others (pass 1).
2756  * The reason for as many as two passes is that when doing IPSTEALTH,
2757  * non-routing options should be processed only if the packet is for us.
2758  * Returns 1 if packet has been forwarded/freed,
2759  * 0 if the packet should be processed further.
2760  */
2761 static int
ip_dooptions(struct mbuf * m,int pass,struct sockaddr_in * next_hop)2762 ip_dooptions(struct mbuf *m, int pass, struct sockaddr_in *next_hop)
2763 {
2764 #pragma unused(pass)
2765 	struct ip *ip = mtod(m, struct ip *);
2766 	u_char *cp;
2767 	struct ip_timestamp *ipt;
2768 	struct in_ifaddr *ia;
2769 	int opt, optlen, cnt, off, type = ICMP_PARAMPROB, forward = 0;
2770 	uint8_t code = 0;
2771 	struct in_addr *sin, dst;
2772 	u_int32_t ntime;
2773 	struct sockaddr_in ipaddr = {
2774 		.sin_len = sizeof(ipaddr),
2775 		.sin_family = AF_INET,
2776 		.sin_port = 0,
2777 		.sin_addr = { .s_addr = 0 },
2778 		.sin_zero = { 0, }
2779 	};
2780 
2781 	/* Expect 32-bit aligned data pointer on strict-align platforms */
2782 	MBUF_STRICT_DATA_ALIGNMENT_CHECK_32(m);
2783 
2784 	dst = ip->ip_dst;
2785 	cp = (u_char *)(ip + 1);
2786 	cnt = (IP_VHL_HL(ip->ip_vhl) << 2) - sizeof(struct ip);
2787 	for (; cnt > 0; cnt -= optlen, cp += optlen) {
2788 		opt = cp[IPOPT_OPTVAL];
2789 		if (opt == IPOPT_EOL) {
2790 			break;
2791 		}
2792 		if (opt == IPOPT_NOP) {
2793 			optlen = 1;
2794 		} else {
2795 			if (cnt < IPOPT_OLEN + sizeof(*cp)) {
2796 				code = (uint8_t)(&cp[IPOPT_OLEN] - (u_char *)ip);
2797 				goto bad;
2798 			}
2799 			optlen = cp[IPOPT_OLEN];
2800 			if (optlen < IPOPT_OLEN + sizeof(*cp) ||
2801 			    optlen > cnt) {
2802 				code = (uint8_t)(&cp[IPOPT_OLEN] - (u_char *)ip);
2803 				goto bad;
2804 			}
2805 		}
2806 		switch (opt) {
2807 		default:
2808 			break;
2809 
2810 		/*
2811 		 * Source routing with record.
2812 		 * Find interface with current destination address.
2813 		 * If none on this machine then drop if strictly routed,
2814 		 * or do nothing if loosely routed.
2815 		 * Record interface address and bring up next address
2816 		 * component.  If strictly routed make sure next
2817 		 * address is on directly accessible net.
2818 		 */
2819 		case IPOPT_LSRR:
2820 		case IPOPT_SSRR:
2821 			if (optlen < IPOPT_OFFSET + sizeof(*cp)) {
2822 				code = (uint8_t)(&cp[IPOPT_OLEN] - (u_char *)ip);
2823 				goto bad;
2824 			}
2825 			if ((off = cp[IPOPT_OFFSET]) < IPOPT_MINOFF) {
2826 				code = (uint8_t)(&cp[IPOPT_OFFSET] - (u_char *)ip);
2827 				goto bad;
2828 			}
2829 			ipaddr.sin_addr = ip->ip_dst;
2830 			ia = (struct in_ifaddr *)ifa_ifwithaddr(SA(&ipaddr));
2831 			if (ia == NULL) {
2832 				if (opt == IPOPT_SSRR) {
2833 					type = ICMP_UNREACH;
2834 					code = ICMP_UNREACH_SRCFAIL;
2835 					goto bad;
2836 				}
2837 				if (!ip_dosourceroute) {
2838 					goto nosourcerouting;
2839 				}
2840 				/*
2841 				 * Loose routing, and not at next destination
2842 				 * yet; nothing to do except forward.
2843 				 */
2844 				break;
2845 			} else {
2846 				IFA_REMREF(&ia->ia_ifa);
2847 				ia = NULL;
2848 			}
2849 			off--;                  /* 0 origin */
2850 			if (off > optlen - (int)sizeof(struct in_addr)) {
2851 				/*
2852 				 * End of source route.  Should be for us.
2853 				 */
2854 				if (!ip_acceptsourceroute) {
2855 					goto nosourcerouting;
2856 				}
2857 				save_rte(cp, ip->ip_src);
2858 				break;
2859 			}
2860 
2861 			if (!ip_dosourceroute) {
2862 				if (ipforwarding) {
2863 					char buf[MAX_IPv4_STR_LEN];
2864 					char buf2[MAX_IPv4_STR_LEN];
2865 					/*
2866 					 * Acting as a router, so generate ICMP
2867 					 */
2868 nosourcerouting:
2869 					log(LOG_WARNING,
2870 					    "attempted source route from %s "
2871 					    "to %s\n",
2872 					    inet_ntop(AF_INET, &ip->ip_src,
2873 					    buf, sizeof(buf)),
2874 					    inet_ntop(AF_INET, &ip->ip_dst,
2875 					    buf2, sizeof(buf2)));
2876 					type = ICMP_UNREACH;
2877 					code = ICMP_UNREACH_SRCFAIL;
2878 					goto bad;
2879 				} else {
2880 					/*
2881 					 * Not acting as a router,
2882 					 * so silently drop.
2883 					 */
2884 					OSAddAtomic(1, &ipstat.ips_cantforward);
2885 					m_freem(m);
2886 					return 1;
2887 				}
2888 			}
2889 
2890 			/*
2891 			 * locate outgoing interface
2892 			 */
2893 			(void) memcpy(&ipaddr.sin_addr, cp + off,
2894 			    sizeof(ipaddr.sin_addr));
2895 
2896 			if (opt == IPOPT_SSRR) {
2897 #define INA     struct in_ifaddr *
2898 				if ((ia = (INA)ifa_ifwithdstaddr(
2899 					    SA(&ipaddr))) == NULL) {
2900 					ia = (INA)ifa_ifwithnet(SA(&ipaddr));
2901 				}
2902 			} else {
2903 				ia = ip_rtaddr(ipaddr.sin_addr);
2904 			}
2905 			if (ia == NULL) {
2906 				type = ICMP_UNREACH;
2907 				code = ICMP_UNREACH_SRCFAIL;
2908 				goto bad;
2909 			}
2910 			ip->ip_dst = ipaddr.sin_addr;
2911 			IFA_LOCK(&ia->ia_ifa);
2912 			(void) memcpy(cp + off, &(IA_SIN(ia)->sin_addr),
2913 			    sizeof(struct in_addr));
2914 			IFA_UNLOCK(&ia->ia_ifa);
2915 			IFA_REMREF(&ia->ia_ifa);
2916 			ia = NULL;
2917 			cp[IPOPT_OFFSET] += sizeof(struct in_addr);
2918 			/*
2919 			 * Let ip_intr's mcast routing check handle mcast pkts
2920 			 */
2921 			forward = !IN_MULTICAST(ntohl(ip->ip_dst.s_addr));
2922 			break;
2923 
2924 		case IPOPT_RR:
2925 			if (optlen < IPOPT_OFFSET + sizeof(*cp)) {
2926 				code = (uint8_t)(&cp[IPOPT_OFFSET] - (u_char *)ip);
2927 				goto bad;
2928 			}
2929 			if ((off = cp[IPOPT_OFFSET]) < IPOPT_MINOFF) {
2930 				code = (uint8_t)(&cp[IPOPT_OFFSET] - (u_char *)ip);
2931 				goto bad;
2932 			}
2933 			/*
2934 			 * If no space remains, ignore.
2935 			 */
2936 			off--;                  /* 0 origin */
2937 			if (off > optlen - (int)sizeof(struct in_addr)) {
2938 				break;
2939 			}
2940 			(void) memcpy(&ipaddr.sin_addr, &ip->ip_dst,
2941 			    sizeof(ipaddr.sin_addr));
2942 			/*
2943 			 * locate outgoing interface; if we're the destination,
2944 			 * use the incoming interface (should be same).
2945 			 */
2946 			if ((ia = (INA)ifa_ifwithaddr(SA(&ipaddr))) == NULL) {
2947 				if ((ia = ip_rtaddr(ipaddr.sin_addr)) == NULL) {
2948 					type = ICMP_UNREACH;
2949 					code = ICMP_UNREACH_HOST;
2950 					goto bad;
2951 				}
2952 			}
2953 			IFA_LOCK(&ia->ia_ifa);
2954 			(void) memcpy(cp + off, &(IA_SIN(ia)->sin_addr),
2955 			    sizeof(struct in_addr));
2956 			IFA_UNLOCK(&ia->ia_ifa);
2957 			IFA_REMREF(&ia->ia_ifa);
2958 			ia = NULL;
2959 			cp[IPOPT_OFFSET] += sizeof(struct in_addr);
2960 			break;
2961 
2962 		case IPOPT_TS:
2963 			code = (uint8_t)(cp - (u_char *)ip);
2964 			ipt = (struct ip_timestamp *)(void *)cp;
2965 			if (ipt->ipt_len < 4 || ipt->ipt_len > 40) {
2966 				code = (uint8_t)((u_char *)&ipt->ipt_len -
2967 				    (u_char *)ip);
2968 				goto bad;
2969 			}
2970 			if (ipt->ipt_ptr < 5) {
2971 				code = (uint8_t)((u_char *)&ipt->ipt_ptr -
2972 				    (u_char *)ip);
2973 				goto bad;
2974 			}
2975 			if (ipt->ipt_ptr >
2976 			    ipt->ipt_len - (int)sizeof(int32_t)) {
2977 				if (++ipt->ipt_oflw == 0) {
2978 					code = (uint8_t)((u_char *)&ipt->ipt_ptr -
2979 					    (u_char *)ip);
2980 					goto bad;
2981 				}
2982 				break;
2983 			}
2984 			sin = (struct in_addr *)(void *)(cp + ipt->ipt_ptr - 1);
2985 			switch (ipt->ipt_flg) {
2986 			case IPOPT_TS_TSONLY:
2987 				break;
2988 
2989 			case IPOPT_TS_TSANDADDR:
2990 				if (ipt->ipt_ptr - 1 + sizeof(n_time) +
2991 				    sizeof(struct in_addr) > ipt->ipt_len) {
2992 					code = (uint8_t)((u_char *)&ipt->ipt_ptr -
2993 					    (u_char *)ip);
2994 					goto bad;
2995 				}
2996 				ipaddr.sin_addr = dst;
2997 				ia = (INA)ifaof_ifpforaddr(SA(&ipaddr),
2998 				    m->m_pkthdr.rcvif);
2999 				if (ia == NULL) {
3000 					continue;
3001 				}
3002 				IFA_LOCK(&ia->ia_ifa);
3003 				(void) memcpy(sin, &IA_SIN(ia)->sin_addr,
3004 				    sizeof(struct in_addr));
3005 				IFA_UNLOCK(&ia->ia_ifa);
3006 				ipt->ipt_ptr += sizeof(struct in_addr);
3007 				IFA_REMREF(&ia->ia_ifa);
3008 				ia = NULL;
3009 				break;
3010 
3011 			case IPOPT_TS_PRESPEC:
3012 				if (ipt->ipt_ptr - 1 + sizeof(n_time) +
3013 				    sizeof(struct in_addr) > ipt->ipt_len) {
3014 					code = (uint8_t)((u_char *)&ipt->ipt_ptr -
3015 					    (u_char *)ip);
3016 					goto bad;
3017 				}
3018 				(void) memcpy(&ipaddr.sin_addr, sin,
3019 				    sizeof(struct in_addr));
3020 				if ((ia = (struct in_ifaddr *)ifa_ifwithaddr(
3021 					    SA(&ipaddr))) == NULL) {
3022 					continue;
3023 				}
3024 				IFA_REMREF(&ia->ia_ifa);
3025 				ia = NULL;
3026 				ipt->ipt_ptr += sizeof(struct in_addr);
3027 				break;
3028 
3029 			default:
3030 				/* XXX can't take &ipt->ipt_flg */
3031 				code = (uint8_t)((u_char *)&ipt->ipt_ptr -
3032 				    (u_char *)ip + 1);
3033 				goto bad;
3034 			}
3035 			ntime = iptime();
3036 			(void) memcpy(cp + ipt->ipt_ptr - 1, &ntime,
3037 			    sizeof(n_time));
3038 			ipt->ipt_ptr += sizeof(n_time);
3039 		}
3040 	}
3041 	if (forward && ipforwarding) {
3042 		ip_forward(m, 1, next_hop);
3043 		return 1;
3044 	}
3045 	return 0;
3046 bad:
3047 	icmp_error(m, type, code, 0, 0);
3048 	OSAddAtomic(1, &ipstat.ips_badoptions);
3049 	return 1;
3050 }
3051 
3052 /*
3053  * Check for the presence of the IP Router Alert option [RFC2113]
3054  * in the header of an IPv4 datagram.
3055  *
3056  * This call is not intended for use from the forwarding path; it is here
3057  * so that protocol domains may check for the presence of the option.
3058  * Given how FreeBSD's IPv4 stack is currently structured, the Router Alert
3059  * option does not have much relevance to the implementation, though this
3060  * may change in future.
3061  * Router alert options SHOULD be passed if running in IPSTEALTH mode and
3062  * we are not the endpoint.
3063  * Length checks on individual options should already have been peformed
3064  * by ip_dooptions() therefore they are folded under DIAGNOSTIC here.
3065  *
3066  * Return zero if not present or options are invalid, non-zero if present.
3067  */
3068 int
ip_checkrouteralert(struct mbuf * m)3069 ip_checkrouteralert(struct mbuf *m)
3070 {
3071 	struct ip *ip = mtod(m, struct ip *);
3072 	u_char *cp;
3073 	int opt, optlen, cnt, found_ra;
3074 
3075 	found_ra = 0;
3076 	cp = (u_char *)(ip + 1);
3077 	cnt = (IP_VHL_HL(ip->ip_vhl) << 2) - sizeof(struct ip);
3078 	for (; cnt > 0; cnt -= optlen, cp += optlen) {
3079 		opt = cp[IPOPT_OPTVAL];
3080 		if (opt == IPOPT_EOL) {
3081 			break;
3082 		}
3083 		if (opt == IPOPT_NOP) {
3084 			optlen = 1;
3085 		} else {
3086 #ifdef DIAGNOSTIC
3087 			if (cnt < IPOPT_OLEN + sizeof(*cp)) {
3088 				break;
3089 			}
3090 #endif
3091 			optlen = cp[IPOPT_OLEN];
3092 #ifdef DIAGNOSTIC
3093 			if (optlen < IPOPT_OLEN + sizeof(*cp) || optlen > cnt) {
3094 				break;
3095 			}
3096 #endif
3097 		}
3098 		switch (opt) {
3099 		case IPOPT_RA:
3100 #ifdef DIAGNOSTIC
3101 			if (optlen != IPOPT_OFFSET + sizeof(uint16_t) ||
3102 			    (*((uint16_t *)(void *)&cp[IPOPT_OFFSET]) != 0)) {
3103 				break;
3104 			} else
3105 #endif
3106 			found_ra = 1;
3107 			break;
3108 		default:
3109 			break;
3110 		}
3111 	}
3112 
3113 	return found_ra;
3114 }
3115 
3116 /*
3117  * Given address of next destination (final or next hop),
3118  * return internet address info of interface to be used to get there.
3119  */
3120 struct in_ifaddr *
ip_rtaddr(struct in_addr dst)3121 ip_rtaddr(struct in_addr dst)
3122 {
3123 	struct sockaddr_in *sin;
3124 	struct ifaddr *rt_ifa;
3125 	struct route ro;
3126 
3127 	bzero(&ro, sizeof(ro));
3128 	sin = SIN(&ro.ro_dst);
3129 	sin->sin_family = AF_INET;
3130 	sin->sin_len = sizeof(*sin);
3131 	sin->sin_addr = dst;
3132 
3133 	rtalloc_ign(&ro, RTF_PRCLONING);
3134 	if (ro.ro_rt == NULL) {
3135 		ROUTE_RELEASE(&ro);
3136 		return NULL;
3137 	}
3138 
3139 	RT_LOCK(ro.ro_rt);
3140 	if ((rt_ifa = ro.ro_rt->rt_ifa) != NULL) {
3141 		IFA_ADDREF(rt_ifa);
3142 	}
3143 	RT_UNLOCK(ro.ro_rt);
3144 	ROUTE_RELEASE(&ro);
3145 
3146 	return (struct in_ifaddr *)rt_ifa;
3147 }
3148 
3149 /*
3150  * Save incoming source route for use in replies,
3151  * to be picked up later by ip_srcroute if the receiver is interested.
3152  */
3153 void
save_rte(u_char * option,struct in_addr dst)3154 save_rte(u_char *option, struct in_addr dst)
3155 {
3156 	unsigned olen;
3157 
3158 	olen = option[IPOPT_OLEN];
3159 #if DIAGNOSTIC
3160 	if (ipprintfs) {
3161 		printf("save_rte: olen %d\n", olen);
3162 	}
3163 #endif
3164 	if (olen > sizeof(ip_srcrt) - (1 + sizeof(dst))) {
3165 		return;
3166 	}
3167 	bcopy(option, ip_srcrt.srcopt, olen);
3168 	ip_nhops = (olen - IPOPT_OFFSET - 1) / sizeof(struct in_addr);
3169 	ip_srcrt.dst = dst;
3170 }
3171 
3172 /*
3173  * Retrieve incoming source route for use in replies,
3174  * in the same form used by setsockopt.
3175  * The first hop is placed before the options, will be removed later.
3176  */
3177 struct mbuf *
ip_srcroute(void)3178 ip_srcroute(void)
3179 {
3180 	struct in_addr *p, *q;
3181 	struct mbuf *m;
3182 
3183 	if (ip_nhops == 0) {
3184 		return NULL;
3185 	}
3186 
3187 	m = m_get(M_DONTWAIT, MT_HEADER);
3188 	if (m == NULL) {
3189 		return NULL;
3190 	}
3191 
3192 #define OPTSIZ  (sizeof (ip_srcrt.nop) + sizeof (ip_srcrt.srcopt))
3193 
3194 	/* length is (nhops+1)*sizeof(addr) + sizeof(nop + srcrt header) */
3195 	m->m_len = ip_nhops * sizeof(struct in_addr) +
3196 	    sizeof(struct in_addr) + OPTSIZ;
3197 #if DIAGNOSTIC
3198 	if (ipprintfs) {
3199 		printf("ip_srcroute: nhops %d mlen %d", ip_nhops, m->m_len);
3200 	}
3201 #endif
3202 
3203 	/*
3204 	 * First save first hop for return route
3205 	 */
3206 	p = &ip_srcrt.route[ip_nhops - 1];
3207 	*(mtod(m, struct in_addr *)) = *p--;
3208 #if DIAGNOSTIC
3209 	if (ipprintfs) {
3210 		printf(" hops %lx",
3211 		    (u_int32_t)ntohl(mtod(m, struct in_addr *)->s_addr));
3212 	}
3213 #endif
3214 
3215 	/*
3216 	 * Copy option fields and padding (nop) to mbuf.
3217 	 */
3218 	ip_srcrt.nop = IPOPT_NOP;
3219 	ip_srcrt.srcopt[IPOPT_OFFSET] = IPOPT_MINOFF;
3220 	(void) memcpy(mtod(m, caddr_t) + sizeof(struct in_addr),
3221 	    &ip_srcrt.nop, OPTSIZ);
3222 	q = (struct in_addr *)(void *)(mtod(m, caddr_t) +
3223 	    sizeof(struct in_addr) + OPTSIZ);
3224 #undef OPTSIZ
3225 	/*
3226 	 * Record return path as an IP source route,
3227 	 * reversing the path (pointers are now aligned).
3228 	 */
3229 	while (p >= ip_srcrt.route) {
3230 #if DIAGNOSTIC
3231 		if (ipprintfs) {
3232 			printf(" %lx", (u_int32_t)ntohl(q->s_addr));
3233 		}
3234 #endif
3235 		*q++ = *p--;
3236 	}
3237 	/*
3238 	 * Last hop goes to final destination.
3239 	 */
3240 	*q = ip_srcrt.dst;
3241 #if DIAGNOSTIC
3242 	if (ipprintfs) {
3243 		printf(" %lx\n", (u_int32_t)ntohl(q->s_addr));
3244 	}
3245 #endif
3246 	return m;
3247 }
3248 
3249 /*
3250  * Strip out IP options, at higher level protocol in the kernel.
3251  */
3252 void
ip_stripoptions(struct mbuf * m)3253 ip_stripoptions(struct mbuf *m)
3254 {
3255 	int i;
3256 	struct ip *ip = mtod(m, struct ip *);
3257 	caddr_t opts;
3258 	int olen;
3259 
3260 	/* Expect 32-bit aligned data pointer on strict-align platforms */
3261 	MBUF_STRICT_DATA_ALIGNMENT_CHECK_32(m);
3262 
3263 	/* use bcopy() since it supports overlapping range */
3264 	olen = (IP_VHL_HL(ip->ip_vhl) << 2) - sizeof(struct ip);
3265 	opts = (caddr_t)(ip + 1);
3266 	i = m->m_len - (sizeof(struct ip) + olen);
3267 	bcopy(opts + olen, opts, (unsigned)i);
3268 	m->m_len -= olen;
3269 	if (m->m_flags & M_PKTHDR) {
3270 		m->m_pkthdr.len -= olen;
3271 	}
3272 	ip->ip_vhl = IP_MAKE_VHL(IPVERSION, sizeof(struct ip) >> 2);
3273 
3274 	/*
3275 	 * We expect ip_{off,len} to be in host order by now, and
3276 	 * that the original IP header length has been subtracted
3277 	 * out from ip_len.  Temporarily adjust ip_len for checksum
3278 	 * recalculation, and restore it afterwards.
3279 	 */
3280 	ip->ip_len += sizeof(struct ip);
3281 
3282 	/* recompute checksum now that IP header is smaller */
3283 #if BYTE_ORDER != BIG_ENDIAN
3284 	HTONS(ip->ip_len);
3285 	HTONS(ip->ip_off);
3286 #endif /* BYTE_ORDER != BIG_ENDIAN */
3287 	ip->ip_sum = in_cksum_hdr(ip);
3288 #if BYTE_ORDER != BIG_ENDIAN
3289 	NTOHS(ip->ip_off);
3290 	NTOHS(ip->ip_len);
3291 #endif /* BYTE_ORDER != BIG_ENDIAN */
3292 
3293 	ip->ip_len -= sizeof(struct ip);
3294 
3295 	/*
3296 	 * Given that we've just stripped IP options from the header,
3297 	 * we need to adjust the start offset accordingly if this
3298 	 * packet had gone thru partial checksum offload.
3299 	 */
3300 	if ((m->m_pkthdr.csum_flags & (CSUM_DATA_VALID | CSUM_PARTIAL)) ==
3301 	    (CSUM_DATA_VALID | CSUM_PARTIAL)) {
3302 		if (m->m_pkthdr.csum_rx_start >= (sizeof(struct ip) + olen)) {
3303 			/* most common case */
3304 			m->m_pkthdr.csum_rx_start -= olen;
3305 		} else {
3306 			/* compute checksum in software instead */
3307 			m->m_pkthdr.csum_flags &= ~CSUM_DATA_VALID;
3308 			m->m_pkthdr.csum_data = 0;
3309 			ipstat.ips_adj_hwcsum_clr++;
3310 		}
3311 	}
3312 }
3313 
3314 u_char inetctlerrmap[PRC_NCMDS] = {
3315 	0, 0, 0, 0,
3316 	0, EMSGSIZE, EHOSTDOWN, EHOSTUNREACH,
3317 	ENETUNREACH, EHOSTUNREACH, ECONNREFUSED, ECONNREFUSED,
3318 	EMSGSIZE, EHOSTUNREACH, 0, 0,
3319 	0, 0, EHOSTUNREACH, 0,
3320 	ENOPROTOOPT, ECONNREFUSED
3321 };
3322 
3323 static int
3324 sysctl_ipforwarding SYSCTL_HANDLER_ARGS
3325 {
3326 #pragma unused(arg1, arg2)
3327 	int i, was_ipforwarding = ipforwarding;
3328 
3329 	i = sysctl_handle_int(oidp, oidp->oid_arg1, oidp->oid_arg2, req);
3330 	if (i != 0 || req->newptr == USER_ADDR_NULL) {
3331 		return i;
3332 	}
3333 
3334 	if (was_ipforwarding && !ipforwarding) {
3335 		/* clean up IPv4 forwarding cached routes */
3336 		ifnet_head_lock_shared();
3337 		for (i = 0; i <= if_index; i++) {
3338 			struct ifnet *ifp = ifindex2ifnet[i];
3339 			if (ifp != NULL) {
3340 				lck_mtx_lock(&ifp->if_cached_route_lock);
3341 				ROUTE_RELEASE(&ifp->if_fwd_route);
3342 				bzero(&ifp->if_fwd_route,
3343 				    sizeof(ifp->if_fwd_route));
3344 				lck_mtx_unlock(&ifp->if_cached_route_lock);
3345 			}
3346 		}
3347 		ifnet_head_done();
3348 	}
3349 
3350 	return 0;
3351 }
3352 
3353 /*
3354  * Similar to inp_route_{copyout,copyin} routines except that these copy
3355  * out the cached IPv4 forwarding route from struct ifnet instead of the
3356  * inpcb.  See comments for those routines for explanations.
3357  */
3358 static void
ip_fwd_route_copyout(struct ifnet * ifp,struct route * dst)3359 ip_fwd_route_copyout(struct ifnet *ifp, struct route *dst)
3360 {
3361 	struct route *src = &ifp->if_fwd_route;
3362 
3363 	lck_mtx_lock_spin(&ifp->if_cached_route_lock);
3364 	lck_mtx_convert_spin(&ifp->if_cached_route_lock);
3365 
3366 	/* Minor sanity check */
3367 	if (src->ro_rt != NULL && rt_key(src->ro_rt)->sa_family != AF_INET) {
3368 		panic("%s: wrong or corrupted route: %p", __func__, src);
3369 	}
3370 
3371 	route_copyout(dst, src, sizeof(*dst));
3372 
3373 	lck_mtx_unlock(&ifp->if_cached_route_lock);
3374 }
3375 
3376 static void
ip_fwd_route_copyin(struct ifnet * ifp,struct route * src)3377 ip_fwd_route_copyin(struct ifnet *ifp, struct route *src)
3378 {
3379 	struct route *dst = &ifp->if_fwd_route;
3380 
3381 	lck_mtx_lock_spin(&ifp->if_cached_route_lock);
3382 	lck_mtx_convert_spin(&ifp->if_cached_route_lock);
3383 
3384 	/* Minor sanity check */
3385 	if (src->ro_rt != NULL && rt_key(src->ro_rt)->sa_family != AF_INET) {
3386 		panic("%s: wrong or corrupted route: %p", __func__, src);
3387 	}
3388 
3389 	if (ifp->if_fwd_cacheok) {
3390 		route_copyin(src, dst, sizeof(*src));
3391 	}
3392 
3393 	lck_mtx_unlock(&ifp->if_cached_route_lock);
3394 }
3395 
3396 /*
3397  * Forward a packet.  If some error occurs return the sender
3398  * an icmp packet.  Note we can't always generate a meaningful
3399  * icmp message because icmp doesn't have a large enough repertoire
3400  * of codes and types.
3401  *
3402  * If not forwarding, just drop the packet.  This could be confusing
3403  * if ipforwarding was zero but some routing protocol was advancing
3404  * us as a gateway to somewhere.  However, we must let the routing
3405  * protocol deal with that.
3406  *
3407  * The srcrt parameter indicates whether the packet is being forwarded
3408  * via a source route.
3409  */
3410 static void
ip_forward(struct mbuf * m,int srcrt,struct sockaddr_in * next_hop)3411 ip_forward(struct mbuf *m, int srcrt, struct sockaddr_in *next_hop)
3412 {
3413 #pragma unused(next_hop)
3414 	struct ip *ip = mtod(m, struct ip *);
3415 	struct sockaddr_in *sin;
3416 	struct rtentry *rt;
3417 	struct route fwd_rt;
3418 	int error, type = 0, code = 0;
3419 	struct mbuf *mcopy;
3420 	n_long dest;
3421 	struct in_addr pkt_dst;
3422 	u_int32_t nextmtu = 0, len;
3423 	struct ip_out_args ipoa;
3424 	struct ifnet *rcvifp = m->m_pkthdr.rcvif;
3425 
3426 	bzero(&ipoa, sizeof(ipoa));
3427 	ipoa.ipoa_boundif = IFSCOPE_NONE;
3428 	ipoa.ipoa_sotc = SO_TC_UNSPEC;
3429 	ipoa.ipoa_netsvctype = _NET_SERVICE_TYPE_UNSPEC;
3430 
3431 #if IPSEC
3432 	struct secpolicy *sp = NULL;
3433 	int ipsecerror;
3434 #endif /* IPSEC */
3435 #if PF
3436 	struct pf_mtag *pf_mtag;
3437 #endif /* PF */
3438 
3439 	dest = 0;
3440 	pkt_dst = ip->ip_dst;
3441 
3442 #if DIAGNOSTIC
3443 	if (ipprintfs) {
3444 		printf("forward: src %lx dst %lx ttl %x\n",
3445 		    (u_int32_t)ip->ip_src.s_addr, (u_int32_t)pkt_dst.s_addr,
3446 		    ip->ip_ttl);
3447 	}
3448 #endif
3449 
3450 	if (m->m_flags & (M_BCAST | M_MCAST) || !in_canforward(pkt_dst)) {
3451 		OSAddAtomic(1, &ipstat.ips_cantforward);
3452 		m_freem(m);
3453 		return;
3454 	}
3455 #if IPSTEALTH
3456 	if (!ipstealth) {
3457 #endif /* IPSTEALTH */
3458 	if (ip->ip_ttl <= IPTTLDEC) {
3459 		icmp_error(m, ICMP_TIMXCEED, ICMP_TIMXCEED_INTRANS,
3460 		    dest, 0);
3461 		return;
3462 	}
3463 #if IPSTEALTH
3464 }
3465 #endif /* IPSTEALTH */
3466 
3467 #if PF
3468 	pf_mtag = pf_find_mtag(m);
3469 	if (pf_mtag != NULL && pf_mtag->pftag_rtableid != IFSCOPE_NONE) {
3470 		ipoa.ipoa_boundif = pf_mtag->pftag_rtableid;
3471 		ipoa.ipoa_flags |= IPOAF_BOUND_IF;
3472 	}
3473 #endif /* PF */
3474 
3475 	ip_fwd_route_copyout(rcvifp, &fwd_rt);
3476 
3477 	sin = SIN(&fwd_rt.ro_dst);
3478 	if (ROUTE_UNUSABLE(&fwd_rt) || pkt_dst.s_addr != sin->sin_addr.s_addr) {
3479 		ROUTE_RELEASE(&fwd_rt);
3480 
3481 		sin->sin_family = AF_INET;
3482 		sin->sin_len = sizeof(*sin);
3483 		sin->sin_addr = pkt_dst;
3484 
3485 		rtalloc_scoped_ign(&fwd_rt, RTF_PRCLONING, ipoa.ipoa_boundif);
3486 		if (fwd_rt.ro_rt == NULL) {
3487 			icmp_error(m, ICMP_UNREACH, ICMP_UNREACH_HOST, dest, 0);
3488 			goto done;
3489 		}
3490 	}
3491 	rt = fwd_rt.ro_rt;
3492 
3493 	/*
3494 	 * Save the IP header and at most 8 bytes of the payload,
3495 	 * in case we need to generate an ICMP message to the src.
3496 	 *
3497 	 * We don't use m_copy() because it might return a reference
3498 	 * to a shared cluster. Both this function and ip_output()
3499 	 * assume exclusive access to the IP header in `m', so any
3500 	 * data in a cluster may change before we reach icmp_error().
3501 	 */
3502 	MGET(mcopy, M_DONTWAIT, m->m_type);
3503 	if (mcopy != NULL && m_dup_pkthdr(mcopy, m, M_DONTWAIT) == 0) {
3504 		mcopy->m_len = imin((IP_VHL_HL(ip->ip_vhl) << 2) + 8,
3505 		    (int)ip->ip_len);
3506 		m_copydata(m, 0, mcopy->m_len, mtod(mcopy, caddr_t));
3507 	}
3508 
3509 #if IPSTEALTH
3510 	if (!ipstealth) {
3511 #endif /* IPSTEALTH */
3512 	ip->ip_ttl -= IPTTLDEC;
3513 #if IPSTEALTH
3514 }
3515 #endif /* IPSTEALTH */
3516 
3517 	/*
3518 	 * If forwarding packet using same interface that it came in on,
3519 	 * perhaps should send a redirect to sender to shortcut a hop.
3520 	 * Only send redirect if source is sending directly to us,
3521 	 * and if packet was not source routed (or has any options).
3522 	 * Also, don't send redirect if forwarding using a default route
3523 	 * or a route modified by a redirect.
3524 	 */
3525 	RT_LOCK_SPIN(rt);
3526 	if (rt->rt_ifp == m->m_pkthdr.rcvif &&
3527 	    !(rt->rt_flags & (RTF_DYNAMIC | RTF_MODIFIED)) &&
3528 	    satosin(rt_key(rt))->sin_addr.s_addr != INADDR_ANY &&
3529 	    ipsendredirects && !srcrt && rt->rt_ifa != NULL) {
3530 		struct in_ifaddr *ia = (struct in_ifaddr *)rt->rt_ifa;
3531 		u_int32_t src = ntohl(ip->ip_src.s_addr);
3532 
3533 		/* Become a regular mutex */
3534 		RT_CONVERT_LOCK(rt);
3535 		IFA_LOCK_SPIN(&ia->ia_ifa);
3536 		if ((src & ia->ia_subnetmask) == ia->ia_subnet) {
3537 			if (rt->rt_flags & RTF_GATEWAY) {
3538 				dest = satosin(rt->rt_gateway)->sin_addr.s_addr;
3539 			} else {
3540 				dest = pkt_dst.s_addr;
3541 			}
3542 			/*
3543 			 * Router requirements says to only send
3544 			 * host redirects.
3545 			 */
3546 			type = ICMP_REDIRECT;
3547 			code = ICMP_REDIRECT_HOST;
3548 #if DIAGNOSTIC
3549 			if (ipprintfs) {
3550 				printf("redirect (%d) to %lx\n", code,
3551 				    (u_int32_t)dest);
3552 			}
3553 #endif
3554 		}
3555 		IFA_UNLOCK(&ia->ia_ifa);
3556 	}
3557 	RT_UNLOCK(rt);
3558 
3559 
3560 	/* Mark this packet as being forwarded from another interface */
3561 	m->m_pkthdr.pkt_flags |= PKTF_FORWARDED;
3562 	len = m_pktlen(m);
3563 
3564 	error = ip_output(m, NULL, &fwd_rt, IP_FORWARDING | IP_OUTARGS,
3565 	    NULL, &ipoa);
3566 
3567 	/* Refresh rt since the route could have changed while in IP */
3568 	rt = fwd_rt.ro_rt;
3569 
3570 	if (error != 0) {
3571 		OSAddAtomic(1, &ipstat.ips_cantforward);
3572 	} else {
3573 		/*
3574 		 * Increment stats on the source interface; the ones
3575 		 * for destination interface has been taken care of
3576 		 * during output above by virtue of PKTF_FORWARDED.
3577 		 */
3578 		rcvifp->if_fpackets++;
3579 		rcvifp->if_fbytes += len;
3580 
3581 		OSAddAtomic(1, &ipstat.ips_forward);
3582 		if (type != 0) {
3583 			OSAddAtomic(1, &ipstat.ips_redirectsent);
3584 		} else {
3585 			if (mcopy != NULL) {
3586 				/*
3587 				 * If we didn't have to go thru ipflow and
3588 				 * the packet was successfully consumed by
3589 				 * ip_output, the mcopy is rather a waste;
3590 				 * this could be further optimized.
3591 				 */
3592 				m_freem(mcopy);
3593 			}
3594 			goto done;
3595 		}
3596 	}
3597 	if (mcopy == NULL) {
3598 		goto done;
3599 	}
3600 
3601 	switch (error) {
3602 	case 0:                         /* forwarded, but need redirect */
3603 		/* type, code set above */
3604 		break;
3605 
3606 	case ENETUNREACH:               /* shouldn't happen, checked above */
3607 	case EHOSTUNREACH:
3608 	case ENETDOWN:
3609 	case EHOSTDOWN:
3610 	default:
3611 		type = ICMP_UNREACH;
3612 		code = ICMP_UNREACH_HOST;
3613 		break;
3614 
3615 	case EMSGSIZE:
3616 		type = ICMP_UNREACH;
3617 		code = ICMP_UNREACH_NEEDFRAG;
3618 
3619 		if (rt == NULL) {
3620 			break;
3621 		} else {
3622 			RT_LOCK_SPIN(rt);
3623 			if (rt->rt_ifp != NULL) {
3624 				nextmtu = rt->rt_ifp->if_mtu;
3625 			}
3626 			RT_UNLOCK(rt);
3627 		}
3628 #ifdef IPSEC
3629 		if (ipsec_bypass) {
3630 			break;
3631 		}
3632 
3633 		/*
3634 		 * If the packet is routed over IPsec tunnel, tell the
3635 		 * originator the tunnel MTU.
3636 		 *	tunnel MTU = if MTU - sizeof(IP) - ESP/AH hdrsiz
3637 		 * XXX quickhack!!!
3638 		 */
3639 		sp = ipsec4_getpolicybyaddr(mcopy, IPSEC_DIR_OUTBOUND,
3640 		    IP_FORWARDING, &ipsecerror);
3641 
3642 		if (sp == NULL) {
3643 			break;
3644 		}
3645 
3646 		/*
3647 		 * find the correct route for outer IPv4
3648 		 * header, compute tunnel MTU.
3649 		 */
3650 		nextmtu = 0;
3651 
3652 		if (sp->req != NULL &&
3653 		    sp->req->saidx.mode == IPSEC_MODE_TUNNEL) {
3654 			struct secasindex saidx;
3655 			struct secasvar *sav;
3656 			struct route *ro;
3657 			struct ip *ipm;
3658 			size_t ipsechdr;
3659 
3660 			/* count IPsec header size */
3661 			ipsechdr = ipsec_hdrsiz(sp);
3662 
3663 			ipm = mtod(mcopy, struct ip *);
3664 			bcopy(&sp->req->saidx, &saidx, sizeof(saidx));
3665 			saidx.mode = sp->req->saidx.mode;
3666 			saidx.reqid = sp->req->saidx.reqid;
3667 			sin = SIN(&saidx.src);
3668 			if (sin->sin_len == 0) {
3669 				sin->sin_len = sizeof(*sin);
3670 				sin->sin_family = AF_INET;
3671 				sin->sin_port = IPSEC_PORT_ANY;
3672 				bcopy(&ipm->ip_src, &sin->sin_addr,
3673 				    sizeof(sin->sin_addr));
3674 			}
3675 			sin = SIN(&saidx.dst);
3676 			if (sin->sin_len == 0) {
3677 				sin->sin_len = sizeof(*sin);
3678 				sin->sin_family = AF_INET;
3679 				sin->sin_port = IPSEC_PORT_ANY;
3680 				bcopy(&ipm->ip_dst, &sin->sin_addr,
3681 				    sizeof(sin->sin_addr));
3682 			}
3683 			sav = key_allocsa_policy(&saidx);
3684 			if (sav != NULL) {
3685 				lck_mtx_lock(sadb_mutex);
3686 				if (sav->sah != NULL) {
3687 					ro = (struct route *)&sav->sah->sa_route;
3688 					if (ro->ro_rt != NULL) {
3689 						RT_LOCK(ro->ro_rt);
3690 						if (ro->ro_rt->rt_ifp != NULL) {
3691 							nextmtu = ro->ro_rt->
3692 							    rt_ifp->if_mtu;
3693 							nextmtu -= ipsechdr;
3694 						}
3695 						RT_UNLOCK(ro->ro_rt);
3696 					}
3697 				}
3698 				key_freesav(sav, KEY_SADB_LOCKED);
3699 				lck_mtx_unlock(sadb_mutex);
3700 			}
3701 		}
3702 		key_freesp(sp, KEY_SADB_UNLOCKED);
3703 #endif /* IPSEC */
3704 		break;
3705 
3706 	case ENOBUFS:
3707 		/*
3708 		 * A router should not generate ICMP_SOURCEQUENCH as
3709 		 * required in RFC1812 Requirements for IP Version 4 Routers.
3710 		 * Source quench could be a big problem under DoS attacks,
3711 		 * or if the underlying interface is rate-limited.
3712 		 * Those who need source quench packets may re-enable them
3713 		 * via the net.inet.ip.sendsourcequench sysctl.
3714 		 */
3715 		if (ip_sendsourcequench == 0) {
3716 			m_freem(mcopy);
3717 			goto done;
3718 		} else {
3719 			type = ICMP_SOURCEQUENCH;
3720 			code = 0;
3721 		}
3722 		break;
3723 
3724 	case EACCES:
3725 		m_freem(mcopy);
3726 		goto done;
3727 	}
3728 
3729 	if (type == ICMP_UNREACH && code == ICMP_UNREACH_NEEDFRAG) {
3730 		OSAddAtomic(1, &ipstat.ips_cantfrag);
3731 	}
3732 
3733 	icmp_error(mcopy, type, code, dest, nextmtu);
3734 done:
3735 	ip_fwd_route_copyin(rcvifp, &fwd_rt);
3736 }
3737 
3738 int
ip_savecontrol(struct inpcb * inp,struct mbuf ** mp,struct ip * ip,struct mbuf * m)3739 ip_savecontrol(struct inpcb *inp, struct mbuf **mp, struct ip *ip,
3740     struct mbuf *m)
3741 {
3742 	*mp = NULL;
3743 	if (inp->inp_socket->so_options & SO_TIMESTAMP) {
3744 		struct timeval tv;
3745 
3746 		getmicrotime(&tv);
3747 		mp = sbcreatecontrol_mbuf((caddr_t)&tv, sizeof(tv),
3748 		    SCM_TIMESTAMP, SOL_SOCKET, mp);
3749 		if (*mp == NULL) {
3750 			goto no_mbufs;
3751 		}
3752 	}
3753 	if (inp->inp_socket->so_options & SO_TIMESTAMP_MONOTONIC) {
3754 		uint64_t time;
3755 
3756 		time = mach_absolute_time();
3757 		mp = sbcreatecontrol_mbuf((caddr_t)&time, sizeof(time),
3758 		    SCM_TIMESTAMP_MONOTONIC, SOL_SOCKET, mp);
3759 		if (*mp == NULL) {
3760 			goto no_mbufs;
3761 		}
3762 	}
3763 	if (inp->inp_socket->so_options & SO_TIMESTAMP_CONTINUOUS) {
3764 		uint64_t time;
3765 
3766 		time = mach_continuous_time();
3767 		mp = sbcreatecontrol_mbuf((caddr_t)&time, sizeof(time),
3768 		    SCM_TIMESTAMP_CONTINUOUS, SOL_SOCKET, mp);
3769 		if (*mp == NULL) {
3770 			goto no_mbufs;
3771 		}
3772 	}
3773 	if (inp->inp_socket->so_flags & SOF_RECV_TRAFFIC_CLASS) {
3774 		int tc = m_get_traffic_class(m);
3775 
3776 		mp = sbcreatecontrol_mbuf((caddr_t)&tc, sizeof(tc),
3777 		    SO_TRAFFIC_CLASS, SOL_SOCKET, mp);
3778 		if (*mp == NULL) {
3779 			goto no_mbufs;
3780 		}
3781 	}
3782 	if ((inp->inp_socket->so_flags & SOF_RECV_WAKE_PKT) &&
3783 	    (m->m_pkthdr.pkt_flags & PKTF_WAKE_PKT)) {
3784 		int flag = 1;
3785 
3786 		mp = sbcreatecontrol_mbuf((caddr_t)&flag, sizeof(flag),
3787 		    SO_RECV_WAKE_PKT, SOL_SOCKET, mp);
3788 		if (*mp == NULL) {
3789 			goto no_mbufs;
3790 		}
3791 	}
3792 
3793 	if (inp->inp_flags & INP_RECVDSTADDR || SOFLOW_ENABLED(inp->inp_socket)) {
3794 		mp = sbcreatecontrol_mbuf((caddr_t)&ip->ip_dst,
3795 		    sizeof(struct in_addr), IP_RECVDSTADDR, IPPROTO_IP, mp);
3796 		if (*mp == NULL) {
3797 			goto no_mbufs;
3798 		}
3799 	}
3800 #ifdef notyet
3801 	/*
3802 	 * XXX
3803 	 * Moving these out of udp_input() made them even more broken
3804 	 * than they already were.
3805 	 */
3806 	/* options were tossed already */
3807 	if (inp->inp_flags & INP_RECVOPTS) {
3808 		mp = sbcreatecontrol_mbuf((caddr_t)opts_deleted_above,
3809 		    sizeof(struct in_addr), IP_RECVOPTS, IPPROTO_IP, mp);
3810 		if (*mp == NULL) {
3811 			goto no_mbufs;
3812 		}
3813 	}
3814 	/* ip_srcroute doesn't do what we want here, need to fix */
3815 	if (inp->inp_flags & INP_RECVRETOPTS) {
3816 		mp = sbcreatecontrol_mbuf((caddr_t)ip_srcroute(),
3817 		    sizeof(struct in_addr), IP_RECVRETOPTS, IPPROTO_IP, mp);
3818 		if (*mp == NULL) {
3819 			goto no_mbufs;
3820 		}
3821 	}
3822 #endif /* notyet */
3823 	if (inp->inp_flags & INP_RECVIF) {
3824 		struct ifnet *ifp;
3825 		uint8_t sdlbuf[SOCK_MAXADDRLEN + 1];
3826 		struct sockaddr_dl *sdl2 = SDL(&sdlbuf);
3827 
3828 		/*
3829 		 * Make sure to accomodate the largest possible
3830 		 * size of SA(if_lladdr)->sa_len.
3831 		 */
3832 		_CASSERT(sizeof(sdlbuf) == (SOCK_MAXADDRLEN + 1));
3833 
3834 		ifnet_head_lock_shared();
3835 		if ((ifp = m->m_pkthdr.rcvif) != NULL &&
3836 		    ifp->if_index && (ifp->if_index <= if_index)) {
3837 			struct ifaddr *ifa = ifnet_addrs[ifp->if_index - 1];
3838 			struct sockaddr_dl *sdp;
3839 
3840 			if (!ifa || !ifa->ifa_addr) {
3841 				goto makedummy;
3842 			}
3843 
3844 			IFA_LOCK_SPIN(ifa);
3845 			sdp = SDL(ifa->ifa_addr);
3846 			/*
3847 			 * Change our mind and don't try copy.
3848 			 */
3849 			if (sdp->sdl_family != AF_LINK) {
3850 				IFA_UNLOCK(ifa);
3851 				goto makedummy;
3852 			}
3853 			/* the above _CASSERT ensures sdl_len fits in sdlbuf */
3854 			bcopy(sdp, sdl2, sdp->sdl_len);
3855 			IFA_UNLOCK(ifa);
3856 		} else {
3857 makedummy:
3858 			sdl2->sdl_len =
3859 			    offsetof(struct sockaddr_dl, sdl_data[0]);
3860 			sdl2->sdl_family = AF_LINK;
3861 			sdl2->sdl_index = 0;
3862 			sdl2->sdl_nlen = sdl2->sdl_alen = sdl2->sdl_slen = 0;
3863 		}
3864 		ifnet_head_done();
3865 		mp = sbcreatecontrol_mbuf((caddr_t)sdl2, sdl2->sdl_len,
3866 		    IP_RECVIF, IPPROTO_IP, mp);
3867 		if (*mp == NULL) {
3868 			goto no_mbufs;
3869 		}
3870 	}
3871 	if (inp->inp_flags & INP_RECVTTL) {
3872 		mp = sbcreatecontrol_mbuf((caddr_t)&ip->ip_ttl,
3873 		    sizeof(ip->ip_ttl), IP_RECVTTL, IPPROTO_IP, mp);
3874 		if (*mp == NULL) {
3875 			goto no_mbufs;
3876 		}
3877 	}
3878 	if (inp->inp_flags & INP_PKTINFO) {
3879 		struct in_pktinfo pi;
3880 
3881 		bzero(&pi, sizeof(struct in_pktinfo));
3882 		bcopy(&ip->ip_dst, &pi.ipi_addr, sizeof(struct in_addr));
3883 		pi.ipi_ifindex = (m != NULL && m->m_pkthdr.rcvif != NULL) ?
3884 		    m->m_pkthdr.rcvif->if_index : 0;
3885 
3886 		mp = sbcreatecontrol_mbuf((caddr_t)&pi,
3887 		    sizeof(struct in_pktinfo), IP_RECVPKTINFO, IPPROTO_IP, mp);
3888 		if (*mp == NULL) {
3889 			goto no_mbufs;
3890 		}
3891 	}
3892 	if (inp->inp_flags & INP_RECVTOS) {
3893 		mp = sbcreatecontrol_mbuf((caddr_t)&ip->ip_tos,
3894 		    sizeof(u_char), IP_RECVTOS, IPPROTO_IP, mp);
3895 		if (*mp == NULL) {
3896 			goto no_mbufs;
3897 		}
3898 	}
3899 	return 0;
3900 
3901 no_mbufs:
3902 	ipstat.ips_pktdropcntrl++;
3903 	return ENOBUFS;
3904 }
3905 
3906 static inline u_short
ip_cksum(struct mbuf * m,int hlen)3907 ip_cksum(struct mbuf *m, int hlen)
3908 {
3909 	u_short sum;
3910 
3911 	if (m->m_pkthdr.csum_flags & CSUM_IP_CHECKED) {
3912 		sum = !(m->m_pkthdr.csum_flags & CSUM_IP_VALID);
3913 	} else if (!(m->m_pkthdr.rcvif->if_flags & IFF_LOOPBACK) &&
3914 	    !(m->m_pkthdr.pkt_flags & PKTF_LOOP)) {
3915 		/*
3916 		 * The packet arrived on an interface which isn't capable
3917 		 * of performing IP header checksum; compute it now.
3918 		 */
3919 		sum = ip_cksum_hdr_in(m, hlen);
3920 	} else {
3921 		sum = 0;
3922 		m->m_pkthdr.csum_flags |= (CSUM_DATA_VALID | CSUM_PSEUDO_HDR |
3923 		    CSUM_IP_CHECKED | CSUM_IP_VALID);
3924 		m->m_pkthdr.csum_data = 0xffff;
3925 	}
3926 
3927 	if (sum != 0) {
3928 		OSAddAtomic(1, &ipstat.ips_badsum);
3929 	}
3930 
3931 	return sum;
3932 }
3933 
3934 static int
3935 ip_getstat SYSCTL_HANDLER_ARGS
3936 {
3937 #pragma unused(oidp, arg1, arg2)
3938 	if (req->oldptr == USER_ADDR_NULL) {
3939 		req->oldlen = (size_t)sizeof(struct ipstat);
3940 	}
3941 
3942 	return SYSCTL_OUT(req, &ipstat, MIN(sizeof(ipstat), req->oldlen));
3943 }
3944 
3945 void
ip_setsrcifaddr_info(struct mbuf * m,uint16_t src_idx,struct in_ifaddr * ia)3946 ip_setsrcifaddr_info(struct mbuf *m, uint16_t src_idx, struct in_ifaddr *ia)
3947 {
3948 	VERIFY(m->m_flags & M_PKTHDR);
3949 
3950 	/*
3951 	 * If the source ifaddr is specified, pick up the information
3952 	 * from there; otherwise just grab the passed-in ifindex as the
3953 	 * caller may not have the ifaddr available.
3954 	 */
3955 	if (ia != NULL) {
3956 		m->m_pkthdr.pkt_flags |= PKTF_IFAINFO;
3957 		m->m_pkthdr.src_ifindex = ia->ia_ifp->if_index;
3958 	} else {
3959 		m->m_pkthdr.src_ifindex = src_idx;
3960 		if (src_idx != 0) {
3961 			m->m_pkthdr.pkt_flags |= PKTF_IFAINFO;
3962 		}
3963 	}
3964 }
3965 
3966 void
ip_setdstifaddr_info(struct mbuf * m,uint16_t dst_idx,struct in_ifaddr * ia)3967 ip_setdstifaddr_info(struct mbuf *m, uint16_t dst_idx, struct in_ifaddr *ia)
3968 {
3969 	VERIFY(m->m_flags & M_PKTHDR);
3970 
3971 	/*
3972 	 * If the destination ifaddr is specified, pick up the information
3973 	 * from there; otherwise just grab the passed-in ifindex as the
3974 	 * caller may not have the ifaddr available.
3975 	 */
3976 	if (ia != NULL) {
3977 		m->m_pkthdr.pkt_flags |= PKTF_IFAINFO;
3978 		m->m_pkthdr.dst_ifindex = ia->ia_ifp->if_index;
3979 	} else {
3980 		m->m_pkthdr.dst_ifindex = dst_idx;
3981 		if (dst_idx != 0) {
3982 			m->m_pkthdr.pkt_flags |= PKTF_IFAINFO;
3983 		}
3984 	}
3985 }
3986 
3987 int
ip_getsrcifaddr_info(struct mbuf * m,uint32_t * src_idx,uint32_t * iaf)3988 ip_getsrcifaddr_info(struct mbuf *m, uint32_t *src_idx, uint32_t *iaf)
3989 {
3990 	VERIFY(m->m_flags & M_PKTHDR);
3991 
3992 	if (!(m->m_pkthdr.pkt_flags & PKTF_IFAINFO)) {
3993 		return -1;
3994 	}
3995 
3996 	if (src_idx != NULL) {
3997 		*src_idx = m->m_pkthdr.src_ifindex;
3998 	}
3999 
4000 	if (iaf != NULL) {
4001 		*iaf = 0;
4002 	}
4003 
4004 	return 0;
4005 }
4006 
4007 int
ip_getdstifaddr_info(struct mbuf * m,uint32_t * dst_idx,uint32_t * iaf)4008 ip_getdstifaddr_info(struct mbuf *m, uint32_t *dst_idx, uint32_t *iaf)
4009 {
4010 	VERIFY(m->m_flags & M_PKTHDR);
4011 
4012 	if (!(m->m_pkthdr.pkt_flags & PKTF_IFAINFO)) {
4013 		return -1;
4014 	}
4015 
4016 	if (dst_idx != NULL) {
4017 		*dst_idx = m->m_pkthdr.dst_ifindex;
4018 	}
4019 
4020 	if (iaf != NULL) {
4021 		*iaf = 0;
4022 	}
4023 
4024 	return 0;
4025 }
4026 
4027 /*
4028  * Protocol input handler for IPPROTO_GRE.
4029  */
4030 void
gre_input(struct mbuf * m,int off)4031 gre_input(struct mbuf *m, int off)
4032 {
4033 	gre_input_func_t fn = gre_input_func;
4034 
4035 	/*
4036 	 * If there is a registered GRE input handler, pass mbuf to it.
4037 	 */
4038 	if (fn != NULL) {
4039 		lck_mtx_unlock(inet_domain_mutex);
4040 		m = fn(m, off, (mtod(m, struct ip *))->ip_p);
4041 		lck_mtx_lock(inet_domain_mutex);
4042 	}
4043 
4044 	/*
4045 	 * If no matching tunnel that is up is found, we inject
4046 	 * the mbuf to raw ip socket to see if anyone picks it up.
4047 	 */
4048 	if (m != NULL) {
4049 		rip_input(m, off);
4050 	}
4051 }
4052 
4053 /*
4054  * Private KPI for PPP/PPTP.
4055  */
4056 int
ip_gre_register_input(gre_input_func_t fn)4057 ip_gre_register_input(gre_input_func_t fn)
4058 {
4059 	lck_mtx_lock(inet_domain_mutex);
4060 	gre_input_func = fn;
4061 	lck_mtx_unlock(inet_domain_mutex);
4062 
4063 	return 0;
4064 }
4065 
4066 #if (DEBUG || DEVELOPMENT)
4067 static int
4068 sysctl_reset_ip_input_stats SYSCTL_HANDLER_ARGS
4069 {
4070 #pragma unused(arg1, arg2)
4071 	int error, i;
4072 
4073 	i = ip_input_measure;
4074 	error = sysctl_handle_int(oidp, &i, 0, req);
4075 	if (error || req->newptr == USER_ADDR_NULL) {
4076 		goto done;
4077 	}
4078 	/* impose bounds */
4079 	if (i < 0 || i > 1) {
4080 		error = EINVAL;
4081 		goto done;
4082 	}
4083 	if (ip_input_measure != i && i == 1) {
4084 		net_perf_initialize(&net_perf, ip_input_measure_bins);
4085 	}
4086 	ip_input_measure = i;
4087 done:
4088 	return error;
4089 }
4090 
4091 static int
4092 sysctl_ip_input_measure_bins SYSCTL_HANDLER_ARGS
4093 {
4094 #pragma unused(arg1, arg2)
4095 	int error;
4096 	uint64_t i;
4097 
4098 	i = ip_input_measure_bins;
4099 	error = sysctl_handle_quad(oidp, &i, 0, req);
4100 	if (error || req->newptr == USER_ADDR_NULL) {
4101 		goto done;
4102 	}
4103 	/* validate data */
4104 	if (!net_perf_validate_bins(i)) {
4105 		error = EINVAL;
4106 		goto done;
4107 	}
4108 	ip_input_measure_bins = i;
4109 done:
4110 	return error;
4111 }
4112 
4113 static int
4114 sysctl_ip_input_getperf SYSCTL_HANDLER_ARGS
4115 {
4116 #pragma unused(oidp, arg1, arg2)
4117 	if (req->oldptr == USER_ADDR_NULL) {
4118 		req->oldlen = (size_t)sizeof(struct ipstat);
4119 	}
4120 
4121 	return SYSCTL_OUT(req, &net_perf, MIN(sizeof(net_perf), req->oldlen));
4122 }
4123 #endif /* (DEBUG || DEVELOPMENT) */
4124 
4125 static int
4126 sysctl_ip_checkinterface SYSCTL_HANDLER_ARGS
4127 {
4128 #pragma unused(arg1, arg2)
4129 	int error, i;
4130 
4131 	i = ip_checkinterface;
4132 	error = sysctl_handle_int(oidp, &i, 0, req);
4133 	if (error != 0 || req->newptr == USER_ADDR_NULL) {
4134 		return error;
4135 	}
4136 
4137 	switch (i) {
4138 	case IP_CHECKINTERFACE_WEAK_ES:
4139 	case IP_CHECKINTERFACE_HYBRID_ES:
4140 	case IP_CHECKINTERFACE_STRONG_ES:
4141 		if (ip_checkinterface != i) {
4142 			ip_checkinterface = i;
4143 			os_log(OS_LOG_DEFAULT, "%s: ip_checkinterface is now %d\n",
4144 			    __func__, ip_checkinterface);
4145 		}
4146 		break;
4147 	default:
4148 		error = EINVAL;
4149 		break;
4150 	}
4151 	return error;
4152 }
4153