2 * Copyright (c) 2000-2020 Apple Inc. All rights reserved.
4 * @APPLE_OSREFERENCE_LICENSE_HEADER_START@
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.
15 * Please obtain a copy of the License at
16 * http://www.opensource.apple.com/apsl/ and read it before using this file.
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.
26 * @APPLE_OSREFERENCE_LICENSE_HEADER_END@
29 * Copyright (c) 1982, 1986, 1988, 1993
30 * The Regents of the University of California. All rights reserved.
32 * Redistribution and use in source and binary forms, with or without
33 * modification, are permitted provided that the following conditions
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.
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
60 * @(#)ip_input.c 8.2 (Berkeley) 1/4/94
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,
71 #include <sys/param.h>
72 #include <sys/systm.h>
74 #include <sys/malloc.h>
75 #include <sys/domain.h>
76 #include <sys/protosw.h>
77 #include <sys/socket.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>
88 #include <machine/endian.h>
89 #include <dev/random/randomdev.h>
91 #include <kern/queue.h>
92 #include <kern/locks.h>
93 #include <libkern/OSAtomic.h>
95 #include <pexpert/pexpert.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>
108 #include <net/pfvar.h>
111 #include <netinet/in.h>
112 #include <netinet/in_systm.h>
113 #include <netinet/in_var.h>
114 #include <netinet/in_arp.h>
115 #include <netinet/ip.h>
116 #include <netinet/in_pcb.h>
117 #include <netinet/ip_var.h>
118 #include <netinet/ip_icmp.h>
119 #include <netinet/kpi_ipfilter_var.h>
120 #include <netinet/udp.h>
121 #include <netinet/udp_var.h>
122 #include <netinet/bootp.h>
125 #include <netinet/ip_dummynet.h>
126 #endif /* DUMMYNET */
129 #include <netinet6/ipsec.h>
130 #include <netkey/key.h>
135 #define DBG_LAYER_BEG NETDBG_CODE(DBG_NETIP, 0)
136 #define DBG_LAYER_END NETDBG_CODE(DBG_NETIP, 2)
137 #define DBG_FNC_IP_INPUT NETDBG_CODE(DBG_NETIP, (2 << 8))
140 extern int ipsec_bypass
;
141 extern lck_mtx_t
*sadb_mutex
;
143 lck_grp_t
*sadb_stat_mutex_grp
;
144 lck_grp_attr_t
*sadb_stat_mutex_grp_attr
;
145 lck_attr_t
*sadb_stat_mutex_attr
;
146 decl_lck_mtx_data(, sadb_stat_mutex_data
);
147 lck_mtx_t
*sadb_stat_mutex
= &sadb_stat_mutex_data
;
152 static int frag_timeout_run
; /* frag timer is scheduled to run */
153 static void frag_timeout(void *);
154 static void frag_sched_timeout(void);
156 static struct ipq
*ipq_alloc(int);
157 static void ipq_free(struct ipq
*);
158 static void ipq_updateparams(void);
159 static void ip_input_second_pass(struct mbuf
*, struct ifnet
*,
160 int, int, struct ip_fw_in_args
*);
162 decl_lck_mtx_data(static, ipqlock
);
163 static lck_attr_t
*ipqlock_attr
;
164 static lck_grp_t
*ipqlock_grp
;
165 static lck_grp_attr_t
*ipqlock_grp_attr
;
167 /* Packet reassembly stuff */
168 #define IPREASS_NHASH_LOG2 6
169 #define IPREASS_NHASH (1 << IPREASS_NHASH_LOG2)
170 #define IPREASS_HMASK (IPREASS_NHASH - 1)
171 #define IPREASS_HASH(x, y) \
172 (((((x) & 0xF) | ((((x) >> 8) & 0xF) << 4)) ^ (y)) & IPREASS_HMASK)
174 /* IP fragment reassembly queues (protected by ipqlock) */
175 static TAILQ_HEAD(ipqhead
, ipq
) ipq
[IPREASS_NHASH
]; /* ip reassembly queues */
176 static int maxnipq
; /* max packets in reass queues */
177 static u_int32_t maxfragsperpacket
; /* max frags/packet in reass queues */
178 static u_int32_t nipq
; /* # of packets in reass queues */
179 static u_int32_t ipq_limit
; /* ipq allocation limit */
180 static u_int32_t ipq_count
; /* current # of allocated ipq's */
182 static int sysctl_ipforwarding SYSCTL_HANDLER_ARGS
;
183 static int sysctl_maxnipq SYSCTL_HANDLER_ARGS
;
184 static int sysctl_maxfragsperpacket SYSCTL_HANDLER_ARGS
;
186 #if (DEBUG || DEVELOPMENT)
187 static int sysctl_reset_ip_input_stats SYSCTL_HANDLER_ARGS
;
188 static int sysctl_ip_input_measure_bins SYSCTL_HANDLER_ARGS
;
189 static int sysctl_ip_input_getperf SYSCTL_HANDLER_ARGS
;
190 #endif /* (DEBUG || DEVELOPMENT) */
192 int ipforwarding
= 0;
193 SYSCTL_PROC(_net_inet_ip
, IPCTL_FORWARDING
, forwarding
,
194 CTLTYPE_INT
| CTLFLAG_RW
| CTLFLAG_LOCKED
, &ipforwarding
, 0,
195 sysctl_ipforwarding
, "I", "Enable IP forwarding between interfaces");
197 static int ipsendredirects
= 1; /* XXX */
198 SYSCTL_INT(_net_inet_ip
, IPCTL_SENDREDIRECTS
, redirect
,
199 CTLFLAG_RW
| CTLFLAG_LOCKED
, &ipsendredirects
, 0,
200 "Enable sending IP redirects");
202 int ip_defttl
= IPDEFTTL
;
203 SYSCTL_INT(_net_inet_ip
, IPCTL_DEFTTL
, ttl
, CTLFLAG_RW
| CTLFLAG_LOCKED
,
204 &ip_defttl
, 0, "Maximum TTL on IP packets");
206 static int ip_dosourceroute
= 0;
207 SYSCTL_INT(_net_inet_ip
, IPCTL_SOURCEROUTE
, sourceroute
,
208 CTLFLAG_RW
| CTLFLAG_LOCKED
, &ip_dosourceroute
, 0,
209 "Enable forwarding source routed IP packets");
211 static int ip_acceptsourceroute
= 0;
212 SYSCTL_INT(_net_inet_ip
, IPCTL_ACCEPTSOURCEROUTE
, accept_sourceroute
,
213 CTLFLAG_RW
| CTLFLAG_LOCKED
, &ip_acceptsourceroute
, 0,
214 "Enable accepting source routed IP packets");
216 static int ip_sendsourcequench
= 0;
217 SYSCTL_INT(_net_inet_ip
, OID_AUTO
, sendsourcequench
,
218 CTLFLAG_RW
| CTLFLAG_LOCKED
, &ip_sendsourcequench
, 0,
219 "Enable the transmission of source quench packets");
221 SYSCTL_PROC(_net_inet_ip
, OID_AUTO
, maxfragpackets
,
222 CTLTYPE_INT
| CTLFLAG_RW
| CTLFLAG_LOCKED
, &maxnipq
, 0, sysctl_maxnipq
,
223 "I", "Maximum number of IPv4 fragment reassembly queue entries");
225 SYSCTL_UINT(_net_inet_ip
, OID_AUTO
, fragpackets
, CTLFLAG_RD
| CTLFLAG_LOCKED
,
226 &nipq
, 0, "Current number of IPv4 fragment reassembly queue entries");
228 SYSCTL_PROC(_net_inet_ip
, OID_AUTO
, maxfragsperpacket
,
229 CTLTYPE_INT
| CTLFLAG_RW
| CTLFLAG_LOCKED
, &maxfragsperpacket
, 0,
230 sysctl_maxfragsperpacket
, "I",
231 "Maximum number of IPv4 fragments allowed per packet");
233 static uint32_t ip_adj_clear_hwcksum
= 0;
234 SYSCTL_UINT(_net_inet_ip
, OID_AUTO
, adj_clear_hwcksum
,
235 CTLFLAG_RW
| CTLFLAG_LOCKED
, &ip_adj_clear_hwcksum
, 0,
236 "Invalidate hwcksum info when adjusting length");
238 static uint32_t ip_adj_partial_sum
= 1;
239 SYSCTL_UINT(_net_inet_ip
, OID_AUTO
, adj_partial_sum
,
240 CTLFLAG_RW
| CTLFLAG_LOCKED
, &ip_adj_partial_sum
, 0,
241 "Perform partial sum adjustment of trailing bytes at IP layer");
244 * ip_checkinterface controls the receive side of the models for multihoming
245 * that are discussed in RFC 1122.
247 * ip_checkinterface values are:
248 * IP_CHECKINTERFACE_WEAK_ES:
249 * This corresponds to the Weak End-System model where incoming packets from
250 * any interface are accepted provided the destination address of the incoming packet
251 * is assigned to some interface.
253 * IP_CHECKINTERFACE_HYBRID_ES:
254 * The Hybrid End-System model use the Strong End-System for tunnel interfaces
255 * (ipsec and utun) and the weak End-System model for other interfaces families.
256 * This prevents a rogue middle box to probe for signs of TCP connections
257 * that use the tunnel interface.
259 * IP_CHECKINTERFACE_STRONG_ES:
260 * The Strong model model requires the packet arrived on an interface that
261 * is assigned the destination address of the packet.
263 * Since the routing table and transmit implementation do not implement the Strong ES model,
264 * setting this to a value different from IP_CHECKINTERFACE_WEAK_ES may lead to unexpected results.
266 * When forwarding is enabled, the system reverts to the Weak ES model as a router
267 * is expected by design to receive packets from several interfaces to the same address.
269 * XXX - ip_checkinterface currently must be set to IP_CHECKINTERFACE_WEAK_ES if you use ipnat
270 * to translate the destination address to another local interface.
272 * XXX - ip_checkinterface must be set to IP_CHECKINTERFACE_WEAK_ES if you add IP aliases
273 * to the loopback interface instead of the interface where the
274 * packets for those addresses are received.
276 #define IP_CHECKINTERFACE_WEAK_ES 0
277 #define IP_CHECKINTERFACE_HYBRID_ES 1
278 #define IP_CHECKINTERFACE_STRONG_ES 2
280 static int ip_checkinterface
= IP_CHECKINTERFACE_HYBRID_ES
;
282 static int sysctl_ip_checkinterface SYSCTL_HANDLER_ARGS
;
283 SYSCTL_PROC(_net_inet_ip
, OID_AUTO
, check_interface
,
284 CTLTYPE_INT
| CTLFLAG_RW
| CTLFLAG_LOCKED
,
285 0, 0, sysctl_ip_checkinterface
, "I", "Verify packet arrives on correct interface");
287 #if (DEBUG || DEVELOPMENT)
288 #define IP_CHECK_IF_DEBUG 1
290 #define IP_CHECK_IF_DEBUG 0
291 #endif /* (DEBUG || DEVELOPMENT) */
292 static int ip_checkinterface_debug
= IP_CHECK_IF_DEBUG
;
293 SYSCTL_INT(_net_inet_ip
, OID_AUTO
, checkinterface_debug
, CTLFLAG_RW
| CTLFLAG_LOCKED
,
294 &ip_checkinterface_debug
, IP_CHECK_IF_DEBUG
, "");
296 static int ip_chaining
= 1;
297 SYSCTL_INT(_net_inet_ip
, OID_AUTO
, rx_chaining
, CTLFLAG_RW
| CTLFLAG_LOCKED
,
298 &ip_chaining
, 1, "Do receive side ip address based chaining");
300 static int ip_chainsz
= 6;
301 SYSCTL_INT(_net_inet_ip
, OID_AUTO
, rx_chainsz
, CTLFLAG_RW
| CTLFLAG_LOCKED
,
302 &ip_chainsz
, 1, "IP receive side max chaining");
304 #if (DEBUG || DEVELOPMENT)
305 static int ip_input_measure
= 0;
306 SYSCTL_PROC(_net_inet_ip
, OID_AUTO
, input_perf
,
307 CTLTYPE_INT
| CTLFLAG_RW
| CTLFLAG_LOCKED
,
308 &ip_input_measure
, 0, sysctl_reset_ip_input_stats
, "I", "Do time measurement");
310 static uint64_t ip_input_measure_bins
= 0;
311 SYSCTL_PROC(_net_inet_ip
, OID_AUTO
, input_perf_bins
,
312 CTLTYPE_QUAD
| CTLFLAG_RW
| CTLFLAG_LOCKED
, &ip_input_measure_bins
, 0,
313 sysctl_ip_input_measure_bins
, "I",
314 "bins for chaining performance data histogram");
316 static net_perf_t net_perf
;
317 SYSCTL_PROC(_net_inet_ip
, OID_AUTO
, input_perf_data
,
318 CTLTYPE_STRUCT
| CTLFLAG_RD
| CTLFLAG_LOCKED
,
319 0, 0, sysctl_ip_input_getperf
, "S,net_perf",
320 "IP input performance data (struct net_perf, net/net_perf.h)");
321 #endif /* (DEBUG || DEVELOPMENT) */
324 static int ipprintfs
= 0;
327 struct protosw
*ip_protox
[IPPROTO_MAX
];
329 static lck_grp_attr_t
*in_ifaddr_rwlock_grp_attr
;
330 static lck_grp_t
*in_ifaddr_rwlock_grp
;
331 static lck_attr_t
*in_ifaddr_rwlock_attr
;
332 decl_lck_rw_data(, in_ifaddr_rwlock_data
);
333 lck_rw_t
*in_ifaddr_rwlock
= &in_ifaddr_rwlock_data
;
335 /* Protected by in_ifaddr_rwlock */
336 struct in_ifaddrhead in_ifaddrhead
; /* first inet address */
337 struct in_ifaddrhashhead
*in_ifaddrhashtbl
; /* inet addr hash table */
339 #define INADDR_NHASH 61
340 static u_int32_t inaddr_nhash
; /* hash table size */
341 static u_int32_t inaddr_hashp
; /* next largest prime */
343 static int ip_getstat SYSCTL_HANDLER_ARGS
;
344 struct ipstat ipstat
;
345 SYSCTL_PROC(_net_inet_ip
, IPCTL_STATS
, stats
,
346 CTLTYPE_STRUCT
| CTLFLAG_RD
| CTLFLAG_LOCKED
,
347 0, 0, ip_getstat
, "S,ipstat",
348 "IP statistics (struct ipstat, netinet/ip_var.h)");
351 SYSCTL_INT(_net_inet_ip
, IPCTL_DEFMTU
, mtu
, CTLFLAG_RW
| CTLFLAG_LOCKED
,
352 &ip_mtu
, 0, "Default MTU");
353 #endif /* IPCTL_DEFMTU */
356 static int ipstealth
= 0;
357 SYSCTL_INT(_net_inet_ip
, OID_AUTO
, stealth
, CTLFLAG_RW
| CTLFLAG_LOCKED
,
359 #endif /* IPSTEALTH */
362 ip_dn_io_t
*ip_dn_io_ptr
;
363 #endif /* DUMMYNET */
365 SYSCTL_NODE(_net_inet_ip
, OID_AUTO
, linklocal
,
366 CTLFLAG_RW
| CTLFLAG_LOCKED
, 0, "link local");
368 struct ip_linklocal_stat ip_linklocal_stat
;
369 SYSCTL_STRUCT(_net_inet_ip_linklocal
, OID_AUTO
, stat
,
370 CTLFLAG_RD
| CTLFLAG_LOCKED
, &ip_linklocal_stat
, ip_linklocal_stat
,
371 "Number of link local packets with TTL less than 255");
373 SYSCTL_NODE(_net_inet_ip_linklocal
, OID_AUTO
, in
,
374 CTLFLAG_RW
| CTLFLAG_LOCKED
, 0, "link local input");
376 int ip_linklocal_in_allowbadttl
= 1;
377 SYSCTL_INT(_net_inet_ip_linklocal_in
, OID_AUTO
, allowbadttl
,
378 CTLFLAG_RW
| CTLFLAG_LOCKED
, &ip_linklocal_in_allowbadttl
, 0,
379 "Allow incoming link local packets with TTL less than 255");
383 * We need to save the IP options in case a protocol wants to respond
384 * to an incoming packet over the same route if the packet got here
385 * using IP source routing. This allows connection establishment and
386 * maintenance when the remote end is on a network that is not known
389 static int ip_nhops
= 0;
390 static struct ip_srcrt
{
391 struct in_addr dst
; /* final destination */
392 char nop
; /* one NOP to align */
393 char srcopt
[IPOPT_OFFSET
+ 1]; /* OPTVAL, OLEN and OFFSET */
394 struct in_addr route
[MAX_IPOPTLEN
/ sizeof(struct in_addr
)];
397 static void in_ifaddrhashtbl_init(void);
398 static void save_rte(u_char
*, struct in_addr
);
399 static int ip_dooptions(struct mbuf
*, int, struct sockaddr_in
*);
400 static void ip_forward(struct mbuf
*, int, struct sockaddr_in
*);
401 static void frag_freef(struct ipqhead
*, struct ipq
*);
402 static struct mbuf
*ip_reass(struct mbuf
*);
403 static void ip_fwd_route_copyout(struct ifnet
*, struct route
*);
404 static void ip_fwd_route_copyin(struct ifnet
*, struct route
*);
405 static inline u_short
ip_cksum(struct mbuf
*, int);
407 int ip_use_randomid
= 1;
408 SYSCTL_INT(_net_inet_ip
, OID_AUTO
, random_id
, CTLFLAG_RW
| CTLFLAG_LOCKED
,
409 &ip_use_randomid
, 0, "Randomize IP packets IDs");
412 * On platforms which require strict alignment (currently for anything but
413 * i386 or x86_64), check if the IP header pointer is 32-bit aligned; if not,
414 * copy the contents of the mbuf chain into a new chain, and free the original
415 * one. Create some head room in the first mbuf of the new chain, in case
416 * it's needed later on.
418 #if defined(__i386__) || defined(__x86_64__)
419 #define IP_HDR_ALIGNMENT_FIXUP(_m, _ifp, _action) do { } while (0)
420 #else /* !__i386__ && !__x86_64__ */
421 #define IP_HDR_ALIGNMENT_FIXUP(_m, _ifp, _action) do { \
422 if (!IP_HDR_ALIGNED_P(mtod(_m, caddr_t))) { \
424 struct ifnet *__ifp = (_ifp); \
425 atomic_add_64(&(__ifp)->if_alignerrs, 1); \
426 if (((_m)->m_flags & M_PKTHDR) && \
427 (_m)->m_pkthdr.pkt_hdr != NULL) \
428 (_m)->m_pkthdr.pkt_hdr = NULL; \
429 _n = m_defrag_offset(_m, max_linkhdr, M_NOWAIT); \
431 atomic_add_32(&ipstat.ips_toosmall, 1); \
436 VERIFY(_n != (_m)); \
441 #endif /* !__i386__ && !__x86_64__ */
444 typedef enum ip_check_if_result
{
445 IP_CHECK_IF_NONE
= 0,
446 IP_CHECK_IF_OURS
= 1,
447 IP_CHECK_IF_DROP
= 2,
448 IP_CHECK_IF_FORWARD
= 3
449 } ip_check_if_result_t
;
451 static ip_check_if_result_t
ip_input_check_interface(struct mbuf
**, struct ip
*, struct ifnet
*);
454 * GRE input handler function, settable via ip_gre_register_input() for PPTP.
456 static gre_input_func_t gre_input_func
;
459 ip_init_delayed(void)
463 struct sockaddr_in
*sin
;
465 bzero(&ifr
, sizeof(ifr
));
466 strlcpy(ifr
.ifr_name
, "lo0", sizeof(ifr
.ifr_name
));
467 sin
= (struct sockaddr_in
*)(void *)&ifr
.ifr_addr
;
468 sin
->sin_len
= sizeof(struct sockaddr_in
);
469 sin
->sin_family
= AF_INET
;
470 sin
->sin_addr
.s_addr
= htonl(INADDR_LOOPBACK
);
471 error
= in_control(NULL
, SIOCSIFADDR
, (caddr_t
)&ifr
, lo_ifp
, kernproc
);
473 printf("%s: failed to initialise lo0's address, error=%d\n",
479 * IP initialization: fill in IP protocol switch table.
480 * All protocols not implemented in kernel go to raw IP protocol handler.
483 ip_init(struct protosw
*pp
, struct domain
*dp
)
485 static int ip_initialized
= 0;
490 domain_proto_mtx_lock_assert_held();
491 VERIFY((pp
->pr_flags
& (PR_INITIALIZED
| PR_ATTACHED
)) == PR_ATTACHED
);
493 /* ipq_alloc() uses mbufs for IP fragment queue structures */
494 _CASSERT(sizeof(struct ipq
) <= _MLEN
);
497 * Some ioctls (e.g. SIOCAIFADDR) use ifaliasreq struct, which is
498 * interchangeable with in_aliasreq; they must have the same size.
500 _CASSERT(sizeof(struct ifaliasreq
) == sizeof(struct in_aliasreq
));
502 if (ip_initialized
) {
509 in_ifaddr_rwlock_grp_attr
= lck_grp_attr_alloc_init();
510 in_ifaddr_rwlock_grp
= lck_grp_alloc_init("in_ifaddr_rwlock",
511 in_ifaddr_rwlock_grp_attr
);
512 in_ifaddr_rwlock_attr
= lck_attr_alloc_init();
513 lck_rw_init(in_ifaddr_rwlock
, in_ifaddr_rwlock_grp
,
514 in_ifaddr_rwlock_attr
);
516 TAILQ_INIT(&in_ifaddrhead
);
517 in_ifaddrhashtbl_init();
521 pr
= pffindproto_locked(PF_INET
, IPPROTO_RAW
, SOCK_RAW
);
523 panic("%s: Unable to find [PF_INET,IPPROTO_RAW,SOCK_RAW]\n",
528 /* Initialize the entire ip_protox[] array to IPPROTO_RAW. */
529 for (i
= 0; i
< IPPROTO_MAX
; i
++) {
533 * Cycle through IP protocols and put them into the appropriate place
534 * in ip_protox[], skipping protocols IPPROTO_{IP,RAW}.
536 VERIFY(dp
== inetdomain
&& dp
->dom_family
== PF_INET
);
537 TAILQ_FOREACH(pr
, &dp
->dom_protosw
, pr_entry
) {
538 VERIFY(pr
->pr_domain
== dp
);
539 if (pr
->pr_protocol
!= 0 && pr
->pr_protocol
!= IPPROTO_RAW
) {
540 /* Be careful to only index valid IP protocols. */
541 if (pr
->pr_protocol
< IPPROTO_MAX
) {
542 ip_protox
[pr
->pr_protocol
] = pr
;
547 /* IP fragment reassembly queue lock */
548 ipqlock_grp_attr
= lck_grp_attr_alloc_init();
549 ipqlock_grp
= lck_grp_alloc_init("ipqlock", ipqlock_grp_attr
);
550 ipqlock_attr
= lck_attr_alloc_init();
551 lck_mtx_init(&ipqlock
, ipqlock_grp
, ipqlock_attr
);
553 lck_mtx_lock(&ipqlock
);
554 /* Initialize IP reassembly queue. */
555 for (i
= 0; i
< IPREASS_NHASH
; i
++) {
559 maxnipq
= nmbclusters
/ 32;
560 maxfragsperpacket
= 128; /* enough for 64k in 512 byte fragments */
562 lck_mtx_unlock(&ipqlock
);
565 ip_id
= RandomULong() ^ tv
.tv_usec
;
570 PE_parse_boot_argn("ip_checkinterface", &i
, sizeof(i
));
572 case IP_CHECKINTERFACE_WEAK_ES
:
573 case IP_CHECKINTERFACE_HYBRID_ES
:
574 case IP_CHECKINTERFACE_STRONG_ES
:
575 ip_checkinterface
= i
;
582 sadb_stat_mutex_grp_attr
= lck_grp_attr_alloc_init();
583 sadb_stat_mutex_grp
= lck_grp_alloc_init("sadb_stat",
584 sadb_stat_mutex_grp_attr
);
585 sadb_stat_mutex_attr
= lck_attr_alloc_init();
586 lck_mtx_init(sadb_stat_mutex
, sadb_stat_mutex_grp
,
587 sadb_stat_mutex_attr
);
591 net_init_add(ip_init_delayed
);
595 * Initialize IPv4 source address hash table.
598 in_ifaddrhashtbl_init(void)
602 if (in_ifaddrhashtbl
!= NULL
) {
606 PE_parse_boot_argn("inaddr_nhash", &inaddr_nhash
,
607 sizeof(inaddr_nhash
));
608 if (inaddr_nhash
== 0) {
609 inaddr_nhash
= INADDR_NHASH
;
612 MALLOC(in_ifaddrhashtbl
, struct in_ifaddrhashhead
*,
613 inaddr_nhash
* sizeof(*in_ifaddrhashtbl
),
614 M_IFADDR
, M_WAITOK
| M_ZERO
);
615 if (in_ifaddrhashtbl
== NULL
) {
616 panic("in_ifaddrhashtbl_init allocation failed");
620 * Generate the next largest prime greater than inaddr_nhash.
622 k
= (inaddr_nhash
% 2 == 0) ? inaddr_nhash
+ 1 : inaddr_nhash
+ 2;
625 for (i
= 3; i
* i
<= k
; i
+= 2) {
639 inaddr_hashval(u_int32_t key
)
642 * The hash index is the computed prime times the key modulo
643 * the hash size, as documented in "Introduction to Algorithms"
644 * (Cormen, Leiserson, Rivest).
646 if (inaddr_nhash
> 1) {
647 return (key
* inaddr_hashp
) % inaddr_nhash
;
653 __private_extern__
void
654 ip_proto_dispatch_in(struct mbuf
*m
, int hlen
, u_int8_t proto
,
655 ipfilter_t inject_ipfref
)
657 struct ipfilter
*filter
;
658 int seen
= (inject_ipfref
== NULL
);
659 int changed_header
= 0;
661 void (*pr_input
)(struct mbuf
*, int len
);
663 if (!TAILQ_EMPTY(&ipv4_filters
)) {
665 TAILQ_FOREACH(filter
, &ipv4_filters
, ipf_link
) {
667 if ((struct ipfilter
*)inject_ipfref
== filter
) {
670 } else if (filter
->ipf_filter
.ipf_input
) {
673 if (changed_header
== 0) {
675 * Perform IP header alignment fixup,
676 * if needed, before passing packet
679 IP_HDR_ALIGNMENT_FIXUP(m
,
680 m
->m_pkthdr
.rcvif
, ipf_unref());
682 /* ipf_unref() already called */
688 ip
= mtod(m
, struct ip
*);
689 ip
->ip_len
= htons(ip
->ip_len
+ hlen
);
690 ip
->ip_off
= htons(ip
->ip_off
);
692 ip
->ip_sum
= ip_cksum_hdr_in(m
, hlen
);
694 result
= filter
->ipf_filter
.ipf_input(
695 filter
->ipf_filter
.cookie
, (mbuf_t
*)&m
,
697 if (result
== EJUSTRETURN
) {
711 /* Perform IP header alignment fixup (post-filters), if needed */
712 IP_HDR_ALIGNMENT_FIXUP(m
, m
->m_pkthdr
.rcvif
, return );
714 ip
= mtod(m
, struct ip
*);
716 if (changed_header
) {
717 ip
->ip_len
= ntohs(ip
->ip_len
) - hlen
;
718 ip
->ip_off
= ntohs(ip
->ip_off
);
722 * If there isn't a specific lock for the protocol
723 * we're about to call, use the generic lock for AF_INET.
724 * otherwise let the protocol deal with its own locking
726 if ((pr_input
= ip_protox
[ip
->ip_p
]->pr_input
) == NULL
) {
728 } else if (!(ip_protox
[ip
->ip_p
]->pr_flags
& PR_PROTOLOCK
)) {
729 lck_mtx_lock(inet_domain_mutex
);
731 lck_mtx_unlock(inet_domain_mutex
);
737 struct pktchain_elm
{
738 struct mbuf
*pkte_head
;
739 struct mbuf
*pkte_tail
;
740 struct in_addr pkte_saddr
;
741 struct in_addr pkte_daddr
;
744 uint32_t pkte_nbytes
;
747 typedef struct pktchain_elm pktchain_elm_t
;
749 /* Store upto PKTTBL_SZ unique flows on the stack */
753 ip_chain_insert(struct mbuf
*packet
, pktchain_elm_t
*tbl
)
758 ip
= mtod(packet
, struct ip
*);
760 /* reusing the hash function from inaddr_hashval */
761 pkttbl_idx
= inaddr_hashval(ntohs(ip
->ip_src
.s_addr
)) % PKTTBL_SZ
;
762 if (tbl
[pkttbl_idx
].pkte_head
== NULL
) {
763 tbl
[pkttbl_idx
].pkte_head
= packet
;
764 tbl
[pkttbl_idx
].pkte_saddr
.s_addr
= ip
->ip_src
.s_addr
;
765 tbl
[pkttbl_idx
].pkte_daddr
.s_addr
= ip
->ip_dst
.s_addr
;
766 tbl
[pkttbl_idx
].pkte_proto
= ip
->ip_p
;
768 if ((ip
->ip_dst
.s_addr
== tbl
[pkttbl_idx
].pkte_daddr
.s_addr
) &&
769 (ip
->ip_src
.s_addr
== tbl
[pkttbl_idx
].pkte_saddr
.s_addr
) &&
770 (ip
->ip_p
== tbl
[pkttbl_idx
].pkte_proto
)) {
775 if (tbl
[pkttbl_idx
].pkte_tail
!= NULL
) {
776 mbuf_setnextpkt(tbl
[pkttbl_idx
].pkte_tail
, packet
);
779 tbl
[pkttbl_idx
].pkte_tail
= packet
;
780 tbl
[pkttbl_idx
].pkte_npkts
+= 1;
781 tbl
[pkttbl_idx
].pkte_nbytes
+= packet
->m_pkthdr
.len
;
785 /* args is a dummy variable here for backward compatibility */
787 ip_input_second_pass_loop_tbl(pktchain_elm_t
*tbl
, struct ip_fw_in_args
*args
)
791 for (i
= 0; i
< PKTTBL_SZ
; i
++) {
792 if (tbl
[i
].pkte_head
!= NULL
) {
793 struct mbuf
*m
= tbl
[i
].pkte_head
;
794 ip_input_second_pass(m
, m
->m_pkthdr
.rcvif
,
795 tbl
[i
].pkte_npkts
, tbl
[i
].pkte_nbytes
, args
);
797 if (tbl
[i
].pkte_npkts
> 2) {
798 ipstat
.ips_rxc_chainsz_gt2
++;
800 if (tbl
[i
].pkte_npkts
> 4) {
801 ipstat
.ips_rxc_chainsz_gt4
++;
803 #if (DEBUG || DEVELOPMENT)
804 if (ip_input_measure
) {
805 net_perf_histogram(&net_perf
, tbl
[i
].pkte_npkts
);
807 #endif /* (DEBUG || DEVELOPMENT) */
808 tbl
[i
].pkte_head
= tbl
[i
].pkte_tail
= NULL
;
809 tbl
[i
].pkte_npkts
= 0;
810 tbl
[i
].pkte_nbytes
= 0;
811 /* no need to initialize address and protocol in tbl */
817 ip_input_cpout_args(struct ip_fw_in_args
*args
, struct ip_fw_args
*args1
,
818 boolean_t
*done_init
)
820 if (*done_init
== FALSE
) {
821 bzero(args1
, sizeof(struct ip_fw_args
));
824 args1
->fwa_pf_rule
= args
->fwai_pf_rule
;
828 ip_input_cpin_args(struct ip_fw_args
*args1
, struct ip_fw_in_args
*args
)
830 args
->fwai_pf_rule
= args1
->fwa_pf_rule
;
838 } ipinput_chain_ret_t
;
841 ip_input_update_nstat(struct ifnet
*ifp
, struct in_addr src_ip
,
842 u_int32_t packets
, u_int32_t bytes
)
845 struct rtentry
*rt
= ifnet_cached_rtlookup_inet(ifp
,
848 nstat_route_rx(rt
, packets
, bytes
, 0);
855 ip_input_dispatch_chain(struct mbuf
*m
)
857 struct mbuf
*tmp_mbuf
= m
;
858 struct mbuf
*nxt_mbuf
= NULL
;
859 struct ip
*ip
= NULL
;
862 ip
= mtod(tmp_mbuf
, struct ip
*);
863 hlen
= IP_VHL_HL(ip
->ip_vhl
) << 2;
864 while (tmp_mbuf
!= NULL
) {
865 nxt_mbuf
= mbuf_nextpkt(tmp_mbuf
);
866 mbuf_setnextpkt(tmp_mbuf
, NULL
);
867 ip_proto_dispatch_in(tmp_mbuf
, hlen
, ip
->ip_p
, 0);
870 ip
= mtod(tmp_mbuf
, struct ip
*);
871 /* first mbuf of chain already has adjusted ip_len */
872 hlen
= IP_VHL_HL(ip
->ip_vhl
) << 2;
879 ip_input_setdst_chain(struct mbuf
*m
, uint32_t ifindex
, struct in_ifaddr
*ia
)
881 struct mbuf
*tmp_mbuf
= m
;
883 while (tmp_mbuf
!= NULL
) {
884 ip_setdstifaddr_info(tmp_mbuf
, ifindex
, ia
);
885 tmp_mbuf
= mbuf_nextpkt(tmp_mbuf
);
890 ip_input_adjust(struct mbuf
*m
, struct ip
*ip
, struct ifnet
*inifp
)
892 boolean_t adjust
= TRUE
;
894 ASSERT(m_pktlen(m
) > ip
->ip_len
);
897 * Invalidate hardware checksum info if ip_adj_clear_hwcksum
898 * is set; useful to handle buggy drivers. Note that this
899 * should not be enabled by default, as we may get here due
900 * to link-layer padding.
902 if (ip_adj_clear_hwcksum
&&
903 (m
->m_pkthdr
.csum_flags
& CSUM_DATA_VALID
) &&
904 !(inifp
->if_flags
& IFF_LOOPBACK
) &&
905 !(m
->m_pkthdr
.pkt_flags
& PKTF_LOOP
)) {
906 m
->m_pkthdr
.csum_flags
&= ~CSUM_DATA_VALID
;
907 m
->m_pkthdr
.csum_data
= 0;
908 ipstat
.ips_adj_hwcsum_clr
++;
912 * If partial checksum information is available, subtract
913 * out the partial sum of postpended extraneous bytes, and
914 * update the checksum metadata accordingly. By doing it
915 * here, the upper layer transport only needs to adjust any
916 * prepended extraneous bytes (else it will do both.)
918 if (ip_adj_partial_sum
&&
919 (m
->m_pkthdr
.csum_flags
& (CSUM_DATA_VALID
| CSUM_PARTIAL
)) ==
920 (CSUM_DATA_VALID
| CSUM_PARTIAL
)) {
921 m
->m_pkthdr
.csum_rx_val
= m_adj_sum16(m
,
922 m
->m_pkthdr
.csum_rx_start
, m
->m_pkthdr
.csum_rx_start
,
923 (ip
->ip_len
- m
->m_pkthdr
.csum_rx_start
),
924 m
->m_pkthdr
.csum_rx_val
);
925 } else if ((m
->m_pkthdr
.csum_flags
&
926 (CSUM_DATA_VALID
| CSUM_PARTIAL
)) ==
927 (CSUM_DATA_VALID
| CSUM_PARTIAL
)) {
929 * If packet has partial checksum info and we decided not
930 * to subtract the partial sum of postpended extraneous
931 * bytes here (not the default case), leave that work to
932 * be handled by the other layers. For now, only TCP, UDP
933 * layers are capable of dealing with this. For all other
934 * protocols (including fragments), trim and ditch the
935 * partial sum as those layers might not implement partial
936 * checksumming (or adjustment) at all.
938 if ((ip
->ip_off
& (IP_MF
| IP_OFFMASK
)) == 0 &&
939 (ip
->ip_p
== IPPROTO_TCP
|| ip
->ip_p
== IPPROTO_UDP
)) {
942 m
->m_pkthdr
.csum_flags
&= ~CSUM_DATA_VALID
;
943 m
->m_pkthdr
.csum_data
= 0;
944 ipstat
.ips_adj_hwcsum_clr
++;
950 if (m
->m_len
== m
->m_pkthdr
.len
) {
951 m
->m_len
= ip
->ip_len
;
952 m
->m_pkthdr
.len
= ip
->ip_len
;
954 m_adj(m
, ip
->ip_len
- m
->m_pkthdr
.len
);
960 * First pass does all essential packet validation and places on a per flow
961 * queue for doing operations that have same outcome for all packets of a flow.
963 static ipinput_chain_ret_t
964 ip_input_first_pass(struct mbuf
*m
, struct ip_fw_in_args
*args
, struct mbuf
**modm
)
969 int retval
= IPINPUT_DOCHAIN
;
971 struct in_addr src_ip
;
975 boolean_t
delete = FALSE
;
976 struct ip_fw_args args1
;
977 boolean_t init
= FALSE
;
978 #endif /* DUMMYNET */
979 ipfilter_t inject_filter_ref
= NULL
;
981 /* Check if the mbuf is still valid after interface filter processing */
982 MBUF_INPUT_CHECK(m
, m
->m_pkthdr
.rcvif
);
983 inifp
= mbuf_pkthdr_rcvif(m
);
984 VERIFY(inifp
!= NULL
);
986 /* Perform IP header alignment fixup, if needed */
987 IP_HDR_ALIGNMENT_FIXUP(m
, inifp
, goto bad
);
989 m
->m_pkthdr
.pkt_flags
&= ~PKTF_FORWARDED
;
993 * Don't bother searching for tag(s) if there's none.
995 if (SLIST_EMPTY(&m
->m_pkthdr
.tags
)) {
999 /* Grab info from mtags prepended to the chain */
1002 if (p
->m_tag_id
== KERNEL_MODULE_TAG_ID
) {
1003 if (p
->m_tag_type
== KERNEL_TAG_TYPE_DUMMYNET
) {
1004 struct dn_pkt_tag
*dn_tag
;
1006 dn_tag
= (struct dn_pkt_tag
*)(p
+ 1);
1007 args
->fwai_pf_rule
= dn_tag
->dn_pf_rule
;
1013 p
= m_tag_next(m
, p
);
1014 m_tag_delete(m
, copy
);
1016 p
= m_tag_next(m
, p
);
1019 p
= m_tag_next(m
, p
);
1024 if (m
== NULL
|| !(m
->m_flags
& M_PKTHDR
)) {
1025 panic("ip_input no HDR");
1029 if (args
->fwai_pf_rule
) {
1030 /* dummynet already filtered us */
1031 ip
= mtod(m
, struct ip
*);
1032 hlen
= IP_VHL_HL(ip
->ip_vhl
) << 2;
1033 inject_filter_ref
= ipf_get_inject_filter(m
);
1034 if (args
->fwai_pf_rule
) {
1039 #endif /* DUMMYNET */
1042 * No need to process packet twice if we've already seen it.
1044 if (!SLIST_EMPTY(&m
->m_pkthdr
.tags
)) {
1045 inject_filter_ref
= ipf_get_inject_filter(m
);
1047 if (inject_filter_ref
!= NULL
) {
1048 ip
= mtod(m
, struct ip
*);
1049 hlen
= IP_VHL_HL(ip
->ip_vhl
) << 2;
1051 DTRACE_IP6(receive
, struct mbuf
*, m
, struct inpcb
*, NULL
,
1052 struct ip
*, ip
, struct ifnet
*, inifp
,
1053 struct ip
*, ip
, struct ip6_hdr
*, NULL
);
1055 ip
->ip_len
= ntohs(ip
->ip_len
) - hlen
;
1056 ip
->ip_off
= ntohs(ip
->ip_off
);
1057 ip_proto_dispatch_in(m
, hlen
, ip
->ip_p
, inject_filter_ref
);
1058 return IPINPUT_DONE
;
1061 if (m
->m_pkthdr
.len
< sizeof(struct ip
)) {
1062 OSAddAtomic(1, &ipstat
.ips_total
);
1063 OSAddAtomic(1, &ipstat
.ips_tooshort
);
1065 return IPINPUT_FREED
;
1068 if (m
->m_len
< sizeof(struct ip
) &&
1069 (m
= m_pullup(m
, sizeof(struct ip
))) == NULL
) {
1070 OSAddAtomic(1, &ipstat
.ips_total
);
1071 OSAddAtomic(1, &ipstat
.ips_toosmall
);
1072 return IPINPUT_FREED
;
1075 ip
= mtod(m
, struct ip
*);
1078 KERNEL_DEBUG(DBG_LAYER_BEG
, ip
->ip_dst
.s_addr
, ip
->ip_src
.s_addr
,
1079 ip
->ip_p
, ip
->ip_off
, ip
->ip_len
);
1081 if (IP_VHL_V(ip
->ip_vhl
) != IPVERSION
) {
1082 OSAddAtomic(1, &ipstat
.ips_total
);
1083 OSAddAtomic(1, &ipstat
.ips_badvers
);
1084 KERNEL_DEBUG(DBG_LAYER_END
, 0, 0, 0, 0, 0);
1086 return IPINPUT_FREED
;
1089 hlen
= IP_VHL_HL(ip
->ip_vhl
) << 2;
1090 if (hlen
< sizeof(struct ip
)) {
1091 OSAddAtomic(1, &ipstat
.ips_total
);
1092 OSAddAtomic(1, &ipstat
.ips_badhlen
);
1093 KERNEL_DEBUG(DBG_LAYER_END
, 0, 0, 0, 0, 0);
1095 return IPINPUT_FREED
;
1098 if (hlen
> m
->m_len
) {
1099 if ((m
= m_pullup(m
, hlen
)) == NULL
) {
1100 OSAddAtomic(1, &ipstat
.ips_total
);
1101 OSAddAtomic(1, &ipstat
.ips_badhlen
);
1102 KERNEL_DEBUG(DBG_LAYER_END
, 0, 0, 0, 0, 0);
1103 return IPINPUT_FREED
;
1105 ip
= mtod(m
, struct ip
*);
1109 /* 127/8 must not appear on wire - RFC1122 */
1110 if ((ntohl(ip
->ip_dst
.s_addr
) >> IN_CLASSA_NSHIFT
) == IN_LOOPBACKNET
||
1111 (ntohl(ip
->ip_src
.s_addr
) >> IN_CLASSA_NSHIFT
) == IN_LOOPBACKNET
) {
1113 * Allow for the following exceptions:
1115 * 1. If the packet was sent to loopback (i.e. rcvif
1116 * would have been set earlier at output time.)
1118 * 2. If the packet was sent out on loopback from a local
1119 * source address which belongs to a non-loopback
1120 * interface (i.e. rcvif may not necessarily be a
1121 * loopback interface, hence the test for PKTF_LOOP.)
1122 * Unlike IPv6, there is no interface scope ID, and
1123 * therefore we don't care so much about PKTF_IFINFO.
1125 if (!(inifp
->if_flags
& IFF_LOOPBACK
) &&
1126 !(m
->m_pkthdr
.pkt_flags
& PKTF_LOOP
)) {
1127 OSAddAtomic(1, &ipstat
.ips_total
);
1128 OSAddAtomic(1, &ipstat
.ips_badaddr
);
1129 KERNEL_DEBUG(DBG_LAYER_END
, 0, 0, 0, 0, 0);
1131 return IPINPUT_FREED
;
1135 /* IPv4 Link-Local Addresses as defined in RFC3927 */
1136 if ((IN_LINKLOCAL(ntohl(ip
->ip_dst
.s_addr
)) ||
1137 IN_LINKLOCAL(ntohl(ip
->ip_src
.s_addr
)))) {
1138 ip_linklocal_stat
.iplls_in_total
++;
1139 if (ip
->ip_ttl
!= MAXTTL
) {
1140 OSAddAtomic(1, &ip_linklocal_stat
.iplls_in_badttl
);
1141 /* Silently drop link local traffic with bad TTL */
1142 if (!ip_linklocal_in_allowbadttl
) {
1143 OSAddAtomic(1, &ipstat
.ips_total
);
1144 KERNEL_DEBUG(DBG_LAYER_END
, 0, 0, 0, 0, 0);
1146 return IPINPUT_FREED
;
1151 if (ip_cksum(m
, hlen
)) {
1152 OSAddAtomic(1, &ipstat
.ips_total
);
1153 KERNEL_DEBUG(DBG_LAYER_END
, 0, 0, 0, 0, 0);
1155 return IPINPUT_FREED
;
1158 DTRACE_IP6(receive
, struct mbuf
*, m
, struct inpcb
*, NULL
,
1159 struct ip
*, ip
, struct ifnet
*, inifp
,
1160 struct ip
*, ip
, struct ip6_hdr
*, NULL
);
1163 * Convert fields to host representation.
1165 #if BYTE_ORDER != BIG_ENDIAN
1169 if (ip
->ip_len
< hlen
) {
1170 OSAddAtomic(1, &ipstat
.ips_total
);
1171 OSAddAtomic(1, &ipstat
.ips_badlen
);
1172 KERNEL_DEBUG(DBG_LAYER_END
, 0, 0, 0, 0, 0);
1174 return IPINPUT_FREED
;
1177 #if BYTE_ORDER != BIG_ENDIAN
1182 * Check that the amount of data in the buffers
1183 * is as at least much as the IP header would have us expect.
1184 * Trim mbufs if longer than we expect.
1185 * Drop packet if shorter than we expect.
1187 if (m
->m_pkthdr
.len
< ip
->ip_len
) {
1188 OSAddAtomic(1, &ipstat
.ips_total
);
1189 OSAddAtomic(1, &ipstat
.ips_tooshort
);
1190 KERNEL_DEBUG(DBG_LAYER_END
, 0, 0, 0, 0, 0);
1192 return IPINPUT_FREED
;
1195 if (m
->m_pkthdr
.len
> ip
->ip_len
) {
1196 ip_input_adjust(m
, ip
, inifp
);
1199 /* for netstat route statistics */
1200 src_ip
= ip
->ip_src
;
1201 len
= m
->m_pkthdr
.len
;
1205 #endif /* DUMMYNET */
1207 /* Invoke inbound packet filter */
1208 if (PF_IS_ENABLED
) {
1210 ip_input_cpout_args(args
, &args1
, &init
);
1211 ip
= mtod(m
, struct ip
*);
1212 src_ip
= ip
->ip_src
;
1215 error
= pf_af_hook(inifp
, NULL
, &m
, AF_INET
, TRUE
, &args1
);
1217 error
= pf_af_hook(inifp
, NULL
, &m
, AF_INET
, TRUE
, NULL
);
1218 #endif /* DUMMYNET */
1219 if (error
!= 0 || m
== NULL
) {
1221 panic("%s: unexpected packet %p\n",
1225 /* Already freed by callee */
1226 ip_input_update_nstat(inifp
, src_ip
, 1, len
);
1227 KERNEL_DEBUG(DBG_LAYER_END
, 0, 0, 0, 0, 0);
1228 OSAddAtomic(1, &ipstat
.ips_total
);
1229 return IPINPUT_FREED
;
1231 ip
= mtod(m
, struct ip
*);
1232 hlen
= IP_VHL_HL(ip
->ip_vhl
) << 2;
1234 ip_input_cpin_args(&args1
, args
);
1239 if (ipsec_bypass
== 0 && ipsec_gethist(m
, NULL
)) {
1240 retval
= IPINPUT_DONTCHAIN
; /* XXX scope for chaining here? */
1249 * Process options and, if not destined for us,
1250 * ship it on. ip_dooptions returns 1 when an
1251 * error was detected (causing an icmp message
1252 * to be sent and the original packet to be freed).
1254 ip_nhops
= 0; /* for source routed packets */
1255 if (hlen
> sizeof(struct ip
) && ip_dooptions(m
, 0, NULL
)) {
1256 ip_input_update_nstat(inifp
, src_ip
, 1, len
);
1257 KERNEL_DEBUG(DBG_LAYER_END
, 0, 0, 0, 0, 0);
1258 OSAddAtomic(1, &ipstat
.ips_total
);
1259 return IPINPUT_FREED
;
1263 * Don't chain fragmented packets
1265 if (ip
->ip_off
& ~(IP_DF
| IP_RF
)) {
1266 return IPINPUT_DONTCHAIN
;
1269 /* Allow DHCP/BootP responses through */
1270 if ((inifp
->if_eflags
& IFEF_AUTOCONFIGURING
) &&
1271 hlen
== sizeof(struct ip
) && ip
->ip_p
== IPPROTO_UDP
) {
1272 struct udpiphdr
*ui
;
1274 if (m
->m_len
< sizeof(struct udpiphdr
) &&
1275 (m
= m_pullup(m
, sizeof(struct udpiphdr
))) == NULL
) {
1276 OSAddAtomic(1, &udpstat
.udps_hdrops
);
1277 KERNEL_DEBUG(DBG_LAYER_END
, 0, 0, 0, 0, 0);
1278 OSAddAtomic(1, &ipstat
.ips_total
);
1279 return IPINPUT_FREED
;
1282 ui
= mtod(m
, struct udpiphdr
*);
1283 if (ntohs(ui
->ui_dport
) == IPPORT_BOOTPC
) {
1284 ip_setdstifaddr_info(m
, inifp
->if_index
, NULL
);
1285 return IPINPUT_DONTCHAIN
;
1289 /* Avoid chaining raw sockets as ipsec checks occur later for them */
1290 if (ip_protox
[ip
->ip_p
]->pr_flags
& PR_LASTHDR
) {
1291 return IPINPUT_DONTCHAIN
;
1295 #if !defined(__i386__) && !defined(__x86_64__)
1298 return IPINPUT_FREED
;
1303 * Because the call to m_pullup() may freem the mbuf, the function frees the mbuf packet
1304 * chain before it return IP_CHECK_IF_DROP
1306 static ip_check_if_result_t
1307 ip_input_check_interface(struct mbuf
**mp
, struct ip
*ip
, struct ifnet
*inifp
)
1309 struct mbuf
*m
= *mp
;
1310 struct in_ifaddr
*ia
= NULL
;
1311 struct in_ifaddr
*best_ia
= NULL
;
1312 struct ifnet
*match_ifp
= NULL
;
1313 ip_check_if_result_t result
= IP_CHECK_IF_NONE
;
1316 * Host broadcast and all network broadcast addresses are always a match
1318 if (ip
->ip_dst
.s_addr
== (u_int32_t
)INADDR_BROADCAST
||
1319 ip
->ip_dst
.s_addr
== INADDR_ANY
) {
1320 ip_input_setdst_chain(m
, inifp
->if_index
, NULL
);
1321 return IP_CHECK_IF_OURS
;
1325 * Check for a match in the hash bucket.
1327 lck_rw_lock_shared(in_ifaddr_rwlock
);
1328 TAILQ_FOREACH(ia
, INADDR_HASH(ip
->ip_dst
.s_addr
), ia_hash
) {
1329 if (IA_SIN(ia
)->sin_addr
.s_addr
== ip
->ip_dst
.s_addr
) {
1331 match_ifp
= best_ia
->ia_ifp
;
1333 if (ia
->ia_ifp
== inifp
|| (inifp
->if_flags
& IFF_LOOPBACK
) ||
1334 (m
->m_pkthdr
.pkt_flags
& PKTF_LOOP
)) {
1336 * A locally originated packet or packet from the loopback
1337 * interface is always an exact interface address match
1343 * Continue the loop in case there's a exact match with another
1348 if (best_ia
!= NULL
) {
1349 if (match_ifp
!= inifp
&& ipforwarding
== 0 &&
1350 ((ip_checkinterface
== IP_CHECKINTERFACE_HYBRID_ES
&&
1351 (match_ifp
->if_family
== IFNET_FAMILY_IPSEC
||
1352 match_ifp
->if_family
== IFNET_FAMILY_UTUN
)) ||
1353 ip_checkinterface
== IP_CHECKINTERFACE_STRONG_ES
)) {
1355 * Drop when interface address check is strict and forwarding
1358 result
= IP_CHECK_IF_DROP
;
1360 result
= IP_CHECK_IF_OURS
;
1361 ip_input_setdst_chain(m
, 0, best_ia
);
1364 lck_rw_done(in_ifaddr_rwlock
);
1366 if (result
== IP_CHECK_IF_NONE
&& (inifp
->if_flags
& IFF_BROADCAST
)) {
1368 * Check for broadcast addresses.
1370 * Only accept broadcast packets that arrive via the matching
1371 * interface. Reception of forwarded directed broadcasts would be
1372 * handled via ip_forward() and ether_frameout() with the loopback
1373 * into the stack for SIMPLEX interfaces handled by ether_frameout().
1377 ifnet_lock_shared(inifp
);
1378 TAILQ_FOREACH(ifa
, &inifp
->if_addrhead
, ifa_link
) {
1379 if (ifa
->ifa_addr
->sa_family
!= AF_INET
) {
1383 if (satosin(&ia
->ia_broadaddr
)->sin_addr
.s_addr
== ip
->ip_dst
.s_addr
||
1384 ia
->ia_netbroadcast
.s_addr
== ip
->ip_dst
.s_addr
) {
1385 ip_input_setdst_chain(m
, 0, ia
);
1386 result
= IP_CHECK_IF_OURS
;
1391 ifnet_lock_done(inifp
);
1394 /* Allow DHCP/BootP responses through */
1395 if (result
== IP_CHECK_IF_NONE
&& (inifp
->if_eflags
& IFEF_AUTOCONFIGURING
) &&
1396 ip
->ip_p
== IPPROTO_UDP
&& (IP_VHL_HL(ip
->ip_vhl
) << 2) == sizeof(struct ip
)) {
1397 struct udpiphdr
*ui
;
1399 if (m
->m_len
< sizeof(struct udpiphdr
)) {
1400 if ((m
= m_pullup(m
, sizeof(struct udpiphdr
))) == NULL
) {
1401 OSAddAtomic(1, &udpstat
.udps_hdrops
);
1403 return IP_CHECK_IF_DROP
;
1406 * m_pullup can return a different mbuf
1409 ip
= mtod(m
, struct ip
*);
1411 ui
= mtod(m
, struct udpiphdr
*);
1412 if (ntohs(ui
->ui_dport
) == IPPORT_BOOTPC
) {
1413 ASSERT(m
->m_nextpkt
== NULL
);
1414 ip_setdstifaddr_info(m
, inifp
->if_index
, NULL
);
1415 result
= IP_CHECK_IF_OURS
;
1420 if (result
== IP_CHECK_IF_NONE
) {
1421 if (ipforwarding
== 0) {
1422 result
= IP_CHECK_IF_DROP
;
1424 result
= IP_CHECK_IF_FORWARD
;
1425 ip_input_setdst_chain(m
, inifp
->if_index
, NULL
);
1429 if (result
== IP_CHECK_IF_OURS
&& match_ifp
!= inifp
) {
1430 ipstat
.ips_rcv_if_weak_match
++;
1432 /* Logging is too noisy when forwarding is enabled */
1433 if (ip_checkinterface_debug
!= 0 && ipforwarding
== 0) {
1434 char src_str
[MAX_IPv4_STR_LEN
];
1435 char dst_str
[MAX_IPv4_STR_LEN
];
1437 inet_ntop(AF_INET
, &ip
->ip_src
, src_str
, sizeof(src_str
));
1438 inet_ntop(AF_INET
, &ip
->ip_dst
, dst_str
, sizeof(dst_str
));
1439 os_log_info(OS_LOG_DEFAULT
,
1440 "%s: weak ES interface match to %s for packet from %s to %s proto %u received via %s",
1441 __func__
, best_ia
->ia_ifp
->if_xname
, src_str
, dst_str
, ip
->ip_p
, inifp
->if_xname
);
1443 } else if (result
== IP_CHECK_IF_DROP
) {
1444 if (ip_checkinterface_debug
> 0) {
1445 char src_str
[MAX_IPv4_STR_LEN
];
1446 char dst_str
[MAX_IPv4_STR_LEN
];
1448 inet_ntop(AF_INET
, &ip
->ip_src
, src_str
, sizeof(src_str
));
1449 inet_ntop(AF_INET
, &ip
->ip_dst
, dst_str
, sizeof(dst_str
));
1450 os_log(OS_LOG_DEFAULT
,
1451 "%s: no interface match for packet from %s to %s proto %u received via %s",
1452 __func__
, src_str
, dst_str
, ip
->ip_p
, inifp
->if_xname
);
1454 struct mbuf
*tmp_mbuf
= m
;
1455 while (tmp_mbuf
!= NULL
) {
1456 ipstat
.ips_rcv_if_no_match
++;
1457 tmp_mbuf
= tmp_mbuf
->m_nextpkt
;
1467 ip_input_second_pass(struct mbuf
*m
, struct ifnet
*inifp
,
1468 int npkts_in_chain
, int bytes_in_chain
, struct ip_fw_in_args
*args
)
1470 struct mbuf
*tmp_mbuf
= NULL
;
1473 #pragma unused (args)
1475 struct ip
*ip
= mtod(m
, struct ip
*);
1476 hlen
= IP_VHL_HL(ip
->ip_vhl
) << 2;
1478 OSAddAtomic(npkts_in_chain
, &ipstat
.ips_total
);
1481 * Naively assume we can attribute inbound data to the route we would
1482 * use to send to this destination. Asymmetric routing breaks this
1483 * assumption, but it still allows us to account for traffic from
1484 * a remote node in the routing table.
1485 * this has a very significant performance impact so we bypass
1486 * if nstat_collect is disabled. We may also bypass if the
1487 * protocol is tcp in the future because tcp will have a route that
1488 * we can use to attribute the data to. That does mean we would not
1489 * account for forwarded tcp traffic.
1491 ip_input_update_nstat(inifp
, ip
->ip_src
, npkts_in_chain
,
1495 * Check our list of addresses, to see if the packet is for us.
1496 * If we don't have any addresses, assume any unicast packet
1497 * we receive might be for us (and let the upper layers deal
1501 if (TAILQ_EMPTY(&in_ifaddrhead
)) {
1502 while (tmp_mbuf
!= NULL
) {
1503 if (!(tmp_mbuf
->m_flags
& (M_MCAST
| M_BCAST
))) {
1504 ip_setdstifaddr_info(tmp_mbuf
, inifp
->if_index
,
1507 tmp_mbuf
= mbuf_nextpkt(tmp_mbuf
);
1513 * Enable a consistency check between the destination address
1514 * and the arrival interface for a unicast packet (the RFC 1122
1515 * strong ES model) if IP forwarding is disabled and the packet
1516 * is not locally generated
1518 * XXX - Checking also should be disabled if the destination
1519 * address is ipnat'ed to a different interface.
1521 * XXX - Checking is incompatible with IP aliases added
1522 * to the loopback interface instead of the interface where
1523 * the packets are received.
1525 if (!IN_MULTICAST(ntohl(ip
->ip_dst
.s_addr
))) {
1526 ip_check_if_result_t ip_check_if_result
= IP_CHECK_IF_NONE
;
1528 ip_check_if_result
= ip_input_check_interface(&m
, ip
, inifp
);
1529 ASSERT(ip_check_if_result
!= IP_CHECK_IF_NONE
);
1530 if (ip_check_if_result
== IP_CHECK_IF_OURS
) {
1532 } else if (ip_check_if_result
== IP_CHECK_IF_DROP
) {
1536 struct in_multi
*inm
;
1538 * See if we belong to the destination multicast group on the
1539 * arrival interface.
1541 in_multihead_lock_shared();
1542 IN_LOOKUP_MULTI(&ip
->ip_dst
, inifp
, inm
);
1543 in_multihead_lock_done();
1545 OSAddAtomic(npkts_in_chain
, &ipstat
.ips_notmember
);
1547 KERNEL_DEBUG(DBG_LAYER_END
, 0, 0, 0, 0, 0);
1550 ip_input_setdst_chain(m
, inifp
->if_index
, NULL
);
1556 struct mbuf
*nxt_mbuf
= NULL
;
1557 while (tmp_mbuf
!= NULL
) {
1558 nxt_mbuf
= mbuf_nextpkt(tmp_mbuf
);
1560 * Not for us; forward if possible and desirable.
1562 mbuf_setnextpkt(tmp_mbuf
, NULL
);
1563 if (ipforwarding
== 0) {
1564 OSAddAtomic(1, &ipstat
.ips_cantforward
);
1567 ip_forward(tmp_mbuf
, 0, NULL
);
1569 tmp_mbuf
= nxt_mbuf
;
1571 KERNEL_DEBUG(DBG_LAYER_END
, 0, 0, 0, 0, 0);
1574 ip
= mtod(m
, struct ip
*); /* in case it changed */
1576 * If offset is set, must reassemble.
1578 if (ip
->ip_off
& ~(IP_DF
| IP_RF
)) {
1579 VERIFY(npkts_in_chain
== 1);
1584 ip
= mtod(m
, struct ip
*);
1585 /* Get the header length of the reassembled packet */
1586 hlen
= IP_VHL_HL(ip
->ip_vhl
) << 2;
1590 * Further protocols expect the packet length to be w/o the
1597 * enforce IPsec policy checking if we are seeing last header.
1598 * note that we do not visit this with protocols with pcb layer
1599 * code - like udp/tcp/raw ip.
1601 if (ipsec_bypass
== 0 && (ip_protox
[ip
->ip_p
]->pr_flags
& PR_LASTHDR
)) {
1602 VERIFY(npkts_in_chain
== 1);
1603 if (ipsec4_in_reject(m
, NULL
)) {
1604 IPSEC_STAT_INCREMENT(ipsecstat
.in_polvio
);
1611 * Switch out to protocol's input routine.
1613 OSAddAtomic(npkts_in_chain
, &ipstat
.ips_delivered
);
1615 ip_input_dispatch_chain(m
);
1617 KERNEL_DEBUG(DBG_LAYER_END
, 0, 0, 0, 0, 0);
1620 KERNEL_DEBUG(DBG_LAYER_END
, 0, 0, 0, 0, 0);
1625 ip_input_process_list(struct mbuf
*packet_list
)
1627 pktchain_elm_t pktchain_tbl
[PKTTBL_SZ
];
1629 struct mbuf
*packet
= NULL
;
1630 struct mbuf
*modm
= NULL
; /* modified mbuf */
1632 #if (DEBUG || DEVELOPMENT)
1633 struct timeval start_tv
;
1634 #endif /* (DEBUG || DEVELOPMENT) */
1637 struct ip_fw_in_args args
;
1639 if (ip_chaining
== 0) {
1640 struct mbuf
*m
= packet_list
;
1641 #if (DEBUG || DEVELOPMENT)
1642 if (ip_input_measure
) {
1643 net_perf_start_time(&net_perf
, &start_tv
);
1645 #endif /* (DEBUG || DEVELOPMENT) */
1648 packet_list
= mbuf_nextpkt(m
);
1649 mbuf_setnextpkt(m
, NULL
);
1654 #if (DEBUG || DEVELOPMENT)
1655 if (ip_input_measure
) {
1656 net_perf_measure_time(&net_perf
, &start_tv
, num_pkts
);
1658 #endif /* (DEBUG || DEVELOPMENT) */
1661 #if (DEBUG || DEVELOPMENT)
1662 if (ip_input_measure
) {
1663 net_perf_start_time(&net_perf
, &start_tv
);
1665 #endif /* (DEBUG || DEVELOPMENT) */
1667 bzero(&pktchain_tbl
, sizeof(pktchain_tbl
));
1668 restart_list_process
:
1670 for (packet
= packet_list
; packet
; packet
= packet_list
) {
1671 packet_list
= mbuf_nextpkt(packet
);
1672 mbuf_setnextpkt(packet
, NULL
);
1676 bzero(&args
, sizeof(args
));
1678 retval
= ip_input_first_pass(packet
, &args
, &modm
);
1680 if (retval
== IPINPUT_DOCHAIN
) {
1684 packet
= ip_chain_insert(packet
, &pktchain_tbl
[0]);
1685 if (packet
== NULL
) {
1686 ipstat
.ips_rxc_chained
++;
1688 if (chain
> ip_chainsz
) {
1692 ipstat
.ips_rxc_collisions
++;
1695 } else if (retval
== IPINPUT_DONTCHAIN
) {
1696 /* in order to preserve order, exit from chaining */
1700 ipstat
.ips_rxc_notchain
++;
1703 /* packet was freed or delivered, do nothing. */
1707 /* do second pass here for pktchain_tbl */
1709 ip_input_second_pass_loop_tbl(&pktchain_tbl
[0], &args
);
1714 * equivalent update in chaining case if performed in
1715 * ip_input_second_pass_loop_tbl().
1717 #if (DEBUG || DEVELOPMENT)
1718 if (ip_input_measure
) {
1719 net_perf_histogram(&net_perf
, 1);
1721 #endif /* (DEBUG || DEVELOPMENT) */
1722 ip_input_second_pass(packet
, packet
->m_pkthdr
.rcvif
,
1723 1, packet
->m_pkthdr
.len
, &args
);
1727 goto restart_list_process
;
1730 #if (DEBUG || DEVELOPMENT)
1731 if (ip_input_measure
) {
1732 net_perf_measure_time(&net_perf
, &start_tv
, num_pkts
);
1734 #endif /* (DEBUG || DEVELOPMENT) */
1737 * Ip input routine. Checksum and byte swap header. If fragmented
1738 * try to reassemble. Process options. Pass to next level.
1741 ip_input(struct mbuf
*m
)
1747 struct ip_fw_args args
;
1750 ipfilter_t inject_filter_ref
= NULL
;
1751 struct ifnet
*inifp
;
1753 /* Check if the mbuf is still valid after interface filter processing */
1754 MBUF_INPUT_CHECK(m
, m
->m_pkthdr
.rcvif
);
1755 inifp
= m
->m_pkthdr
.rcvif
;
1756 VERIFY(inifp
!= NULL
);
1758 ipstat
.ips_rxc_notlist
++;
1760 /* Perform IP header alignment fixup, if needed */
1761 IP_HDR_ALIGNMENT_FIXUP(m
, inifp
, goto bad
);
1763 m
->m_pkthdr
.pkt_flags
&= ~PKTF_FORWARDED
;
1766 bzero(&args
, sizeof(struct ip_fw_args
));
1769 * Don't bother searching for tag(s) if there's none.
1771 if (SLIST_EMPTY(&m
->m_pkthdr
.tags
)) {
1772 goto ipfw_tags_done
;
1775 /* Grab info from mtags prepended to the chain */
1776 if ((tag
= m_tag_locate(m
, KERNEL_MODULE_TAG_ID
,
1777 KERNEL_TAG_TYPE_DUMMYNET
, NULL
)) != NULL
) {
1778 struct dn_pkt_tag
*dn_tag
;
1780 dn_tag
= (struct dn_pkt_tag
*)(tag
+ 1);
1781 args
.fwa_pf_rule
= dn_tag
->dn_pf_rule
;
1783 m_tag_delete(m
, tag
);
1787 if (m
== NULL
|| !(m
->m_flags
& M_PKTHDR
)) {
1788 panic("ip_input no HDR");
1792 if (args
.fwa_pf_rule
) {
1793 /* dummynet already filtered us */
1794 ip
= mtod(m
, struct ip
*);
1795 hlen
= IP_VHL_HL(ip
->ip_vhl
) << 2;
1796 inject_filter_ref
= ipf_get_inject_filter(m
);
1797 if (args
.fwa_pf_rule
) {
1802 #endif /* DUMMYNET */
1805 * No need to process packet twice if we've already seen it.
1807 if (!SLIST_EMPTY(&m
->m_pkthdr
.tags
)) {
1808 inject_filter_ref
= ipf_get_inject_filter(m
);
1810 if (inject_filter_ref
!= NULL
) {
1811 ip
= mtod(m
, struct ip
*);
1812 hlen
= IP_VHL_HL(ip
->ip_vhl
) << 2;
1814 DTRACE_IP6(receive
, struct mbuf
*, m
, struct inpcb
*, NULL
,
1815 struct ip
*, ip
, struct ifnet
*, inifp
,
1816 struct ip
*, ip
, struct ip6_hdr
*, NULL
);
1818 ip
->ip_len
= ntohs(ip
->ip_len
) - hlen
;
1819 ip
->ip_off
= ntohs(ip
->ip_off
);
1820 ip_proto_dispatch_in(m
, hlen
, ip
->ip_p
, inject_filter_ref
);
1824 OSAddAtomic(1, &ipstat
.ips_total
);
1825 if (m
->m_pkthdr
.len
< sizeof(struct ip
)) {
1829 if (m
->m_len
< sizeof(struct ip
) &&
1830 (m
= m_pullup(m
, sizeof(struct ip
))) == NULL
) {
1831 OSAddAtomic(1, &ipstat
.ips_toosmall
);
1834 ip
= mtod(m
, struct ip
*);
1836 KERNEL_DEBUG(DBG_LAYER_BEG
, ip
->ip_dst
.s_addr
, ip
->ip_src
.s_addr
,
1837 ip
->ip_p
, ip
->ip_off
, ip
->ip_len
);
1839 if (IP_VHL_V(ip
->ip_vhl
) != IPVERSION
) {
1840 OSAddAtomic(1, &ipstat
.ips_badvers
);
1844 hlen
= IP_VHL_HL(ip
->ip_vhl
) << 2;
1845 if (hlen
< sizeof(struct ip
)) { /* minimum header length */
1846 OSAddAtomic(1, &ipstat
.ips_badhlen
);
1849 if (hlen
> m
->m_len
) {
1850 if ((m
= m_pullup(m
, hlen
)) == NULL
) {
1851 OSAddAtomic(1, &ipstat
.ips_badhlen
);
1854 ip
= mtod(m
, struct ip
*);
1857 /* 127/8 must not appear on wire - RFC1122 */
1858 if ((ntohl(ip
->ip_dst
.s_addr
) >> IN_CLASSA_NSHIFT
) == IN_LOOPBACKNET
||
1859 (ntohl(ip
->ip_src
.s_addr
) >> IN_CLASSA_NSHIFT
) == IN_LOOPBACKNET
) {
1861 * Allow for the following exceptions:
1863 * 1. If the packet was sent to loopback (i.e. rcvif
1864 * would have been set earlier at output time.)
1866 * 2. If the packet was sent out on loopback from a local
1867 * source address which belongs to a non-loopback
1868 * interface (i.e. rcvif may not necessarily be a
1869 * loopback interface, hence the test for PKTF_LOOP.)
1870 * Unlike IPv6, there is no interface scope ID, and
1871 * therefore we don't care so much about PKTF_IFINFO.
1873 if (!(inifp
->if_flags
& IFF_LOOPBACK
) &&
1874 !(m
->m_pkthdr
.pkt_flags
& PKTF_LOOP
)) {
1875 OSAddAtomic(1, &ipstat
.ips_badaddr
);
1880 /* IPv4 Link-Local Addresses as defined in RFC3927 */
1881 if ((IN_LINKLOCAL(ntohl(ip
->ip_dst
.s_addr
)) ||
1882 IN_LINKLOCAL(ntohl(ip
->ip_src
.s_addr
)))) {
1883 ip_linklocal_stat
.iplls_in_total
++;
1884 if (ip
->ip_ttl
!= MAXTTL
) {
1885 OSAddAtomic(1, &ip_linklocal_stat
.iplls_in_badttl
);
1886 /* Silently drop link local traffic with bad TTL */
1887 if (!ip_linklocal_in_allowbadttl
) {
1893 sum
= ip_cksum(m
, hlen
);
1898 DTRACE_IP6(receive
, struct mbuf
*, m
, struct inpcb
*, NULL
,
1899 struct ip
*, ip
, struct ifnet
*, inifp
,
1900 struct ip
*, ip
, struct ip6_hdr
*, NULL
);
1903 * Naively assume we can attribute inbound data to the route we would
1904 * use to send to this destination. Asymmetric routing breaks this
1905 * assumption, but it still allows us to account for traffic from
1906 * a remote node in the routing table.
1907 * this has a very significant performance impact so we bypass
1908 * if nstat_collect is disabled. We may also bypass if the
1909 * protocol is tcp in the future because tcp will have a route that
1910 * we can use to attribute the data to. That does mean we would not
1911 * account for forwarded tcp traffic.
1913 if (nstat_collect
) {
1914 struct rtentry
*rt
=
1915 ifnet_cached_rtlookup_inet(inifp
, ip
->ip_src
);
1917 nstat_route_rx(rt
, 1, m
->m_pkthdr
.len
, 0);
1923 * Convert fields to host representation.
1925 #if BYTE_ORDER != BIG_ENDIAN
1929 if (ip
->ip_len
< hlen
) {
1930 OSAddAtomic(1, &ipstat
.ips_badlen
);
1934 #if BYTE_ORDER != BIG_ENDIAN
1938 * Check that the amount of data in the buffers
1939 * is as at least much as the IP header would have us expect.
1940 * Trim mbufs if longer than we expect.
1941 * Drop packet if shorter than we expect.
1943 if (m
->m_pkthdr
.len
< ip
->ip_len
) {
1945 OSAddAtomic(1, &ipstat
.ips_tooshort
);
1948 if (m
->m_pkthdr
.len
> ip
->ip_len
) {
1949 ip_input_adjust(m
, ip
, inifp
);
1956 /* Invoke inbound packet filter */
1957 if (PF_IS_ENABLED
) {
1960 error
= pf_af_hook(inifp
, NULL
, &m
, AF_INET
, TRUE
, &args
);
1962 error
= pf_af_hook(inifp
, NULL
, &m
, AF_INET
, TRUE
, NULL
);
1963 #endif /* DUMMYNET */
1964 if (error
!= 0 || m
== NULL
) {
1966 panic("%s: unexpected packet %p\n",
1970 /* Already freed by callee */
1973 ip
= mtod(m
, struct ip
*);
1974 hlen
= IP_VHL_HL(ip
->ip_vhl
) << 2;
1979 if (ipsec_bypass
== 0 && ipsec_gethist(m
, NULL
)) {
1986 * Process options and, if not destined for us,
1987 * ship it on. ip_dooptions returns 1 when an
1988 * error was detected (causing an icmp message
1989 * to be sent and the original packet to be freed).
1991 ip_nhops
= 0; /* for source routed packets */
1992 if (hlen
> sizeof(struct ip
) && ip_dooptions(m
, 0, NULL
)) {
1997 * Check our list of addresses, to see if the packet is for us.
1998 * If we don't have any addresses, assume any unicast packet
1999 * we receive might be for us (and let the upper layers deal
2002 if (TAILQ_EMPTY(&in_ifaddrhead
) && !(m
->m_flags
& (M_MCAST
| M_BCAST
))) {
2003 ip_setdstifaddr_info(m
, inifp
->if_index
, NULL
);
2008 * Enable a consistency check between the destination address
2009 * and the arrival interface for a unicast packet (the RFC 1122
2010 * strong ES model) if IP forwarding is disabled and the packet
2011 * is not locally generated and the packet is not subject to
2014 * XXX - Checking also should be disabled if the destination
2015 * address is ipnat'ed to a different interface.
2017 * XXX - Checking is incompatible with IP aliases added
2018 * to the loopback interface instead of the interface where
2019 * the packets are received.
2021 if (!IN_MULTICAST(ntohl(ip
->ip_dst
.s_addr
))) {
2022 ip_check_if_result_t check_if_result
= IP_CHECK_IF_NONE
;
2024 check_if_result
= ip_input_check_interface(&m
, ip
, inifp
);
2025 ASSERT(check_if_result
!= IP_CHECK_IF_NONE
);
2026 if (check_if_result
== IP_CHECK_IF_OURS
) {
2028 } else if (check_if_result
== IP_CHECK_IF_DROP
) {
2032 struct in_multi
*inm
;
2034 * See if we belong to the destination multicast group on the
2035 * arrival interface.
2037 in_multihead_lock_shared();
2038 IN_LOOKUP_MULTI(&ip
->ip_dst
, inifp
, inm
);
2039 in_multihead_lock_done();
2041 OSAddAtomic(1, &ipstat
.ips_notmember
);
2045 ip_setdstifaddr_info(m
, inifp
->if_index
, NULL
);
2051 * Not for us; forward if possible and desirable.
2053 if (ipforwarding
== 0) {
2054 OSAddAtomic(1, &ipstat
.ips_cantforward
);
2057 ip_forward(m
, 0, NULL
);
2063 * If offset or IP_MF are set, must reassemble.
2065 if (ip
->ip_off
& ~(IP_DF
| IP_RF
)) {
2070 ip
= mtod(m
, struct ip
*);
2071 /* Get the header length of the reassembled packet */
2072 hlen
= IP_VHL_HL(ip
->ip_vhl
) << 2;
2076 * Further protocols expect the packet length to be w/o the
2084 * enforce IPsec policy checking if we are seeing last header.
2085 * note that we do not visit this with protocols with pcb layer
2086 * code - like udp/tcp/raw ip.
2088 if (ipsec_bypass
== 0 && (ip_protox
[ip
->ip_p
]->pr_flags
& PR_LASTHDR
)) {
2089 if (ipsec4_in_reject(m
, NULL
)) {
2090 IPSEC_STAT_INCREMENT(ipsecstat
.in_polvio
);
2097 * Switch out to protocol's input routine.
2099 OSAddAtomic(1, &ipstat
.ips_delivered
);
2101 ip_proto_dispatch_in(m
, hlen
, ip
->ip_p
, 0);
2105 KERNEL_DEBUG(DBG_LAYER_END
, 0, 0, 0, 0, 0);
2110 ipq_updateparams(void)
2112 LCK_MTX_ASSERT(&ipqlock
, LCK_MTX_ASSERT_OWNED
);
2114 * -1 for unlimited allocation.
2120 * Positive number for specific bound.
2123 ipq_limit
= maxnipq
;
2126 * Zero specifies no further fragment queue allocation -- set the
2127 * bound very low, but rely on implementation elsewhere to actually
2128 * prevent allocation and reclaim current queues.
2134 * Arm the purge timer if not already and if there's work to do
2136 frag_sched_timeout();
2140 sysctl_maxnipq SYSCTL_HANDLER_ARGS
2142 #pragma unused(arg1, arg2)
2145 lck_mtx_lock(&ipqlock
);
2147 error
= sysctl_handle_int(oidp
, &i
, 0, req
);
2148 if (error
|| req
->newptr
== USER_ADDR_NULL
) {
2152 if (i
< -1 || i
> (nmbclusters
/ 4)) {
2159 lck_mtx_unlock(&ipqlock
);
2164 sysctl_maxfragsperpacket SYSCTL_HANDLER_ARGS
2166 #pragma unused(arg1, arg2)
2169 lck_mtx_lock(&ipqlock
);
2170 i
= maxfragsperpacket
;
2171 error
= sysctl_handle_int(oidp
, &i
, 0, req
);
2172 if (error
|| req
->newptr
== USER_ADDR_NULL
) {
2175 maxfragsperpacket
= i
;
2176 ipq_updateparams(); /* see if we need to arm timer */
2178 lck_mtx_unlock(&ipqlock
);
2183 * Take incoming datagram fragment and try to reassemble it into
2184 * whole datagram. If a chain for reassembly of this datagram already
2185 * exists, then it is given as fp; otherwise have to make a chain.
2187 * The IP header is *NOT* adjusted out of iplen (but in host byte order).
2189 static struct mbuf
*
2190 ip_reass(struct mbuf
*m
)
2193 struct mbuf
*p
, *q
, *nq
, *t
;
2194 struct ipq
*fp
= NULL
;
2195 struct ipqhead
*head
;
2198 uint32_t csum
, csum_flags
;
2202 MBUFQ_INIT(&dfq
); /* for deferred frees */
2204 /* If maxnipq or maxfragsperpacket is 0, never accept fragments. */
2205 if (maxnipq
== 0 || maxfragsperpacket
== 0) {
2206 ipstat
.ips_fragments
++;
2207 ipstat
.ips_fragdropped
++;
2210 lck_mtx_lock(&ipqlock
);
2211 frag_sched_timeout(); /* purge stale fragments */
2212 lck_mtx_unlock(&ipqlock
);
2217 ip
= mtod(m
, struct ip
*);
2218 hlen
= IP_VHL_HL(ip
->ip_vhl
) << 2;
2220 lck_mtx_lock(&ipqlock
);
2222 hash
= IPREASS_HASH(ip
->ip_src
.s_addr
, ip
->ip_id
);
2226 * Look for queue of fragments
2229 TAILQ_FOREACH(fp
, head
, ipq_list
) {
2230 if (ip
->ip_id
== fp
->ipq_id
&&
2231 ip
->ip_src
.s_addr
== fp
->ipq_src
.s_addr
&&
2232 ip
->ip_dst
.s_addr
== fp
->ipq_dst
.s_addr
&&
2233 ip
->ip_p
== fp
->ipq_p
) {
2241 * Attempt to trim the number of allocated fragment queues if it
2242 * exceeds the administrative limit.
2244 if ((nipq
> (unsigned)maxnipq
) && (maxnipq
> 0)) {
2246 * drop something from the tail of the current queue
2247 * before proceeding further
2249 struct ipq
*fq
= TAILQ_LAST(head
, ipqhead
);
2250 if (fq
== NULL
) { /* gak */
2251 for (i
= 0; i
< IPREASS_NHASH
; i
++) {
2252 struct ipq
*r
= TAILQ_LAST(&ipq
[i
], ipqhead
);
2254 ipstat
.ips_fragtimeout
+= r
->ipq_nfrags
;
2255 frag_freef(&ipq
[i
], r
);
2260 ipstat
.ips_fragtimeout
+= fq
->ipq_nfrags
;
2261 frag_freef(head
, fq
);
2267 * Leverage partial checksum offload for IP fragments. Narrow down
2268 * the scope to cover only UDP without IP options, as that is the
2271 * Perform 1's complement adjustment of octets that got included/
2272 * excluded in the hardware-calculated checksum value. Ignore cases
2273 * where the value includes the entire IPv4 header span, as the sum
2274 * for those octets would already be 0 by the time we get here; IP
2275 * has already performed its header checksum validation. Also take
2276 * care of any trailing bytes and subtract out their partial sum.
2278 if (ip
->ip_p
== IPPROTO_UDP
&& hlen
== sizeof(struct ip
) &&
2279 (m
->m_pkthdr
.csum_flags
&
2280 (CSUM_DATA_VALID
| CSUM_PARTIAL
| CSUM_PSEUDO_HDR
)) ==
2281 (CSUM_DATA_VALID
| CSUM_PARTIAL
)) {
2282 uint32_t start
= m
->m_pkthdr
.csum_rx_start
;
2283 int32_t trailer
= (m_pktlen(m
) - ip
->ip_len
);
2284 uint32_t swbytes
= (uint32_t)trailer
;
2286 csum
= m
->m_pkthdr
.csum_rx_val
;
2288 ASSERT(trailer
>= 0);
2289 if ((start
!= 0 && start
!= hlen
) || trailer
!= 0) {
2290 uint32_t datalen
= ip
->ip_len
- hlen
;
2292 #if BYTE_ORDER != BIG_ENDIAN
2297 #endif /* BYTE_ORDER != BIG_ENDIAN */
2298 /* callee folds in sum */
2299 csum
= m_adj_sum16(m
, start
, hlen
, datalen
, csum
);
2301 swbytes
+= (hlen
- start
);
2303 swbytes
+= (start
- hlen
);
2305 #if BYTE_ORDER != BIG_ENDIAN
2310 #endif /* BYTE_ORDER != BIG_ENDIAN */
2312 csum_flags
= m
->m_pkthdr
.csum_flags
;
2315 udp_in_cksum_stats(swbytes
);
2325 /* Invalidate checksum */
2326 m
->m_pkthdr
.csum_flags
&= ~CSUM_DATA_VALID
;
2328 ipstat
.ips_fragments
++;
2331 * Adjust ip_len to not reflect header,
2332 * convert offset of this to bytes.
2335 if (ip
->ip_off
& IP_MF
) {
2337 * Make sure that fragments have a data length
2338 * that's a non-zero multiple of 8 bytes.
2340 if (ip
->ip_len
== 0 || (ip
->ip_len
& 0x7) != 0) {
2341 OSAddAtomic(1, &ipstat
.ips_toosmall
);
2343 * Reassembly queue may have been found if previous
2344 * fragments were valid; given that this one is bad,
2345 * we need to drop it. Make sure to set fp to NULL
2346 * if not already, since we don't want to decrement
2347 * ipq_nfrags as it doesn't include this packet.
2352 m
->m_flags
|= M_FRAG
;
2354 /* Clear the flag in case packet comes from loopback */
2355 m
->m_flags
&= ~M_FRAG
;
2359 m
->m_pkthdr
.pkt_hdr
= ip
;
2361 /* Previous ip_reass() started here. */
2363 * Presence of header sizes in mbufs
2364 * would confuse code below.
2370 * If first fragment to arrive, create a reassembly queue.
2373 fp
= ipq_alloc(M_DONTWAIT
);
2377 TAILQ_INSERT_HEAD(head
, fp
, ipq_list
);
2380 fp
->ipq_ttl
= IPFRAGTTL
;
2381 fp
->ipq_p
= ip
->ip_p
;
2382 fp
->ipq_id
= ip
->ip_id
;
2383 fp
->ipq_src
= ip
->ip_src
;
2384 fp
->ipq_dst
= ip
->ip_dst
;
2386 m
->m_nextpkt
= NULL
;
2388 * If the first fragment has valid checksum offload
2389 * info, the rest of fragments are eligible as well.
2391 if (csum_flags
!= 0) {
2392 fp
->ipq_csum
= csum
;
2393 fp
->ipq_csum_flags
= csum_flags
;
2395 m
= NULL
; /* nothing to return */
2401 #define GETIP(m) ((struct ip *)((m)->m_pkthdr.pkt_hdr))
2404 * Handle ECN by comparing this segment with the first one;
2405 * if CE is set, do not lose CE.
2406 * drop if CE and not-ECT are mixed for the same packet.
2408 ecn
= ip
->ip_tos
& IPTOS_ECN_MASK
;
2409 ecn0
= GETIP(fp
->ipq_frags
)->ip_tos
& IPTOS_ECN_MASK
;
2410 if (ecn
== IPTOS_ECN_CE
) {
2411 if (ecn0
== IPTOS_ECN_NOTECT
) {
2414 if (ecn0
!= IPTOS_ECN_CE
) {
2415 GETIP(fp
->ipq_frags
)->ip_tos
|= IPTOS_ECN_CE
;
2418 if (ecn
== IPTOS_ECN_NOTECT
&& ecn0
!= IPTOS_ECN_NOTECT
) {
2423 * Find a segment which begins after this one does.
2425 for (p
= NULL
, q
= fp
->ipq_frags
; q
; p
= q
, q
= q
->m_nextpkt
) {
2426 if (GETIP(q
)->ip_off
> ip
->ip_off
) {
2432 * If there is a preceding segment, it may provide some of
2433 * our data already. If so, drop the data from the incoming
2434 * segment. If it provides all of our data, drop us, otherwise
2435 * stick new segment in the proper place.
2437 * If some of the data is dropped from the preceding
2438 * segment, then it's checksum is invalidated.
2441 i
= GETIP(p
)->ip_off
+ GETIP(p
)->ip_len
- ip
->ip_off
;
2443 if (i
>= ip
->ip_len
) {
2447 fp
->ipq_csum_flags
= 0;
2451 m
->m_nextpkt
= p
->m_nextpkt
;
2454 m
->m_nextpkt
= fp
->ipq_frags
;
2459 * While we overlap succeeding segments trim them or,
2460 * if they are completely covered, dequeue them.
2462 for (; q
!= NULL
&& ip
->ip_off
+ ip
->ip_len
> GETIP(q
)->ip_off
;
2464 i
= (ip
->ip_off
+ ip
->ip_len
) - GETIP(q
)->ip_off
;
2465 if (i
< GETIP(q
)->ip_len
) {
2466 GETIP(q
)->ip_len
-= i
;
2467 GETIP(q
)->ip_off
+= i
;
2469 fp
->ipq_csum_flags
= 0;
2474 ipstat
.ips_fragdropped
++;
2476 /* defer freeing until after lock is dropped */
2477 MBUFQ_ENQUEUE(&dfq
, q
);
2481 * If this fragment contains similar checksum offload info
2482 * as that of the existing ones, accumulate checksum. Otherwise,
2483 * invalidate checksum offload info for the entire datagram.
2485 if (csum_flags
!= 0 && csum_flags
== fp
->ipq_csum_flags
) {
2486 fp
->ipq_csum
+= csum
;
2487 } else if (fp
->ipq_csum_flags
!= 0) {
2488 fp
->ipq_csum_flags
= 0;
2493 * Check for complete reassembly and perform frag per packet
2496 * Frag limiting is performed here so that the nth frag has
2497 * a chance to complete the packet before we drop the packet.
2498 * As a result, n+1 frags are actually allowed per packet, but
2499 * only n will ever be stored. (n = maxfragsperpacket.)
2503 for (p
= NULL
, q
= fp
->ipq_frags
; q
; p
= q
, q
= q
->m_nextpkt
) {
2504 if (GETIP(q
)->ip_off
!= next
) {
2505 if (fp
->ipq_nfrags
> maxfragsperpacket
) {
2506 ipstat
.ips_fragdropped
+= fp
->ipq_nfrags
;
2507 frag_freef(head
, fp
);
2509 m
= NULL
; /* nothing to return */
2512 next
+= GETIP(q
)->ip_len
;
2514 /* Make sure the last packet didn't have the IP_MF flag */
2515 if (p
->m_flags
& M_FRAG
) {
2516 if (fp
->ipq_nfrags
> maxfragsperpacket
) {
2517 ipstat
.ips_fragdropped
+= fp
->ipq_nfrags
;
2518 frag_freef(head
, fp
);
2520 m
= NULL
; /* nothing to return */
2525 * Reassembly is complete. Make sure the packet is a sane size.
2529 if (next
+ (IP_VHL_HL(ip
->ip_vhl
) << 2) > IP_MAXPACKET
) {
2530 ipstat
.ips_toolong
++;
2531 ipstat
.ips_fragdropped
+= fp
->ipq_nfrags
;
2532 frag_freef(head
, fp
);
2533 m
= NULL
; /* nothing to return */
2538 * Concatenate fragments.
2545 q
->m_nextpkt
= NULL
;
2546 for (q
= nq
; q
!= NULL
; q
= nq
) {
2548 q
->m_nextpkt
= NULL
;
2553 * Store partial hardware checksum info from the fragment queue;
2554 * the receive start offset is set to 20 bytes (see code at the
2555 * top of this routine.)
2557 if (fp
->ipq_csum_flags
!= 0) {
2558 csum
= fp
->ipq_csum
;
2562 m
->m_pkthdr
.csum_rx_val
= csum
;
2563 m
->m_pkthdr
.csum_rx_start
= sizeof(struct ip
);
2564 m
->m_pkthdr
.csum_flags
= fp
->ipq_csum_flags
;
2565 } else if ((m
->m_pkthdr
.rcvif
->if_flags
& IFF_LOOPBACK
) ||
2566 (m
->m_pkthdr
.pkt_flags
& PKTF_LOOP
)) {
2567 /* loopback checksums are always OK */
2568 m
->m_pkthdr
.csum_data
= 0xffff;
2569 m
->m_pkthdr
.csum_flags
=
2570 CSUM_DATA_VALID
| CSUM_PSEUDO_HDR
|
2571 CSUM_IP_CHECKED
| CSUM_IP_VALID
;
2575 * Create header for new ip packet by modifying header of first
2576 * packet; dequeue and discard fragment reassembly header.
2577 * Make header visible.
2579 ip
->ip_len
= (IP_VHL_HL(ip
->ip_vhl
) << 2) + next
;
2580 ip
->ip_src
= fp
->ipq_src
;
2581 ip
->ip_dst
= fp
->ipq_dst
;
2583 fp
->ipq_frags
= NULL
; /* return to caller as 'm' */
2584 frag_freef(head
, fp
);
2587 m
->m_len
+= (IP_VHL_HL(ip
->ip_vhl
) << 2);
2588 m
->m_data
-= (IP_VHL_HL(ip
->ip_vhl
) << 2);
2589 /* some debugging cruft by sklower, below, will go away soon */
2590 if (m
->m_flags
& M_PKTHDR
) { /* XXX this should be done elsewhere */
2593 ipstat
.ips_reassembled
++;
2595 /* arm the purge timer if not already and if there's work to do */
2596 frag_sched_timeout();
2597 lck_mtx_unlock(&ipqlock
);
2598 /* perform deferred free (if needed) now that lock is dropped */
2599 if (!MBUFQ_EMPTY(&dfq
)) {
2602 VERIFY(MBUFQ_EMPTY(&dfq
));
2607 /* arm the purge timer if not already and if there's work to do */
2608 frag_sched_timeout();
2609 lck_mtx_unlock(&ipqlock
);
2610 /* perform deferred free (if needed) */
2611 if (!MBUFQ_EMPTY(&dfq
)) {
2614 VERIFY(MBUFQ_EMPTY(&dfq
));
2618 ipstat
.ips_fragdropped
++;
2622 /* arm the purge timer if not already and if there's work to do */
2623 frag_sched_timeout();
2624 lck_mtx_unlock(&ipqlock
);
2626 /* perform deferred free (if needed) */
2627 if (!MBUFQ_EMPTY(&dfq
)) {
2630 VERIFY(MBUFQ_EMPTY(&dfq
));
2636 * Free a fragment reassembly header and all
2637 * associated datagrams.
2640 frag_freef(struct ipqhead
*fhp
, struct ipq
*fp
)
2642 LCK_MTX_ASSERT(&ipqlock
, LCK_MTX_ASSERT_OWNED
);
2645 if (fp
->ipq_frags
!= NULL
) {
2646 m_freem_list(fp
->ipq_frags
);
2647 fp
->ipq_frags
= NULL
;
2649 TAILQ_REMOVE(fhp
, fp
, ipq_list
);
2655 * IP reassembly timer processing
2658 frag_timeout(void *arg
)
2665 * Update coarse-grained networking timestamp (in sec.); the idea
2666 * is to piggy-back on the timeout callout to update the counter
2667 * returnable via net_uptime().
2669 net_update_uptime();
2671 lck_mtx_lock(&ipqlock
);
2672 for (i
= 0; i
< IPREASS_NHASH
; i
++) {
2673 for (fp
= TAILQ_FIRST(&ipq
[i
]); fp
;) {
2677 fp
= TAILQ_NEXT(fp
, ipq_list
);
2678 if (--fpp
->ipq_ttl
== 0) {
2679 ipstat
.ips_fragtimeout
+= fpp
->ipq_nfrags
;
2680 frag_freef(&ipq
[i
], fpp
);
2685 * If we are over the maximum number of fragments
2686 * (due to the limit being lowered), drain off
2687 * enough to get down to the new limit.
2689 if (maxnipq
>= 0 && nipq
> (unsigned)maxnipq
) {
2690 for (i
= 0; i
< IPREASS_NHASH
; i
++) {
2691 while (nipq
> (unsigned)maxnipq
&&
2692 !TAILQ_EMPTY(&ipq
[i
])) {
2693 ipstat
.ips_fragdropped
+=
2694 TAILQ_FIRST(&ipq
[i
])->ipq_nfrags
;
2695 frag_freef(&ipq
[i
], TAILQ_FIRST(&ipq
[i
]));
2699 /* re-arm the purge timer if there's work to do */
2700 frag_timeout_run
= 0;
2701 frag_sched_timeout();
2702 lck_mtx_unlock(&ipqlock
);
2706 frag_sched_timeout(void)
2708 LCK_MTX_ASSERT(&ipqlock
, LCK_MTX_ASSERT_OWNED
);
2710 if (!frag_timeout_run
&& nipq
> 0) {
2711 frag_timeout_run
= 1;
2712 timeout(frag_timeout
, NULL
, hz
);
2717 * Drain off all datagram fragments.
2724 lck_mtx_lock(&ipqlock
);
2725 for (i
= 0; i
< IPREASS_NHASH
; i
++) {
2726 while (!TAILQ_EMPTY(&ipq
[i
])) {
2727 ipstat
.ips_fragdropped
+=
2728 TAILQ_FIRST(&ipq
[i
])->ipq_nfrags
;
2729 frag_freef(&ipq
[i
], TAILQ_FIRST(&ipq
[i
]));
2732 lck_mtx_unlock(&ipqlock
);
2742 * See comments in ipq_updateparams(). Keep the count separate
2743 * from nipq since the latter represents the elements already
2744 * in the reassembly queues.
2746 if (ipq_limit
> 0 && ipq_count
> ipq_limit
) {
2750 t
= m_get(how
, MT_FTABLE
);
2752 atomic_add_32(&ipq_count
, 1);
2753 fp
= mtod(t
, struct ipq
*);
2754 bzero(fp
, sizeof(*fp
));
2762 ipq_free(struct ipq
*fp
)
2764 (void) m_free(dtom(fp
));
2765 atomic_add_32(&ipq_count
, -1);
2774 frag_drain(); /* fragments */
2775 in_rtqdrain(); /* protocol cloned routes */
2776 in_arpdrain(NULL
); /* cloned routes: ARP */
2780 * Do option processing on a datagram,
2781 * possibly discarding it if bad options are encountered,
2782 * or forwarding it if source-routed.
2783 * The pass argument is used when operating in the IPSTEALTH
2784 * mode to tell what options to process:
2785 * [LS]SRR (pass 0) or the others (pass 1).
2786 * The reason for as many as two passes is that when doing IPSTEALTH,
2787 * non-routing options should be processed only if the packet is for us.
2788 * Returns 1 if packet has been forwarded/freed,
2789 * 0 if the packet should be processed further.
2792 ip_dooptions(struct mbuf
*m
, int pass
, struct sockaddr_in
*next_hop
)
2794 #pragma unused(pass)
2795 struct ip
*ip
= mtod(m
, struct ip
*);
2797 struct ip_timestamp
*ipt
;
2798 struct in_ifaddr
*ia
;
2799 int opt
, optlen
, cnt
, off
, code
, type
= ICMP_PARAMPROB
, forward
= 0;
2800 struct in_addr
*sin
, dst
;
2802 struct sockaddr_in ipaddr
= {
2803 .sin_len
= sizeof(ipaddr
),
2804 .sin_family
= AF_INET
,
2806 .sin_addr
= { .s_addr
= 0 },
2810 /* Expect 32-bit aligned data pointer on strict-align platforms */
2811 MBUF_STRICT_DATA_ALIGNMENT_CHECK_32(m
);
2814 cp
= (u_char
*)(ip
+ 1);
2815 cnt
= (IP_VHL_HL(ip
->ip_vhl
) << 2) - sizeof(struct ip
);
2816 for (; cnt
> 0; cnt
-= optlen
, cp
+= optlen
) {
2817 opt
= cp
[IPOPT_OPTVAL
];
2818 if (opt
== IPOPT_EOL
) {
2821 if (opt
== IPOPT_NOP
) {
2824 if (cnt
< IPOPT_OLEN
+ sizeof(*cp
)) {
2825 code
= &cp
[IPOPT_OLEN
] - (u_char
*)ip
;
2828 optlen
= cp
[IPOPT_OLEN
];
2829 if (optlen
< IPOPT_OLEN
+ sizeof(*cp
) ||
2831 code
= &cp
[IPOPT_OLEN
] - (u_char
*)ip
;
2840 * Source routing with record.
2841 * Find interface with current destination address.
2842 * If none on this machine then drop if strictly routed,
2843 * or do nothing if loosely routed.
2844 * Record interface address and bring up next address
2845 * component. If strictly routed make sure next
2846 * address is on directly accessible net.
2850 if (optlen
< IPOPT_OFFSET
+ sizeof(*cp
)) {
2851 code
= &cp
[IPOPT_OLEN
] - (u_char
*)ip
;
2854 if ((off
= cp
[IPOPT_OFFSET
]) < IPOPT_MINOFF
) {
2855 code
= &cp
[IPOPT_OFFSET
] - (u_char
*)ip
;
2858 ipaddr
.sin_addr
= ip
->ip_dst
;
2859 ia
= (struct in_ifaddr
*)ifa_ifwithaddr(SA(&ipaddr
));
2861 if (opt
== IPOPT_SSRR
) {
2862 type
= ICMP_UNREACH
;
2863 code
= ICMP_UNREACH_SRCFAIL
;
2866 if (!ip_dosourceroute
) {
2867 goto nosourcerouting
;
2870 * Loose routing, and not at next destination
2871 * yet; nothing to do except forward.
2875 IFA_REMREF(&ia
->ia_ifa
);
2878 off
--; /* 0 origin */
2879 if (off
> optlen
- (int)sizeof(struct in_addr
)) {
2881 * End of source route. Should be for us.
2883 if (!ip_acceptsourceroute
) {
2884 goto nosourcerouting
;
2886 save_rte(cp
, ip
->ip_src
);
2890 if (!ip_dosourceroute
) {
2892 char buf
[MAX_IPv4_STR_LEN
];
2893 char buf2
[MAX_IPv4_STR_LEN
];
2895 * Acting as a router, so generate ICMP
2899 "attempted source route from %s "
2901 inet_ntop(AF_INET
, &ip
->ip_src
,
2903 inet_ntop(AF_INET
, &ip
->ip_dst
,
2904 buf2
, sizeof(buf2
)));
2905 type
= ICMP_UNREACH
;
2906 code
= ICMP_UNREACH_SRCFAIL
;
2910 * Not acting as a router,
2913 OSAddAtomic(1, &ipstat
.ips_cantforward
);
2920 * locate outgoing interface
2922 (void) memcpy(&ipaddr
.sin_addr
, cp
+ off
,
2923 sizeof(ipaddr
.sin_addr
));
2925 if (opt
== IPOPT_SSRR
) {
2926 #define INA struct in_ifaddr *
2927 if ((ia
= (INA
)ifa_ifwithdstaddr(
2928 SA(&ipaddr
))) == NULL
) {
2929 ia
= (INA
)ifa_ifwithnet(SA(&ipaddr
));
2932 ia
= ip_rtaddr(ipaddr
.sin_addr
);
2935 type
= ICMP_UNREACH
;
2936 code
= ICMP_UNREACH_SRCFAIL
;
2939 ip
->ip_dst
= ipaddr
.sin_addr
;
2940 IFA_LOCK(&ia
->ia_ifa
);
2941 (void) memcpy(cp
+ off
, &(IA_SIN(ia
)->sin_addr
),
2942 sizeof(struct in_addr
));
2943 IFA_UNLOCK(&ia
->ia_ifa
);
2944 IFA_REMREF(&ia
->ia_ifa
);
2946 cp
[IPOPT_OFFSET
] += sizeof(struct in_addr
);
2948 * Let ip_intr's mcast routing check handle mcast pkts
2950 forward
= !IN_MULTICAST(ntohl(ip
->ip_dst
.s_addr
));
2954 if (optlen
< IPOPT_OFFSET
+ sizeof(*cp
)) {
2955 code
= &cp
[IPOPT_OFFSET
] - (u_char
*)ip
;
2958 if ((off
= cp
[IPOPT_OFFSET
]) < IPOPT_MINOFF
) {
2959 code
= &cp
[IPOPT_OFFSET
] - (u_char
*)ip
;
2963 * If no space remains, ignore.
2965 off
--; /* 0 origin */
2966 if (off
> optlen
- (int)sizeof(struct in_addr
)) {
2969 (void) memcpy(&ipaddr
.sin_addr
, &ip
->ip_dst
,
2970 sizeof(ipaddr
.sin_addr
));
2972 * locate outgoing interface; if we're the destination,
2973 * use the incoming interface (should be same).
2975 if ((ia
= (INA
)ifa_ifwithaddr(SA(&ipaddr
))) == NULL
) {
2976 if ((ia
= ip_rtaddr(ipaddr
.sin_addr
)) == NULL
) {
2977 type
= ICMP_UNREACH
;
2978 code
= ICMP_UNREACH_HOST
;
2982 IFA_LOCK(&ia
->ia_ifa
);
2983 (void) memcpy(cp
+ off
, &(IA_SIN(ia
)->sin_addr
),
2984 sizeof(struct in_addr
));
2985 IFA_UNLOCK(&ia
->ia_ifa
);
2986 IFA_REMREF(&ia
->ia_ifa
);
2988 cp
[IPOPT_OFFSET
] += sizeof(struct in_addr
);
2992 code
= cp
- (u_char
*)ip
;
2993 ipt
= (struct ip_timestamp
*)(void *)cp
;
2994 if (ipt
->ipt_len
< 4 || ipt
->ipt_len
> 40) {
2995 code
= (u_char
*)&ipt
->ipt_len
- (u_char
*)ip
;
2998 if (ipt
->ipt_ptr
< 5) {
2999 code
= (u_char
*)&ipt
->ipt_ptr
- (u_char
*)ip
;
3003 ipt
->ipt_len
- (int)sizeof(int32_t)) {
3004 if (++ipt
->ipt_oflw
== 0) {
3005 code
= (u_char
*)&ipt
->ipt_ptr
-
3011 sin
= (struct in_addr
*)(void *)(cp
+ ipt
->ipt_ptr
- 1);
3012 switch (ipt
->ipt_flg
) {
3013 case IPOPT_TS_TSONLY
:
3016 case IPOPT_TS_TSANDADDR
:
3017 if (ipt
->ipt_ptr
- 1 + sizeof(n_time
) +
3018 sizeof(struct in_addr
) > ipt
->ipt_len
) {
3019 code
= (u_char
*)&ipt
->ipt_ptr
-
3023 ipaddr
.sin_addr
= dst
;
3024 ia
= (INA
)ifaof_ifpforaddr(SA(&ipaddr
),
3029 IFA_LOCK(&ia
->ia_ifa
);
3030 (void) memcpy(sin
, &IA_SIN(ia
)->sin_addr
,
3031 sizeof(struct in_addr
));
3032 IFA_UNLOCK(&ia
->ia_ifa
);
3033 ipt
->ipt_ptr
+= sizeof(struct in_addr
);
3034 IFA_REMREF(&ia
->ia_ifa
);
3038 case IPOPT_TS_PRESPEC
:
3039 if (ipt
->ipt_ptr
- 1 + sizeof(n_time
) +
3040 sizeof(struct in_addr
) > ipt
->ipt_len
) {
3041 code
= (u_char
*)&ipt
->ipt_ptr
-
3045 (void) memcpy(&ipaddr
.sin_addr
, sin
,
3046 sizeof(struct in_addr
));
3047 if ((ia
= (struct in_ifaddr
*)ifa_ifwithaddr(
3048 SA(&ipaddr
))) == NULL
) {
3051 IFA_REMREF(&ia
->ia_ifa
);
3053 ipt
->ipt_ptr
+= sizeof(struct in_addr
);
3057 /* XXX can't take &ipt->ipt_flg */
3058 code
= (u_char
*)&ipt
->ipt_ptr
-
3063 (void) memcpy(cp
+ ipt
->ipt_ptr
- 1, &ntime
,
3065 ipt
->ipt_ptr
+= sizeof(n_time
);
3068 if (forward
&& ipforwarding
) {
3069 ip_forward(m
, 1, next_hop
);
3074 icmp_error(m
, type
, code
, 0, 0);
3075 OSAddAtomic(1, &ipstat
.ips_badoptions
);
3080 * Check for the presence of the IP Router Alert option [RFC2113]
3081 * in the header of an IPv4 datagram.
3083 * This call is not intended for use from the forwarding path; it is here
3084 * so that protocol domains may check for the presence of the option.
3085 * Given how FreeBSD's IPv4 stack is currently structured, the Router Alert
3086 * option does not have much relevance to the implementation, though this
3087 * may change in future.
3088 * Router alert options SHOULD be passed if running in IPSTEALTH mode and
3089 * we are not the endpoint.
3090 * Length checks on individual options should already have been peformed
3091 * by ip_dooptions() therefore they are folded under DIAGNOSTIC here.
3093 * Return zero if not present or options are invalid, non-zero if present.
3096 ip_checkrouteralert(struct mbuf
*m
)
3098 struct ip
*ip
= mtod(m
, struct ip
*);
3100 int opt
, optlen
, cnt
, found_ra
;
3103 cp
= (u_char
*)(ip
+ 1);
3104 cnt
= (IP_VHL_HL(ip
->ip_vhl
) << 2) - sizeof(struct ip
);
3105 for (; cnt
> 0; cnt
-= optlen
, cp
+= optlen
) {
3106 opt
= cp
[IPOPT_OPTVAL
];
3107 if (opt
== IPOPT_EOL
) {
3110 if (opt
== IPOPT_NOP
) {
3114 if (cnt
< IPOPT_OLEN
+ sizeof(*cp
)) {
3118 optlen
= cp
[IPOPT_OLEN
];
3120 if (optlen
< IPOPT_OLEN
+ sizeof(*cp
) || optlen
> cnt
) {
3128 if (optlen
!= IPOPT_OFFSET
+ sizeof(uint16_t) ||
3129 (*((uint16_t *)(void *)&cp
[IPOPT_OFFSET
]) != 0)) {
3144 * Given address of next destination (final or next hop),
3145 * return internet address info of interface to be used to get there.
3148 ip_rtaddr(struct in_addr dst
)
3150 struct sockaddr_in
*sin
;
3151 struct ifaddr
*rt_ifa
;
3154 bzero(&ro
, sizeof(ro
));
3155 sin
= SIN(&ro
.ro_dst
);
3156 sin
->sin_family
= AF_INET
;
3157 sin
->sin_len
= sizeof(*sin
);
3158 sin
->sin_addr
= dst
;
3160 rtalloc_ign(&ro
, RTF_PRCLONING
);
3161 if (ro
.ro_rt
== NULL
) {
3167 if ((rt_ifa
= ro
.ro_rt
->rt_ifa
) != NULL
) {
3170 RT_UNLOCK(ro
.ro_rt
);
3173 return (struct in_ifaddr
*)rt_ifa
;
3177 * Save incoming source route for use in replies,
3178 * to be picked up later by ip_srcroute if the receiver is interested.
3181 save_rte(u_char
*option
, struct in_addr dst
)
3185 olen
= option
[IPOPT_OLEN
];
3188 printf("save_rte: olen %d\n", olen
);
3191 if (olen
> sizeof(ip_srcrt
) - (1 + sizeof(dst
))) {
3194 bcopy(option
, ip_srcrt
.srcopt
, olen
);
3195 ip_nhops
= (olen
- IPOPT_OFFSET
- 1) / sizeof(struct in_addr
);
3200 * Retrieve incoming source route for use in replies,
3201 * in the same form used by setsockopt.
3202 * The first hop is placed before the options, will be removed later.
3207 struct in_addr
*p
, *q
;
3210 if (ip_nhops
== 0) {
3214 m
= m_get(M_DONTWAIT
, MT_HEADER
);
3219 #define OPTSIZ (sizeof (ip_srcrt.nop) + sizeof (ip_srcrt.srcopt))
3221 /* length is (nhops+1)*sizeof(addr) + sizeof(nop + srcrt header) */
3222 m
->m_len
= ip_nhops
* sizeof(struct in_addr
) +
3223 sizeof(struct in_addr
) + OPTSIZ
;
3226 printf("ip_srcroute: nhops %d mlen %d", ip_nhops
, m
->m_len
);
3231 * First save first hop for return route
3233 p
= &ip_srcrt
.route
[ip_nhops
- 1];
3234 *(mtod(m
, struct in_addr
*)) = *p
--;
3238 (u_int32_t
)ntohl(mtod(m
, struct in_addr
*)->s_addr
));
3243 * Copy option fields and padding (nop) to mbuf.
3245 ip_srcrt
.nop
= IPOPT_NOP
;
3246 ip_srcrt
.srcopt
[IPOPT_OFFSET
] = IPOPT_MINOFF
;
3247 (void) memcpy(mtod(m
, caddr_t
) + sizeof(struct in_addr
),
3248 &ip_srcrt
.nop
, OPTSIZ
);
3249 q
= (struct in_addr
*)(void *)(mtod(m
, caddr_t
) +
3250 sizeof(struct in_addr
) + OPTSIZ
);
3253 * Record return path as an IP source route,
3254 * reversing the path (pointers are now aligned).
3256 while (p
>= ip_srcrt
.route
) {
3259 printf(" %lx", (u_int32_t
)ntohl(q
->s_addr
));
3265 * Last hop goes to final destination.
3270 printf(" %lx\n", (u_int32_t
)ntohl(q
->s_addr
));
3277 * Strip out IP options, at higher level protocol in the kernel.
3280 ip_stripoptions(struct mbuf
*m
)
3283 struct ip
*ip
= mtod(m
, struct ip
*);
3287 /* Expect 32-bit aligned data pointer on strict-align platforms */
3288 MBUF_STRICT_DATA_ALIGNMENT_CHECK_32(m
);
3290 /* use bcopy() since it supports overlapping range */
3291 olen
= (IP_VHL_HL(ip
->ip_vhl
) << 2) - sizeof(struct ip
);
3292 opts
= (caddr_t
)(ip
+ 1);
3293 i
= m
->m_len
- (sizeof(struct ip
) + olen
);
3294 bcopy(opts
+ olen
, opts
, (unsigned)i
);
3296 if (m
->m_flags
& M_PKTHDR
) {
3297 m
->m_pkthdr
.len
-= olen
;
3299 ip
->ip_vhl
= IP_MAKE_VHL(IPVERSION
, sizeof(struct ip
) >> 2);
3302 * We expect ip_{off,len} to be in host order by now, and
3303 * that the original IP header length has been subtracted
3304 * out from ip_len. Temporarily adjust ip_len for checksum
3305 * recalculation, and restore it afterwards.
3307 ip
->ip_len
+= sizeof(struct ip
);
3309 /* recompute checksum now that IP header is smaller */
3310 #if BYTE_ORDER != BIG_ENDIAN
3313 #endif /* BYTE_ORDER != BIG_ENDIAN */
3314 ip
->ip_sum
= in_cksum_hdr(ip
);
3315 #if BYTE_ORDER != BIG_ENDIAN
3318 #endif /* BYTE_ORDER != BIG_ENDIAN */
3320 ip
->ip_len
-= sizeof(struct ip
);
3323 * Given that we've just stripped IP options from the header,
3324 * we need to adjust the start offset accordingly if this
3325 * packet had gone thru partial checksum offload.
3327 if ((m
->m_pkthdr
.csum_flags
& (CSUM_DATA_VALID
| CSUM_PARTIAL
)) ==
3328 (CSUM_DATA_VALID
| CSUM_PARTIAL
)) {
3329 if (m
->m_pkthdr
.csum_rx_start
>= (sizeof(struct ip
) + olen
)) {
3330 /* most common case */
3331 m
->m_pkthdr
.csum_rx_start
-= olen
;
3333 /* compute checksum in software instead */
3334 m
->m_pkthdr
.csum_flags
&= ~CSUM_DATA_VALID
;
3335 m
->m_pkthdr
.csum_data
= 0;
3336 ipstat
.ips_adj_hwcsum_clr
++;
3341 u_char inetctlerrmap
[PRC_NCMDS
] = {
3343 0, EMSGSIZE
, EHOSTDOWN
, EHOSTUNREACH
,
3344 ENETUNREACH
, EHOSTUNREACH
, ECONNREFUSED
, ECONNREFUSED
,
3345 EMSGSIZE
, EHOSTUNREACH
, 0, 0,
3346 0, 0, EHOSTUNREACH
, 0,
3347 ENOPROTOOPT
, ECONNREFUSED
3351 sysctl_ipforwarding SYSCTL_HANDLER_ARGS
3353 #pragma unused(arg1, arg2)
3354 int i
, was_ipforwarding
= ipforwarding
;
3356 i
= sysctl_handle_int(oidp
, oidp
->oid_arg1
, oidp
->oid_arg2
, req
);
3357 if (i
!= 0 || req
->newptr
== USER_ADDR_NULL
) {
3361 if (was_ipforwarding
&& !ipforwarding
) {
3362 /* clean up IPv4 forwarding cached routes */
3363 ifnet_head_lock_shared();
3364 for (i
= 0; i
<= if_index
; i
++) {
3365 struct ifnet
*ifp
= ifindex2ifnet
[i
];
3367 lck_mtx_lock(&ifp
->if_cached_route_lock
);
3368 ROUTE_RELEASE(&ifp
->if_fwd_route
);
3369 bzero(&ifp
->if_fwd_route
,
3370 sizeof(ifp
->if_fwd_route
));
3371 lck_mtx_unlock(&ifp
->if_cached_route_lock
);
3381 * Similar to inp_route_{copyout,copyin} routines except that these copy
3382 * out the cached IPv4 forwarding route from struct ifnet instead of the
3383 * inpcb. See comments for those routines for explanations.
3386 ip_fwd_route_copyout(struct ifnet
*ifp
, struct route
*dst
)
3388 struct route
*src
= &ifp
->if_fwd_route
;
3390 lck_mtx_lock_spin(&ifp
->if_cached_route_lock
);
3391 lck_mtx_convert_spin(&ifp
->if_cached_route_lock
);
3393 /* Minor sanity check */
3394 if (src
->ro_rt
!= NULL
&& rt_key(src
->ro_rt
)->sa_family
!= AF_INET
) {
3395 panic("%s: wrong or corrupted route: %p", __func__
, src
);
3398 route_copyout(dst
, src
, sizeof(*dst
));
3400 lck_mtx_unlock(&ifp
->if_cached_route_lock
);
3404 ip_fwd_route_copyin(struct ifnet
*ifp
, struct route
*src
)
3406 struct route
*dst
= &ifp
->if_fwd_route
;
3408 lck_mtx_lock_spin(&ifp
->if_cached_route_lock
);
3409 lck_mtx_convert_spin(&ifp
->if_cached_route_lock
);
3411 /* Minor sanity check */
3412 if (src
->ro_rt
!= NULL
&& rt_key(src
->ro_rt
)->sa_family
!= AF_INET
) {
3413 panic("%s: wrong or corrupted route: %p", __func__
, src
);
3416 if (ifp
->if_fwd_cacheok
) {
3417 route_copyin(src
, dst
, sizeof(*src
));
3420 lck_mtx_unlock(&ifp
->if_cached_route_lock
);
3424 * Forward a packet. If some error occurs return the sender
3425 * an icmp packet. Note we can't always generate a meaningful
3426 * icmp message because icmp doesn't have a large enough repertoire
3427 * of codes and types.
3429 * If not forwarding, just drop the packet. This could be confusing
3430 * if ipforwarding was zero but some routing protocol was advancing
3431 * us as a gateway to somewhere. However, we must let the routing
3432 * protocol deal with that.
3434 * The srcrt parameter indicates whether the packet is being forwarded
3435 * via a source route.
3438 ip_forward(struct mbuf
*m
, int srcrt
, struct sockaddr_in
*next_hop
)
3440 #pragma unused(next_hop)
3441 struct ip
*ip
= mtod(m
, struct ip
*);
3442 struct sockaddr_in
*sin
;
3444 struct route fwd_rt
;
3445 int error
, type
= 0, code
= 0;
3448 struct in_addr pkt_dst
;
3449 u_int32_t nextmtu
= 0, len
;
3450 struct ip_out_args ipoa
;
3451 struct ifnet
*rcvifp
= m
->m_pkthdr
.rcvif
;
3453 bzero(&ipoa
, sizeof(ipoa
));
3454 ipoa
.ipoa_boundif
= IFSCOPE_NONE
;
3455 ipoa
.ipoa_sotc
= SO_TC_UNSPEC
;
3456 ipoa
.ipoa_netsvctype
= _NET_SERVICE_TYPE_UNSPEC
;
3459 struct secpolicy
*sp
= NULL
;
3463 struct pf_mtag
*pf_mtag
;
3467 pkt_dst
= ip
->ip_dst
;
3471 printf("forward: src %lx dst %lx ttl %x\n",
3472 (u_int32_t
)ip
->ip_src
.s_addr
, (u_int32_t
)pkt_dst
.s_addr
,
3477 if (m
->m_flags
& (M_BCAST
| M_MCAST
) || !in_canforward(pkt_dst
)) {
3478 OSAddAtomic(1, &ipstat
.ips_cantforward
);
3484 #endif /* IPSTEALTH */
3485 if (ip
->ip_ttl
<= IPTTLDEC
) {
3486 icmp_error(m
, ICMP_TIMXCEED
, ICMP_TIMXCEED_INTRANS
,
3492 #endif /* IPSTEALTH */
3495 pf_mtag
= pf_find_mtag(m
);
3496 if (pf_mtag
!= NULL
&& pf_mtag
->pftag_rtableid
!= IFSCOPE_NONE
) {
3497 ipoa
.ipoa_boundif
= pf_mtag
->pftag_rtableid
;
3498 ipoa
.ipoa_flags
|= IPOAF_BOUND_IF
;
3502 ip_fwd_route_copyout(rcvifp
, &fwd_rt
);
3504 sin
= SIN(&fwd_rt
.ro_dst
);
3505 if (ROUTE_UNUSABLE(&fwd_rt
) || pkt_dst
.s_addr
!= sin
->sin_addr
.s_addr
) {
3506 ROUTE_RELEASE(&fwd_rt
);
3508 sin
->sin_family
= AF_INET
;
3509 sin
->sin_len
= sizeof(*sin
);
3510 sin
->sin_addr
= pkt_dst
;
3512 rtalloc_scoped_ign(&fwd_rt
, RTF_PRCLONING
, ipoa
.ipoa_boundif
);
3513 if (fwd_rt
.ro_rt
== NULL
) {
3514 icmp_error(m
, ICMP_UNREACH
, ICMP_UNREACH_HOST
, dest
, 0);
3521 * Save the IP header and at most 8 bytes of the payload,
3522 * in case we need to generate an ICMP message to the src.
3524 * We don't use m_copy() because it might return a reference
3525 * to a shared cluster. Both this function and ip_output()
3526 * assume exclusive access to the IP header in `m', so any
3527 * data in a cluster may change before we reach icmp_error().
3529 MGET(mcopy
, M_DONTWAIT
, m
->m_type
);
3530 if (mcopy
!= NULL
) {
3531 M_COPY_PKTHDR(mcopy
, m
);
3532 mcopy
->m_len
= imin((IP_VHL_HL(ip
->ip_vhl
) << 2) + 8,
3534 m_copydata(m
, 0, mcopy
->m_len
, mtod(mcopy
, caddr_t
));
3539 #endif /* IPSTEALTH */
3540 ip
->ip_ttl
-= IPTTLDEC
;
3543 #endif /* IPSTEALTH */
3546 * If forwarding packet using same interface that it came in on,
3547 * perhaps should send a redirect to sender to shortcut a hop.
3548 * Only send redirect if source is sending directly to us,
3549 * and if packet was not source routed (or has any options).
3550 * Also, don't send redirect if forwarding using a default route
3551 * or a route modified by a redirect.
3554 if (rt
->rt_ifp
== m
->m_pkthdr
.rcvif
&&
3555 !(rt
->rt_flags
& (RTF_DYNAMIC
| RTF_MODIFIED
)) &&
3556 satosin(rt_key(rt
))->sin_addr
.s_addr
!= INADDR_ANY
&&
3557 ipsendredirects
&& !srcrt
&& rt
->rt_ifa
!= NULL
) {
3558 struct in_ifaddr
*ia
= (struct in_ifaddr
*)rt
->rt_ifa
;
3559 u_int32_t src
= ntohl(ip
->ip_src
.s_addr
);
3561 /* Become a regular mutex */
3562 RT_CONVERT_LOCK(rt
);
3563 IFA_LOCK_SPIN(&ia
->ia_ifa
);
3564 if ((src
& ia
->ia_subnetmask
) == ia
->ia_subnet
) {
3565 if (rt
->rt_flags
& RTF_GATEWAY
) {
3566 dest
= satosin(rt
->rt_gateway
)->sin_addr
.s_addr
;
3568 dest
= pkt_dst
.s_addr
;
3571 * Router requirements says to only send
3574 type
= ICMP_REDIRECT
;
3575 code
= ICMP_REDIRECT_HOST
;
3578 printf("redirect (%d) to %lx\n", code
,
3583 IFA_UNLOCK(&ia
->ia_ifa
);
3588 /* Mark this packet as being forwarded from another interface */
3589 m
->m_pkthdr
.pkt_flags
|= PKTF_FORWARDED
;
3592 error
= ip_output(m
, NULL
, &fwd_rt
, IP_FORWARDING
| IP_OUTARGS
,
3595 /* Refresh rt since the route could have changed while in IP */
3599 OSAddAtomic(1, &ipstat
.ips_cantforward
);
3602 * Increment stats on the source interface; the ones
3603 * for destination interface has been taken care of
3604 * during output above by virtue of PKTF_FORWARDED.
3606 rcvifp
->if_fpackets
++;
3607 rcvifp
->if_fbytes
+= len
;
3609 OSAddAtomic(1, &ipstat
.ips_forward
);
3611 OSAddAtomic(1, &ipstat
.ips_redirectsent
);
3613 if (mcopy
!= NULL
) {
3615 * If we didn't have to go thru ipflow and
3616 * the packet was successfully consumed by
3617 * ip_output, the mcopy is rather a waste;
3618 * this could be further optimized.
3625 if (mcopy
== NULL
) {
3630 case 0: /* forwarded, but need redirect */
3631 /* type, code set above */
3634 case ENETUNREACH
: /* shouldn't happen, checked above */
3639 type
= ICMP_UNREACH
;
3640 code
= ICMP_UNREACH_HOST
;
3644 type
= ICMP_UNREACH
;
3645 code
= ICMP_UNREACH_NEEDFRAG
;
3651 if (rt
->rt_ifp
!= NULL
) {
3652 nextmtu
= rt
->rt_ifp
->if_mtu
;
3662 * If the packet is routed over IPsec tunnel, tell the
3663 * originator the tunnel MTU.
3664 * tunnel MTU = if MTU - sizeof(IP) - ESP/AH hdrsiz
3667 sp
= ipsec4_getpolicybyaddr(mcopy
, IPSEC_DIR_OUTBOUND
,
3668 IP_FORWARDING
, &ipsecerror
);
3675 * find the correct route for outer IPv4
3676 * header, compute tunnel MTU.
3680 if (sp
->req
!= NULL
&&
3681 sp
->req
->saidx
.mode
== IPSEC_MODE_TUNNEL
) {
3682 struct secasindex saidx
;
3683 struct secasvar
*sav
;
3688 /* count IPsec header size */
3689 ipsechdr
= ipsec_hdrsiz(sp
);
3691 ipm
= mtod(mcopy
, struct ip
*);
3692 bcopy(&sp
->req
->saidx
, &saidx
, sizeof(saidx
));
3693 saidx
.mode
= sp
->req
->saidx
.mode
;
3694 saidx
.reqid
= sp
->req
->saidx
.reqid
;
3695 sin
= SIN(&saidx
.src
);
3696 if (sin
->sin_len
== 0) {
3697 sin
->sin_len
= sizeof(*sin
);
3698 sin
->sin_family
= AF_INET
;
3699 sin
->sin_port
= IPSEC_PORT_ANY
;
3700 bcopy(&ipm
->ip_src
, &sin
->sin_addr
,
3701 sizeof(sin
->sin_addr
));
3703 sin
= SIN(&saidx
.dst
);
3704 if (sin
->sin_len
== 0) {
3705 sin
->sin_len
= sizeof(*sin
);
3706 sin
->sin_family
= AF_INET
;
3707 sin
->sin_port
= IPSEC_PORT_ANY
;
3708 bcopy(&ipm
->ip_dst
, &sin
->sin_addr
,
3709 sizeof(sin
->sin_addr
));
3711 sav
= key_allocsa_policy(&saidx
);
3713 lck_mtx_lock(sadb_mutex
);
3714 if (sav
->sah
!= NULL
) {
3715 ro
= (struct route
*)&sav
->sah
->sa_route
;
3716 if (ro
->ro_rt
!= NULL
) {
3718 if (ro
->ro_rt
->rt_ifp
!= NULL
) {
3719 nextmtu
= ro
->ro_rt
->
3721 nextmtu
-= ipsechdr
;
3723 RT_UNLOCK(ro
->ro_rt
);
3726 key_freesav(sav
, KEY_SADB_LOCKED
);
3727 lck_mtx_unlock(sadb_mutex
);
3730 key_freesp(sp
, KEY_SADB_UNLOCKED
);
3736 * A router should not generate ICMP_SOURCEQUENCH as
3737 * required in RFC1812 Requirements for IP Version 4 Routers.
3738 * Source quench could be a big problem under DoS attacks,
3739 * or if the underlying interface is rate-limited.
3740 * Those who need source quench packets may re-enable them
3741 * via the net.inet.ip.sendsourcequench sysctl.
3743 if (ip_sendsourcequench
== 0) {
3747 type
= ICMP_SOURCEQUENCH
;
3757 if (type
== ICMP_UNREACH
&& code
== ICMP_UNREACH_NEEDFRAG
) {
3758 OSAddAtomic(1, &ipstat
.ips_cantfrag
);
3761 icmp_error(mcopy
, type
, code
, dest
, nextmtu
);
3763 ip_fwd_route_copyin(rcvifp
, &fwd_rt
);
3767 ip_savecontrol(struct inpcb
*inp
, struct mbuf
**mp
, struct ip
*ip
,
3771 if (inp
->inp_socket
->so_options
& SO_TIMESTAMP
) {
3775 mp
= sbcreatecontrol_mbuf((caddr_t
)&tv
, sizeof(tv
),
3776 SCM_TIMESTAMP
, SOL_SOCKET
, mp
);
3781 if (inp
->inp_socket
->so_options
& SO_TIMESTAMP_MONOTONIC
) {
3784 time
= mach_absolute_time();
3785 mp
= sbcreatecontrol_mbuf((caddr_t
)&time
, sizeof(time
),
3786 SCM_TIMESTAMP_MONOTONIC
, SOL_SOCKET
, mp
);
3791 if (inp
->inp_socket
->so_options
& SO_TIMESTAMP_CONTINUOUS
) {
3794 time
= mach_continuous_time();
3795 mp
= sbcreatecontrol_mbuf((caddr_t
)&time
, sizeof(time
),
3796 SCM_TIMESTAMP_CONTINUOUS
, SOL_SOCKET
, mp
);
3801 if (inp
->inp_flags
& INP_RECVDSTADDR
3803 /* Content Filter needs to see local address */
3804 || (inp
->inp_socket
->so_cfil_db
!= NULL
)
3807 mp
= sbcreatecontrol_mbuf((caddr_t
)&ip
->ip_dst
,
3808 sizeof(struct in_addr
), IP_RECVDSTADDR
, IPPROTO_IP
, mp
);
3816 * Moving these out of udp_input() made them even more broken
3817 * than they already were.
3819 /* options were tossed already */
3820 if (inp
->inp_flags
& INP_RECVOPTS
) {
3821 mp
= sbcreatecontrol_mbuf((caddr_t
)opts_deleted_above
,
3822 sizeof(struct in_addr
), IP_RECVOPTS
, IPPROTO_IP
, mp
);
3827 /* ip_srcroute doesn't do what we want here, need to fix */
3828 if (inp
->inp_flags
& INP_RECVRETOPTS
) {
3829 mp
= sbcreatecontrol_mbuf((caddr_t
)ip_srcroute(),
3830 sizeof(struct in_addr
), IP_RECVRETOPTS
, IPPROTO_IP
, mp
);
3836 if (inp
->inp_flags
& INP_RECVIF
) {
3838 uint8_t sdlbuf
[SOCK_MAXADDRLEN
+ 1];
3839 struct sockaddr_dl
*sdl2
= SDL(&sdlbuf
);
3842 * Make sure to accomodate the largest possible
3843 * size of SA(if_lladdr)->sa_len.
3845 _CASSERT(sizeof(sdlbuf
) == (SOCK_MAXADDRLEN
+ 1));
3847 ifnet_head_lock_shared();
3848 if ((ifp
= m
->m_pkthdr
.rcvif
) != NULL
&&
3849 ifp
->if_index
&& (ifp
->if_index
<= if_index
)) {
3850 struct ifaddr
*ifa
= ifnet_addrs
[ifp
->if_index
- 1];
3851 struct sockaddr_dl
*sdp
;
3853 if (!ifa
|| !ifa
->ifa_addr
) {
3858 sdp
= SDL(ifa
->ifa_addr
);
3860 * Change our mind and don't try copy.
3862 if (sdp
->sdl_family
!= AF_LINK
) {
3866 /* the above _CASSERT ensures sdl_len fits in sdlbuf */
3867 bcopy(sdp
, sdl2
, sdp
->sdl_len
);
3872 offsetof(struct sockaddr_dl
, sdl_data
[0]);
3873 sdl2
->sdl_family
= AF_LINK
;
3874 sdl2
->sdl_index
= 0;
3875 sdl2
->sdl_nlen
= sdl2
->sdl_alen
= sdl2
->sdl_slen
= 0;
3878 mp
= sbcreatecontrol_mbuf((caddr_t
)sdl2
, sdl2
->sdl_len
,
3879 IP_RECVIF
, IPPROTO_IP
, mp
);
3884 if (inp
->inp_flags
& INP_RECVTTL
) {
3885 mp
= sbcreatecontrol_mbuf((caddr_t
)&ip
->ip_ttl
,
3886 sizeof(ip
->ip_ttl
), IP_RECVTTL
, IPPROTO_IP
, mp
);
3891 if (inp
->inp_socket
->so_flags
& SOF_RECV_TRAFFIC_CLASS
) {
3892 int tc
= m_get_traffic_class(m
);
3894 mp
= sbcreatecontrol_mbuf((caddr_t
)&tc
, sizeof(tc
),
3895 SO_TRAFFIC_CLASS
, SOL_SOCKET
, mp
);
3900 if (inp
->inp_flags
& INP_PKTINFO
) {
3901 struct in_pktinfo pi
;
3903 bzero(&pi
, sizeof(struct in_pktinfo
));
3904 bcopy(&ip
->ip_dst
, &pi
.ipi_addr
, sizeof(struct in_addr
));
3905 pi
.ipi_ifindex
= (m
!= NULL
&& m
->m_pkthdr
.rcvif
!= NULL
) ?
3906 m
->m_pkthdr
.rcvif
->if_index
: 0;
3908 mp
= sbcreatecontrol_mbuf((caddr_t
)&pi
,
3909 sizeof(struct in_pktinfo
), IP_RECVPKTINFO
, IPPROTO_IP
, mp
);
3914 if (inp
->inp_flags
& INP_RECVTOS
) {
3915 mp
= sbcreatecontrol_mbuf((caddr_t
)&ip
->ip_tos
,
3916 sizeof(u_char
), IP_RECVTOS
, IPPROTO_IP
, mp
);
3924 ipstat
.ips_pktdropcntrl
++;
3928 static inline u_short
3929 ip_cksum(struct mbuf
*m
, int hlen
)
3933 if (m
->m_pkthdr
.csum_flags
& CSUM_IP_CHECKED
) {
3934 sum
= !(m
->m_pkthdr
.csum_flags
& CSUM_IP_VALID
);
3935 } else if (!(m
->m_pkthdr
.rcvif
->if_flags
& IFF_LOOPBACK
) &&
3936 !(m
->m_pkthdr
.pkt_flags
& PKTF_LOOP
)) {
3938 * The packet arrived on an interface which isn't capable
3939 * of performing IP header checksum; compute it now.
3941 sum
= ip_cksum_hdr_in(m
, hlen
);
3944 m
->m_pkthdr
.csum_flags
|= (CSUM_DATA_VALID
| CSUM_PSEUDO_HDR
|
3945 CSUM_IP_CHECKED
| CSUM_IP_VALID
);
3946 m
->m_pkthdr
.csum_data
= 0xffff;
3950 OSAddAtomic(1, &ipstat
.ips_badsum
);
3957 ip_getstat SYSCTL_HANDLER_ARGS
3959 #pragma unused(oidp, arg1, arg2)
3960 if (req
->oldptr
== USER_ADDR_NULL
) {
3961 req
->oldlen
= (size_t)sizeof(struct ipstat
);
3964 return SYSCTL_OUT(req
, &ipstat
, MIN(sizeof(ipstat
), req
->oldlen
));
3968 ip_setsrcifaddr_info(struct mbuf
*m
, uint32_t src_idx
, struct in_ifaddr
*ia
)
3970 VERIFY(m
->m_flags
& M_PKTHDR
);
3973 * If the source ifaddr is specified, pick up the information
3974 * from there; otherwise just grab the passed-in ifindex as the
3975 * caller may not have the ifaddr available.
3978 m
->m_pkthdr
.pkt_flags
|= PKTF_IFAINFO
;
3979 m
->m_pkthdr
.src_ifindex
= ia
->ia_ifp
->if_index
;
3981 m
->m_pkthdr
.src_ifindex
= src_idx
;
3983 m
->m_pkthdr
.pkt_flags
|= PKTF_IFAINFO
;
3989 ip_setdstifaddr_info(struct mbuf
*m
, uint32_t dst_idx
, struct in_ifaddr
*ia
)
3991 VERIFY(m
->m_flags
& M_PKTHDR
);
3994 * If the destination ifaddr is specified, pick up the information
3995 * from there; otherwise just grab the passed-in ifindex as the
3996 * caller may not have the ifaddr available.
3999 m
->m_pkthdr
.pkt_flags
|= PKTF_IFAINFO
;
4000 m
->m_pkthdr
.dst_ifindex
= ia
->ia_ifp
->if_index
;
4002 m
->m_pkthdr
.dst_ifindex
= dst_idx
;
4004 m
->m_pkthdr
.pkt_flags
|= PKTF_IFAINFO
;
4010 ip_getsrcifaddr_info(struct mbuf
*m
, uint32_t *src_idx
, uint32_t *iaf
)
4012 VERIFY(m
->m_flags
& M_PKTHDR
);
4014 if (!(m
->m_pkthdr
.pkt_flags
& PKTF_IFAINFO
)) {
4018 if (src_idx
!= NULL
) {
4019 *src_idx
= m
->m_pkthdr
.src_ifindex
;
4030 ip_getdstifaddr_info(struct mbuf
*m
, uint32_t *dst_idx
, uint32_t *iaf
)
4032 VERIFY(m
->m_flags
& M_PKTHDR
);
4034 if (!(m
->m_pkthdr
.pkt_flags
& PKTF_IFAINFO
)) {
4038 if (dst_idx
!= NULL
) {
4039 *dst_idx
= m
->m_pkthdr
.dst_ifindex
;
4050 * Protocol input handler for IPPROTO_GRE.
4053 gre_input(struct mbuf
*m
, int off
)
4055 gre_input_func_t fn
= gre_input_func
;
4058 * If there is a registered GRE input handler, pass mbuf to it.
4061 lck_mtx_unlock(inet_domain_mutex
);
4062 m
= fn(m
, off
, (mtod(m
, struct ip
*))->ip_p
);
4063 lck_mtx_lock(inet_domain_mutex
);
4067 * If no matching tunnel that is up is found, we inject
4068 * the mbuf to raw ip socket to see if anyone picks it up.
4076 * Private KPI for PPP/PPTP.
4079 ip_gre_register_input(gre_input_func_t fn
)
4081 lck_mtx_lock(inet_domain_mutex
);
4082 gre_input_func
= fn
;
4083 lck_mtx_unlock(inet_domain_mutex
);
4088 #if (DEBUG || DEVELOPMENT)
4090 sysctl_reset_ip_input_stats SYSCTL_HANDLER_ARGS
4092 #pragma unused(arg1, arg2)
4095 i
= ip_input_measure
;
4096 error
= sysctl_handle_int(oidp
, &i
, 0, req
);
4097 if (error
|| req
->newptr
== USER_ADDR_NULL
) {
4101 if (i
< 0 || i
> 1) {
4105 if (ip_input_measure
!= i
&& i
== 1) {
4106 net_perf_initialize(&net_perf
, ip_input_measure_bins
);
4108 ip_input_measure
= i
;
4114 sysctl_ip_input_measure_bins SYSCTL_HANDLER_ARGS
4116 #pragma unused(arg1, arg2)
4120 i
= ip_input_measure_bins
;
4121 error
= sysctl_handle_quad(oidp
, &i
, 0, req
);
4122 if (error
|| req
->newptr
== USER_ADDR_NULL
) {
4126 if (!net_perf_validate_bins(i
)) {
4130 ip_input_measure_bins
= i
;
4136 sysctl_ip_input_getperf SYSCTL_HANDLER_ARGS
4138 #pragma unused(oidp, arg1, arg2)
4139 if (req
->oldptr
== USER_ADDR_NULL
) {
4140 req
->oldlen
= (size_t)sizeof(struct ipstat
);
4143 return SYSCTL_OUT(req
, &net_perf
, MIN(sizeof(net_perf
), req
->oldlen
));
4145 #endif /* (DEBUG || DEVELOPMENT) */
4148 sysctl_ip_checkinterface SYSCTL_HANDLER_ARGS
4150 #pragma unused(arg1, arg2)
4153 i
= ip_checkinterface
;
4154 error
= sysctl_handle_int(oidp
, &i
, 0, req
);
4155 if (error
!= 0 || req
->newptr
== USER_ADDR_NULL
) {
4160 case IP_CHECKINTERFACE_WEAK_ES
:
4161 case IP_CHECKINTERFACE_HYBRID_ES
:
4162 case IP_CHECKINTERFACE_STRONG_ES
:
4163 if (ip_checkinterface
!= i
) {
4164 ip_checkinterface
= i
;
4165 os_log(OS_LOG_DEFAULT
, "%s: ip_checkinterface is now %d\n",
4166 __func__
, ip_checkinterface
);