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/ip_fw.h>
120 #include <netinet/ip_divert.h>
121 #include <netinet/kpi_ipfilter_var.h>
122 #include <netinet/udp.h>
123 #include <netinet/udp_var.h>
124 #include <netinet/bootp.h>
125 #include <netinet/lro_ext.h>
128 #include <netinet/ip_dummynet.h>
129 #endif /* DUMMYNET */
132 #include <security/mac_framework.h>
133 #endif /* CONFIG_MACF_NET */
136 #include <netinet6/ipsec.h>
137 #include <netkey/key.h>
142 #define DBG_LAYER_BEG NETDBG_CODE(DBG_NETIP, 0)
143 #define DBG_LAYER_END NETDBG_CODE(DBG_NETIP, 2)
144 #define DBG_FNC_IP_INPUT NETDBG_CODE(DBG_NETIP, (2 << 8))
147 extern int ipsec_bypass
;
148 extern lck_mtx_t
*sadb_mutex
;
150 lck_grp_t
*sadb_stat_mutex_grp
;
151 lck_grp_attr_t
*sadb_stat_mutex_grp_attr
;
152 lck_attr_t
*sadb_stat_mutex_attr
;
153 decl_lck_mtx_data(, sadb_stat_mutex_data
);
154 lck_mtx_t
*sadb_stat_mutex
= &sadb_stat_mutex_data
;
159 static int frag_timeout_run
; /* frag timer is scheduled to run */
160 static void frag_timeout(void *);
161 static void frag_sched_timeout(void);
163 static struct ipq
*ipq_alloc(int);
164 static void ipq_free(struct ipq
*);
165 static void ipq_updateparams(void);
166 static void ip_input_second_pass(struct mbuf
*, struct ifnet
*,
167 u_int32_t
, int, int, struct ip_fw_in_args
*, int);
169 decl_lck_mtx_data(static, ipqlock
);
170 static lck_attr_t
*ipqlock_attr
;
171 static lck_grp_t
*ipqlock_grp
;
172 static lck_grp_attr_t
*ipqlock_grp_attr
;
174 /* Packet reassembly stuff */
175 #define IPREASS_NHASH_LOG2 6
176 #define IPREASS_NHASH (1 << IPREASS_NHASH_LOG2)
177 #define IPREASS_HMASK (IPREASS_NHASH - 1)
178 #define IPREASS_HASH(x, y) \
179 (((((x) & 0xF) | ((((x) >> 8) & 0xF) << 4)) ^ (y)) & IPREASS_HMASK)
181 /* IP fragment reassembly queues (protected by ipqlock) */
182 static TAILQ_HEAD(ipqhead
, ipq
) ipq
[IPREASS_NHASH
]; /* ip reassembly queues */
183 static int maxnipq
; /* max packets in reass queues */
184 static u_int32_t maxfragsperpacket
; /* max frags/packet in reass queues */
185 static u_int32_t nipq
; /* # of packets in reass queues */
186 static u_int32_t ipq_limit
; /* ipq allocation limit */
187 static u_int32_t ipq_count
; /* current # of allocated ipq's */
189 static int sysctl_ipforwarding SYSCTL_HANDLER_ARGS
;
190 static int sysctl_maxnipq SYSCTL_HANDLER_ARGS
;
191 static int sysctl_maxfragsperpacket SYSCTL_HANDLER_ARGS
;
193 #if (DEBUG || DEVELOPMENT)
194 static int sysctl_reset_ip_input_stats SYSCTL_HANDLER_ARGS
;
195 static int sysctl_ip_input_measure_bins SYSCTL_HANDLER_ARGS
;
196 static int sysctl_ip_input_getperf SYSCTL_HANDLER_ARGS
;
197 #endif /* (DEBUG || DEVELOPMENT) */
199 int ipforwarding
= 0;
200 SYSCTL_PROC(_net_inet_ip
, IPCTL_FORWARDING
, forwarding
,
201 CTLTYPE_INT
| CTLFLAG_RW
| CTLFLAG_LOCKED
, &ipforwarding
, 0,
202 sysctl_ipforwarding
, "I", "Enable IP forwarding between interfaces");
204 static int ipsendredirects
= 1; /* XXX */
205 SYSCTL_INT(_net_inet_ip
, IPCTL_SENDREDIRECTS
, redirect
,
206 CTLFLAG_RW
| CTLFLAG_LOCKED
, &ipsendredirects
, 0,
207 "Enable sending IP redirects");
209 int ip_defttl
= IPDEFTTL
;
210 SYSCTL_INT(_net_inet_ip
, IPCTL_DEFTTL
, ttl
, CTLFLAG_RW
| CTLFLAG_LOCKED
,
211 &ip_defttl
, 0, "Maximum TTL on IP packets");
213 static int ip_dosourceroute
= 0;
214 SYSCTL_INT(_net_inet_ip
, IPCTL_SOURCEROUTE
, sourceroute
,
215 CTLFLAG_RW
| CTLFLAG_LOCKED
, &ip_dosourceroute
, 0,
216 "Enable forwarding source routed IP packets");
218 static int ip_acceptsourceroute
= 0;
219 SYSCTL_INT(_net_inet_ip
, IPCTL_ACCEPTSOURCEROUTE
, accept_sourceroute
,
220 CTLFLAG_RW
| CTLFLAG_LOCKED
, &ip_acceptsourceroute
, 0,
221 "Enable accepting source routed IP packets");
223 static int ip_sendsourcequench
= 0;
224 SYSCTL_INT(_net_inet_ip
, OID_AUTO
, sendsourcequench
,
225 CTLFLAG_RW
| CTLFLAG_LOCKED
, &ip_sendsourcequench
, 0,
226 "Enable the transmission of source quench packets");
228 SYSCTL_PROC(_net_inet_ip
, OID_AUTO
, maxfragpackets
,
229 CTLTYPE_INT
| CTLFLAG_RW
| CTLFLAG_LOCKED
, &maxnipq
, 0, sysctl_maxnipq
,
230 "I", "Maximum number of IPv4 fragment reassembly queue entries");
232 SYSCTL_UINT(_net_inet_ip
, OID_AUTO
, fragpackets
, CTLFLAG_RD
| CTLFLAG_LOCKED
,
233 &nipq
, 0, "Current number of IPv4 fragment reassembly queue entries");
235 SYSCTL_PROC(_net_inet_ip
, OID_AUTO
, maxfragsperpacket
,
236 CTLTYPE_INT
| CTLFLAG_RW
| CTLFLAG_LOCKED
, &maxfragsperpacket
, 0,
237 sysctl_maxfragsperpacket
, "I",
238 "Maximum number of IPv4 fragments allowed per packet");
240 static uint32_t ip_adj_clear_hwcksum
= 0;
241 SYSCTL_UINT(_net_inet_ip
, OID_AUTO
, adj_clear_hwcksum
,
242 CTLFLAG_RW
| CTLFLAG_LOCKED
, &ip_adj_clear_hwcksum
, 0,
243 "Invalidate hwcksum info when adjusting length");
245 static uint32_t ip_adj_partial_sum
= 1;
246 SYSCTL_UINT(_net_inet_ip
, OID_AUTO
, adj_partial_sum
,
247 CTLFLAG_RW
| CTLFLAG_LOCKED
, &ip_adj_partial_sum
, 0,
248 "Perform partial sum adjustment of trailing bytes at IP layer");
251 * ip_checkinterface controls the receive side of the models for multihoming
252 * that are discussed in RFC 1122.
254 * ip_checkinterface values are:
255 * IP_CHECKINTERFACE_WEAK_ES:
256 * This corresponds to the Weak End-System model where incoming packets from
257 * any interface are accepted provided the destination address of the incoming packet
258 * is assigned to some interface.
260 * IP_CHECKINTERFACE_HYBRID_ES:
261 * The Hybrid End-System model use the Strong End-System for tunnel interfaces
262 * (ipsec and utun) and the weak End-System model for other interfaces families.
263 * This prevents a rogue middle box to probe for signs of TCP connections
264 * that use the tunnel interface.
266 * IP_CHECKINTERFACE_STRONG_ES:
267 * The Strong model model requires the packet arrived on an interface that
268 * is assigned the destination address of the packet.
270 * Since the routing table and transmit implementation do not implement the Strong ES model,
271 * setting this to a value different from IP_CHECKINTERFACE_WEAK_ES may lead to unexpected results.
273 * When forwarding is enabled, the system reverts to the Weak ES model as a router
274 * is expected by design to receive packets from several interfaces to the same address.
276 * XXX - ip_checkinterface currently must be set to IP_CHECKINTERFACE_WEAK_ES if you use ipnat
277 * to translate the destination address to another local interface.
279 * XXX - ip_checkinterface must be set to IP_CHECKINTERFACE_WEAK_ES if you add IP aliases
280 * to the loopback interface instead of the interface where the
281 * packets for those addresses are received.
283 #define IP_CHECKINTERFACE_WEAK_ES 0
284 #define IP_CHECKINTERFACE_HYBRID_ES 1
285 #define IP_CHECKINTERFACE_STRONG_ES 2
287 static int ip_checkinterface
= IP_CHECKINTERFACE_HYBRID_ES
;
289 static int sysctl_ip_checkinterface SYSCTL_HANDLER_ARGS
;
290 SYSCTL_PROC(_net_inet_ip
, OID_AUTO
, check_interface
,
291 CTLTYPE_INT
| CTLFLAG_RW
| CTLFLAG_LOCKED
,
292 0, 0, sysctl_ip_checkinterface
, "I", "Verify packet arrives on correct interface");
294 #if (DEBUG || DEVELOPMENT)
295 #define IP_CHECK_IF_DEBUG 1
297 #define IP_CHECK_IF_DEBUG 0
298 #endif /* (DEBUG || DEVELOPMENT) */
299 static int ip_checkinterface_debug
= IP_CHECK_IF_DEBUG
;
300 SYSCTL_INT(_net_inet_ip
, OID_AUTO
, checkinterface_debug
, CTLFLAG_RW
| CTLFLAG_LOCKED
,
301 &ip_checkinterface_debug
, IP_CHECK_IF_DEBUG
, "");
303 static int ip_chaining
= 1;
304 SYSCTL_INT(_net_inet_ip
, OID_AUTO
, rx_chaining
, CTLFLAG_RW
| CTLFLAG_LOCKED
,
305 &ip_chaining
, 1, "Do receive side ip address based chaining");
307 static int ip_chainsz
= 6;
308 SYSCTL_INT(_net_inet_ip
, OID_AUTO
, rx_chainsz
, CTLFLAG_RW
| CTLFLAG_LOCKED
,
309 &ip_chainsz
, 1, "IP receive side max chaining");
311 #if (DEBUG || DEVELOPMENT)
312 static int ip_input_measure
= 0;
313 SYSCTL_PROC(_net_inet_ip
, OID_AUTO
, input_perf
,
314 CTLTYPE_INT
| CTLFLAG_RW
| CTLFLAG_LOCKED
,
315 &ip_input_measure
, 0, sysctl_reset_ip_input_stats
, "I", "Do time measurement");
317 static uint64_t ip_input_measure_bins
= 0;
318 SYSCTL_PROC(_net_inet_ip
, OID_AUTO
, input_perf_bins
,
319 CTLTYPE_QUAD
| CTLFLAG_RW
| CTLFLAG_LOCKED
, &ip_input_measure_bins
, 0,
320 sysctl_ip_input_measure_bins
, "I",
321 "bins for chaining performance data histogram");
323 static net_perf_t net_perf
;
324 SYSCTL_PROC(_net_inet_ip
, OID_AUTO
, input_perf_data
,
325 CTLTYPE_STRUCT
| CTLFLAG_RD
| CTLFLAG_LOCKED
,
326 0, 0, sysctl_ip_input_getperf
, "S,net_perf",
327 "IP input performance data (struct net_perf, net/net_perf.h)");
328 #endif /* (DEBUG || DEVELOPMENT) */
331 static int ipprintfs
= 0;
334 struct protosw
*ip_protox
[IPPROTO_MAX
];
336 static lck_grp_attr_t
*in_ifaddr_rwlock_grp_attr
;
337 static lck_grp_t
*in_ifaddr_rwlock_grp
;
338 static lck_attr_t
*in_ifaddr_rwlock_attr
;
339 decl_lck_rw_data(, in_ifaddr_rwlock_data
);
340 lck_rw_t
*in_ifaddr_rwlock
= &in_ifaddr_rwlock_data
;
342 /* Protected by in_ifaddr_rwlock */
343 struct in_ifaddrhead in_ifaddrhead
; /* first inet address */
344 struct in_ifaddrhashhead
*in_ifaddrhashtbl
; /* inet addr hash table */
346 #define INADDR_NHASH 61
347 static u_int32_t inaddr_nhash
; /* hash table size */
348 static u_int32_t inaddr_hashp
; /* next largest prime */
350 static int ip_getstat SYSCTL_HANDLER_ARGS
;
351 struct ipstat ipstat
;
352 SYSCTL_PROC(_net_inet_ip
, IPCTL_STATS
, stats
,
353 CTLTYPE_STRUCT
| CTLFLAG_RD
| CTLFLAG_LOCKED
,
354 0, 0, ip_getstat
, "S,ipstat",
355 "IP statistics (struct ipstat, netinet/ip_var.h)");
358 SYSCTL_INT(_net_inet_ip
, IPCTL_DEFMTU
, mtu
, CTLFLAG_RW
| CTLFLAG_LOCKED
,
359 &ip_mtu
, 0, "Default MTU");
360 #endif /* IPCTL_DEFMTU */
363 static int ipstealth
= 0;
364 SYSCTL_INT(_net_inet_ip
, OID_AUTO
, stealth
, CTLFLAG_RW
| CTLFLAG_LOCKED
,
366 #endif /* IPSTEALTH */
370 ip_fw_chk_t
*ip_fw_chk_ptr
;
374 #endif /* IPFIREWALL */
377 ip_dn_io_t
*ip_dn_io_ptr
;
378 #endif /* DUMMYNET */
380 SYSCTL_NODE(_net_inet_ip
, OID_AUTO
, linklocal
,
381 CTLFLAG_RW
| CTLFLAG_LOCKED
, 0, "link local");
383 struct ip_linklocal_stat ip_linklocal_stat
;
384 SYSCTL_STRUCT(_net_inet_ip_linklocal
, OID_AUTO
, stat
,
385 CTLFLAG_RD
| CTLFLAG_LOCKED
, &ip_linklocal_stat
, ip_linklocal_stat
,
386 "Number of link local packets with TTL less than 255");
388 SYSCTL_NODE(_net_inet_ip_linklocal
, OID_AUTO
, in
,
389 CTLFLAG_RW
| CTLFLAG_LOCKED
, 0, "link local input");
391 int ip_linklocal_in_allowbadttl
= 1;
392 SYSCTL_INT(_net_inet_ip_linklocal_in
, OID_AUTO
, allowbadttl
,
393 CTLFLAG_RW
| CTLFLAG_LOCKED
, &ip_linklocal_in_allowbadttl
, 0,
394 "Allow incoming link local packets with TTL less than 255");
398 * We need to save the IP options in case a protocol wants to respond
399 * to an incoming packet over the same route if the packet got here
400 * using IP source routing. This allows connection establishment and
401 * maintenance when the remote end is on a network that is not known
404 static int ip_nhops
= 0;
405 static struct ip_srcrt
{
406 struct in_addr dst
; /* final destination */
407 char nop
; /* one NOP to align */
408 char srcopt
[IPOPT_OFFSET
+ 1]; /* OPTVAL, OLEN and OFFSET */
409 struct in_addr route
[MAX_IPOPTLEN
/ sizeof(struct in_addr
)];
412 static void in_ifaddrhashtbl_init(void);
413 static void save_rte(u_char
*, struct in_addr
);
414 static int ip_dooptions(struct mbuf
*, int, struct sockaddr_in
*);
415 static void ip_forward(struct mbuf
*, int, struct sockaddr_in
*);
416 static void frag_freef(struct ipqhead
*, struct ipq
*);
419 static struct mbuf
*ip_reass(struct mbuf
*, u_int32_t
*, u_int16_t
*);
420 #else /* !IPDIVERT_44 */
421 static struct mbuf
*ip_reass(struct mbuf
*, u_int16_t
*, u_int16_t
*);
422 #endif /* !IPDIVERT_44 */
423 #else /* !IPDIVERT */
424 static struct mbuf
*ip_reass(struct mbuf
*);
425 #endif /* !IPDIVERT */
426 static void ip_fwd_route_copyout(struct ifnet
*, struct route
*);
427 static void ip_fwd_route_copyin(struct ifnet
*, struct route
*);
428 static inline u_short
ip_cksum(struct mbuf
*, int);
430 int ip_use_randomid
= 1;
431 SYSCTL_INT(_net_inet_ip
, OID_AUTO
, random_id
, CTLFLAG_RW
| CTLFLAG_LOCKED
,
432 &ip_use_randomid
, 0, "Randomize IP packets IDs");
435 * On platforms which require strict alignment (currently for anything but
436 * i386 or x86_64), check if the IP header pointer is 32-bit aligned; if not,
437 * copy the contents of the mbuf chain into a new chain, and free the original
438 * one. Create some head room in the first mbuf of the new chain, in case
439 * it's needed later on.
441 #if defined(__i386__) || defined(__x86_64__)
442 #define IP_HDR_ALIGNMENT_FIXUP(_m, _ifp, _action) do { } while (0)
443 #else /* !__i386__ && !__x86_64__ */
444 #define IP_HDR_ALIGNMENT_FIXUP(_m, _ifp, _action) do { \
445 if (!IP_HDR_ALIGNED_P(mtod(_m, caddr_t))) { \
447 struct ifnet *__ifp = (_ifp); \
448 atomic_add_64(&(__ifp)->if_alignerrs, 1); \
449 if (((_m)->m_flags & M_PKTHDR) && \
450 (_m)->m_pkthdr.pkt_hdr != NULL) \
451 (_m)->m_pkthdr.pkt_hdr = NULL; \
452 _n = m_defrag_offset(_m, max_linkhdr, M_NOWAIT); \
454 atomic_add_32(&ipstat.ips_toosmall, 1); \
459 VERIFY(_n != (_m)); \
464 #endif /* !__i386__ && !__x86_64__ */
467 typedef enum ip_check_if_result
{
468 IP_CHECK_IF_NONE
= 0,
469 IP_CHECK_IF_OURS
= 1,
470 IP_CHECK_IF_DROP
= 2,
471 IP_CHECK_IF_FORWARD
= 3
472 } ip_check_if_result_t
;
474 static ip_check_if_result_t
ip_input_check_interface(struct mbuf
**, struct ip
*, struct ifnet
*);
477 * GRE input handler function, settable via ip_gre_register_input() for PPTP.
479 static gre_input_func_t gre_input_func
;
482 ip_init_delayed(void)
486 struct sockaddr_in
*sin
;
488 bzero(&ifr
, sizeof(ifr
));
489 strlcpy(ifr
.ifr_name
, "lo0", sizeof(ifr
.ifr_name
));
490 sin
= (struct sockaddr_in
*)(void *)&ifr
.ifr_addr
;
491 sin
->sin_len
= sizeof(struct sockaddr_in
);
492 sin
->sin_family
= AF_INET
;
493 sin
->sin_addr
.s_addr
= htonl(INADDR_LOOPBACK
);
494 error
= in_control(NULL
, SIOCSIFADDR
, (caddr_t
)&ifr
, lo_ifp
, kernproc
);
496 printf("%s: failed to initialise lo0's address, error=%d\n",
502 * IP initialization: fill in IP protocol switch table.
503 * All protocols not implemented in kernel go to raw IP protocol handler.
506 ip_init(struct protosw
*pp
, struct domain
*dp
)
508 static int ip_initialized
= 0;
513 domain_proto_mtx_lock_assert_held();
514 VERIFY((pp
->pr_flags
& (PR_INITIALIZED
| PR_ATTACHED
)) == PR_ATTACHED
);
516 /* ipq_alloc() uses mbufs for IP fragment queue structures */
517 _CASSERT(sizeof(struct ipq
) <= _MLEN
);
520 * Some ioctls (e.g. SIOCAIFADDR) use ifaliasreq struct, which is
521 * interchangeable with in_aliasreq; they must have the same size.
523 _CASSERT(sizeof(struct ifaliasreq
) == sizeof(struct in_aliasreq
));
525 if (ip_initialized
) {
532 in_ifaddr_rwlock_grp_attr
= lck_grp_attr_alloc_init();
533 in_ifaddr_rwlock_grp
= lck_grp_alloc_init("in_ifaddr_rwlock",
534 in_ifaddr_rwlock_grp_attr
);
535 in_ifaddr_rwlock_attr
= lck_attr_alloc_init();
536 lck_rw_init(in_ifaddr_rwlock
, in_ifaddr_rwlock_grp
,
537 in_ifaddr_rwlock_attr
);
539 TAILQ_INIT(&in_ifaddrhead
);
540 in_ifaddrhashtbl_init();
544 pr
= pffindproto_locked(PF_INET
, IPPROTO_RAW
, SOCK_RAW
);
546 panic("%s: Unable to find [PF_INET,IPPROTO_RAW,SOCK_RAW]\n",
551 /* Initialize the entire ip_protox[] array to IPPROTO_RAW. */
552 for (i
= 0; i
< IPPROTO_MAX
; i
++) {
556 * Cycle through IP protocols and put them into the appropriate place
557 * in ip_protox[], skipping protocols IPPROTO_{IP,RAW}.
559 VERIFY(dp
== inetdomain
&& dp
->dom_family
== PF_INET
);
560 TAILQ_FOREACH(pr
, &dp
->dom_protosw
, pr_entry
) {
561 VERIFY(pr
->pr_domain
== dp
);
562 if (pr
->pr_protocol
!= 0 && pr
->pr_protocol
!= IPPROTO_RAW
) {
563 /* Be careful to only index valid IP protocols. */
564 if (pr
->pr_protocol
< IPPROTO_MAX
) {
565 ip_protox
[pr
->pr_protocol
] = pr
;
570 /* IP fragment reassembly queue lock */
571 ipqlock_grp_attr
= lck_grp_attr_alloc_init();
572 ipqlock_grp
= lck_grp_alloc_init("ipqlock", ipqlock_grp_attr
);
573 ipqlock_attr
= lck_attr_alloc_init();
574 lck_mtx_init(&ipqlock
, ipqlock_grp
, ipqlock_attr
);
576 lck_mtx_lock(&ipqlock
);
577 /* Initialize IP reassembly queue. */
578 for (i
= 0; i
< IPREASS_NHASH
; i
++) {
582 maxnipq
= nmbclusters
/ 32;
583 maxfragsperpacket
= 128; /* enough for 64k in 512 byte fragments */
585 lck_mtx_unlock(&ipqlock
);
588 ip_id
= RandomULong() ^ tv
.tv_usec
;
593 PE_parse_boot_argn("ip_checkinterface", &i
, sizeof(i
));
595 case IP_CHECKINTERFACE_WEAK_ES
:
596 case IP_CHECKINTERFACE_HYBRID_ES
:
597 case IP_CHECKINTERFACE_STRONG_ES
:
598 ip_checkinterface
= i
;
605 sadb_stat_mutex_grp_attr
= lck_grp_attr_alloc_init();
606 sadb_stat_mutex_grp
= lck_grp_alloc_init("sadb_stat",
607 sadb_stat_mutex_grp_attr
);
608 sadb_stat_mutex_attr
= lck_attr_alloc_init();
609 lck_mtx_init(sadb_stat_mutex
, sadb_stat_mutex_grp
,
610 sadb_stat_mutex_attr
);
614 net_init_add(ip_init_delayed
);
618 * Initialize IPv4 source address hash table.
621 in_ifaddrhashtbl_init(void)
625 if (in_ifaddrhashtbl
!= NULL
) {
629 PE_parse_boot_argn("inaddr_nhash", &inaddr_nhash
,
630 sizeof(inaddr_nhash
));
631 if (inaddr_nhash
== 0) {
632 inaddr_nhash
= INADDR_NHASH
;
635 MALLOC(in_ifaddrhashtbl
, struct in_ifaddrhashhead
*,
636 inaddr_nhash
* sizeof(*in_ifaddrhashtbl
),
637 M_IFADDR
, M_WAITOK
| M_ZERO
);
638 if (in_ifaddrhashtbl
== NULL
) {
639 panic("in_ifaddrhashtbl_init allocation failed");
643 * Generate the next largest prime greater than inaddr_nhash.
645 k
= (inaddr_nhash
% 2 == 0) ? inaddr_nhash
+ 1 : inaddr_nhash
+ 2;
648 for (i
= 3; i
* i
<= k
; i
+= 2) {
662 inaddr_hashval(u_int32_t key
)
665 * The hash index is the computed prime times the key modulo
666 * the hash size, as documented in "Introduction to Algorithms"
667 * (Cormen, Leiserson, Rivest).
669 if (inaddr_nhash
> 1) {
670 return (key
* inaddr_hashp
) % inaddr_nhash
;
677 ip_proto_dispatch_in_wrapper(struct mbuf
*m
, int hlen
, u_int8_t proto
)
679 ip_proto_dispatch_in(m
, hlen
, proto
, 0);
682 __private_extern__
void
683 ip_proto_dispatch_in(struct mbuf
*m
, int hlen
, u_int8_t proto
,
684 ipfilter_t inject_ipfref
)
686 struct ipfilter
*filter
;
687 int seen
= (inject_ipfref
== NULL
);
688 int changed_header
= 0;
690 void (*pr_input
)(struct mbuf
*, int len
);
692 if (!TAILQ_EMPTY(&ipv4_filters
)) {
694 TAILQ_FOREACH(filter
, &ipv4_filters
, ipf_link
) {
696 if ((struct ipfilter
*)inject_ipfref
== filter
) {
699 } else if (filter
->ipf_filter
.ipf_input
) {
702 if (changed_header
== 0) {
704 * Perform IP header alignment fixup,
705 * if needed, before passing packet
708 IP_HDR_ALIGNMENT_FIXUP(m
,
709 m
->m_pkthdr
.rcvif
, ipf_unref());
711 /* ipf_unref() already called */
717 ip
= mtod(m
, struct ip
*);
718 ip
->ip_len
= htons(ip
->ip_len
+ hlen
);
719 ip
->ip_off
= htons(ip
->ip_off
);
721 ip
->ip_sum
= ip_cksum_hdr_in(m
, hlen
);
723 result
= filter
->ipf_filter
.ipf_input(
724 filter
->ipf_filter
.cookie
, (mbuf_t
*)&m
,
726 if (result
== EJUSTRETURN
) {
740 /* Perform IP header alignment fixup (post-filters), if needed */
741 IP_HDR_ALIGNMENT_FIXUP(m
, m
->m_pkthdr
.rcvif
, return );
743 ip
= mtod(m
, struct ip
*);
745 if (changed_header
) {
746 ip
->ip_len
= ntohs(ip
->ip_len
) - hlen
;
747 ip
->ip_off
= ntohs(ip
->ip_off
);
751 * If there isn't a specific lock for the protocol
752 * we're about to call, use the generic lock for AF_INET.
753 * otherwise let the protocol deal with its own locking
755 if ((pr_input
= ip_protox
[ip
->ip_p
]->pr_input
) == NULL
) {
757 } else if (!(ip_protox
[ip
->ip_p
]->pr_flags
& PR_PROTOLOCK
)) {
758 lck_mtx_lock(inet_domain_mutex
);
760 lck_mtx_unlock(inet_domain_mutex
);
766 struct pktchain_elm
{
767 struct mbuf
*pkte_head
;
768 struct mbuf
*pkte_tail
;
769 struct in_addr pkte_saddr
;
770 struct in_addr pkte_daddr
;
773 uint32_t pkte_nbytes
;
776 typedef struct pktchain_elm pktchain_elm_t
;
778 /* Store upto PKTTBL_SZ unique flows on the stack */
782 ip_chain_insert(struct mbuf
*packet
, pktchain_elm_t
*tbl
)
787 ip
= mtod(packet
, struct ip
*);
789 /* reusing the hash function from inaddr_hashval */
790 pkttbl_idx
= inaddr_hashval(ntohs(ip
->ip_src
.s_addr
)) % PKTTBL_SZ
;
791 if (tbl
[pkttbl_idx
].pkte_head
== NULL
) {
792 tbl
[pkttbl_idx
].pkte_head
= packet
;
793 tbl
[pkttbl_idx
].pkte_saddr
.s_addr
= ip
->ip_src
.s_addr
;
794 tbl
[pkttbl_idx
].pkte_daddr
.s_addr
= ip
->ip_dst
.s_addr
;
795 tbl
[pkttbl_idx
].pkte_proto
= ip
->ip_p
;
797 if ((ip
->ip_dst
.s_addr
== tbl
[pkttbl_idx
].pkte_daddr
.s_addr
) &&
798 (ip
->ip_src
.s_addr
== tbl
[pkttbl_idx
].pkte_saddr
.s_addr
) &&
799 (ip
->ip_p
== tbl
[pkttbl_idx
].pkte_proto
)) {
804 if (tbl
[pkttbl_idx
].pkte_tail
!= NULL
) {
805 mbuf_setnextpkt(tbl
[pkttbl_idx
].pkte_tail
, packet
);
808 tbl
[pkttbl_idx
].pkte_tail
= packet
;
809 tbl
[pkttbl_idx
].pkte_npkts
+= 1;
810 tbl
[pkttbl_idx
].pkte_nbytes
+= packet
->m_pkthdr
.len
;
814 /* args is a dummy variable here for backward compatibility */
816 ip_input_second_pass_loop_tbl(pktchain_elm_t
*tbl
, struct ip_fw_in_args
*args
)
820 for (i
= 0; i
< PKTTBL_SZ
; i
++) {
821 if (tbl
[i
].pkte_head
!= NULL
) {
822 struct mbuf
*m
= tbl
[i
].pkte_head
;
823 ip_input_second_pass(m
, m
->m_pkthdr
.rcvif
, 0,
824 tbl
[i
].pkte_npkts
, tbl
[i
].pkte_nbytes
, args
, 0);
826 if (tbl
[i
].pkte_npkts
> 2) {
827 ipstat
.ips_rxc_chainsz_gt2
++;
829 if (tbl
[i
].pkte_npkts
> 4) {
830 ipstat
.ips_rxc_chainsz_gt4
++;
832 #if (DEBUG || DEVELOPMENT)
833 if (ip_input_measure
) {
834 net_perf_histogram(&net_perf
, tbl
[i
].pkte_npkts
);
836 #endif /* (DEBUG || DEVELOPMENT) */
837 tbl
[i
].pkte_head
= tbl
[i
].pkte_tail
= NULL
;
838 tbl
[i
].pkte_npkts
= 0;
839 tbl
[i
].pkte_nbytes
= 0;
840 /* no need to initialize address and protocol in tbl */
846 ip_input_cpout_args(struct ip_fw_in_args
*args
, struct ip_fw_args
*args1
,
847 boolean_t
*done_init
)
849 if (*done_init
== FALSE
) {
850 bzero(args1
, sizeof(struct ip_fw_args
));
853 args1
->fwa_next_hop
= args
->fwai_next_hop
;
854 args1
->fwa_ipfw_rule
= args
->fwai_ipfw_rule
;
855 args1
->fwa_pf_rule
= args
->fwai_pf_rule
;
856 args1
->fwa_divert_rule
= args
->fwai_divert_rule
;
860 ip_input_cpin_args(struct ip_fw_args
*args1
, struct ip_fw_in_args
*args
)
862 args
->fwai_next_hop
= args1
->fwa_next_hop
;
863 args
->fwai_ipfw_rule
= args1
->fwa_ipfw_rule
;
864 args
->fwai_pf_rule
= args1
->fwa_pf_rule
;
865 args
->fwai_divert_rule
= args1
->fwa_divert_rule
;
873 } ipinput_chain_ret_t
;
876 ip_input_update_nstat(struct ifnet
*ifp
, struct in_addr src_ip
,
877 u_int32_t packets
, u_int32_t bytes
)
880 struct rtentry
*rt
= ifnet_cached_rtlookup_inet(ifp
,
883 nstat_route_rx(rt
, packets
, bytes
, 0);
890 ip_input_dispatch_chain(struct mbuf
*m
)
892 struct mbuf
*tmp_mbuf
= m
;
893 struct mbuf
*nxt_mbuf
= NULL
;
894 struct ip
*ip
= NULL
;
897 ip
= mtod(tmp_mbuf
, struct ip
*);
898 hlen
= IP_VHL_HL(ip
->ip_vhl
) << 2;
899 while (tmp_mbuf
!= NULL
) {
900 nxt_mbuf
= mbuf_nextpkt(tmp_mbuf
);
901 mbuf_setnextpkt(tmp_mbuf
, NULL
);
903 if ((sw_lro
) && (ip
->ip_p
== IPPROTO_TCP
)) {
904 tmp_mbuf
= tcp_lro(tmp_mbuf
, hlen
);
907 ip_proto_dispatch_in(tmp_mbuf
, hlen
, ip
->ip_p
, 0);
911 ip
= mtod(tmp_mbuf
, struct ip
*);
912 /* first mbuf of chain already has adjusted ip_len */
913 hlen
= IP_VHL_HL(ip
->ip_vhl
) << 2;
920 ip_input_setdst_chain(struct mbuf
*m
, uint32_t ifindex
, struct in_ifaddr
*ia
)
922 struct mbuf
*tmp_mbuf
= m
;
924 while (tmp_mbuf
!= NULL
) {
925 ip_setdstifaddr_info(tmp_mbuf
, ifindex
, ia
);
926 tmp_mbuf
= mbuf_nextpkt(tmp_mbuf
);
931 ip_input_adjust(struct mbuf
*m
, struct ip
*ip
, struct ifnet
*inifp
)
933 boolean_t adjust
= TRUE
;
935 ASSERT(m_pktlen(m
) > ip
->ip_len
);
938 * Invalidate hardware checksum info if ip_adj_clear_hwcksum
939 * is set; useful to handle buggy drivers. Note that this
940 * should not be enabled by default, as we may get here due
941 * to link-layer padding.
943 if (ip_adj_clear_hwcksum
&&
944 (m
->m_pkthdr
.csum_flags
& CSUM_DATA_VALID
) &&
945 !(inifp
->if_flags
& IFF_LOOPBACK
) &&
946 !(m
->m_pkthdr
.pkt_flags
& PKTF_LOOP
)) {
947 m
->m_pkthdr
.csum_flags
&= ~CSUM_DATA_VALID
;
948 m
->m_pkthdr
.csum_data
= 0;
949 ipstat
.ips_adj_hwcsum_clr
++;
953 * If partial checksum information is available, subtract
954 * out the partial sum of postpended extraneous bytes, and
955 * update the checksum metadata accordingly. By doing it
956 * here, the upper layer transport only needs to adjust any
957 * prepended extraneous bytes (else it will do both.)
959 if (ip_adj_partial_sum
&&
960 (m
->m_pkthdr
.csum_flags
& (CSUM_DATA_VALID
| CSUM_PARTIAL
)) ==
961 (CSUM_DATA_VALID
| CSUM_PARTIAL
)) {
962 m
->m_pkthdr
.csum_rx_val
= m_adj_sum16(m
,
963 m
->m_pkthdr
.csum_rx_start
, m
->m_pkthdr
.csum_rx_start
,
964 (ip
->ip_len
- m
->m_pkthdr
.csum_rx_start
),
965 m
->m_pkthdr
.csum_rx_val
);
966 } else if ((m
->m_pkthdr
.csum_flags
&
967 (CSUM_DATA_VALID
| CSUM_PARTIAL
)) ==
968 (CSUM_DATA_VALID
| CSUM_PARTIAL
)) {
970 * If packet has partial checksum info and we decided not
971 * to subtract the partial sum of postpended extraneous
972 * bytes here (not the default case), leave that work to
973 * be handled by the other layers. For now, only TCP, UDP
974 * layers are capable of dealing with this. For all other
975 * protocols (including fragments), trim and ditch the
976 * partial sum as those layers might not implement partial
977 * checksumming (or adjustment) at all.
979 if ((ip
->ip_off
& (IP_MF
| IP_OFFMASK
)) == 0 &&
980 (ip
->ip_p
== IPPROTO_TCP
|| ip
->ip_p
== IPPROTO_UDP
)) {
983 m
->m_pkthdr
.csum_flags
&= ~CSUM_DATA_VALID
;
984 m
->m_pkthdr
.csum_data
= 0;
985 ipstat
.ips_adj_hwcsum_clr
++;
991 if (m
->m_len
== m
->m_pkthdr
.len
) {
992 m
->m_len
= ip
->ip_len
;
993 m
->m_pkthdr
.len
= ip
->ip_len
;
995 m_adj(m
, ip
->ip_len
- m
->m_pkthdr
.len
);
1001 * First pass does all essential packet validation and places on a per flow
1002 * queue for doing operations that have same outcome for all packets of a flow.
1003 * div_info is packet divert/tee info
1005 static ipinput_chain_ret_t
1006 ip_input_first_pass(struct mbuf
*m
, u_int32_t
*div_info
,
1007 struct ip_fw_in_args
*args
, int *ours
, struct mbuf
**modm
)
1010 struct ifnet
*inifp
;
1012 int retval
= IPINPUT_DOCHAIN
;
1014 struct in_addr src_ip
;
1018 #if IPFIREWALL || DUMMYNET
1021 boolean_t
delete = FALSE
;
1022 struct ip_fw_args args1
;
1023 boolean_t init
= FALSE
;
1025 ipfilter_t inject_filter_ref
= NULL
;
1028 #pragma unused (args)
1032 #pragma unused (div_info)
1033 #pragma unused (ours)
1036 #if !IPFIREWALL_FORWARD
1037 #pragma unused (ours)
1040 /* Check if the mbuf is still valid after interface filter processing */
1041 MBUF_INPUT_CHECK(m
, m
->m_pkthdr
.rcvif
);
1042 inifp
= mbuf_pkthdr_rcvif(m
);
1043 VERIFY(inifp
!= NULL
);
1045 /* Perform IP header alignment fixup, if needed */
1046 IP_HDR_ALIGNMENT_FIXUP(m
, inifp
, goto bad
);
1048 m
->m_pkthdr
.pkt_flags
&= ~PKTF_FORWARDED
;
1050 #if IPFIREWALL || DUMMYNET
1053 * Don't bother searching for tag(s) if there's none.
1055 if (SLIST_EMPTY(&m
->m_pkthdr
.tags
)) {
1056 goto ipfw_tags_done
;
1059 /* Grab info from mtags prepended to the chain */
1062 if (p
->m_tag_id
== KERNEL_MODULE_TAG_ID
) {
1064 if (p
->m_tag_type
== KERNEL_TAG_TYPE_DUMMYNET
) {
1065 struct dn_pkt_tag
*dn_tag
;
1067 dn_tag
= (struct dn_pkt_tag
*)(p
+ 1);
1068 args
->fwai_ipfw_rule
= dn_tag
->dn_ipfw_rule
;
1069 args
->fwai_pf_rule
= dn_tag
->dn_pf_rule
;
1075 if (p
->m_tag_type
== KERNEL_TAG_TYPE_DIVERT
) {
1076 struct divert_tag
*div_tag
;
1078 div_tag
= (struct divert_tag
*)(p
+ 1);
1079 args
->fwai_divert_rule
= div_tag
->cookie
;
1084 if (p
->m_tag_type
== KERNEL_TAG_TYPE_IPFORWARD
) {
1085 struct ip_fwd_tag
*ipfwd_tag
;
1087 ipfwd_tag
= (struct ip_fwd_tag
*)(p
+ 1);
1088 args
->fwai_next_hop
= ipfwd_tag
->next_hop
;
1094 p
= m_tag_next(m
, p
);
1095 m_tag_delete(m
, copy
);
1097 p
= m_tag_next(m
, p
);
1100 p
= m_tag_next(m
, p
);
1105 if (m
== NULL
|| !(m
->m_flags
& M_PKTHDR
)) {
1106 panic("ip_input no HDR");
1111 if (args
->fwai_ipfw_rule
|| args
->fwai_pf_rule
) {
1112 /* dummynet already filtered us */
1113 ip
= mtod(m
, struct ip
*);
1114 hlen
= IP_VHL_HL(ip
->ip_vhl
) << 2;
1115 inject_filter_ref
= ipf_get_inject_filter(m
);
1117 if (args
->fwai_ipfw_rule
) {
1120 #endif /* IPFIREWALL */
1121 if (args
->fwai_pf_rule
) {
1125 #endif /* DUMMYNET */
1127 #endif /* IPFIREWALL || DUMMYNET */
1130 * No need to process packet twice if we've already seen it.
1132 if (!SLIST_EMPTY(&m
->m_pkthdr
.tags
)) {
1133 inject_filter_ref
= ipf_get_inject_filter(m
);
1135 if (inject_filter_ref
!= NULL
) {
1136 ip
= mtod(m
, struct ip
*);
1137 hlen
= IP_VHL_HL(ip
->ip_vhl
) << 2;
1139 DTRACE_IP6(receive
, struct mbuf
*, m
, struct inpcb
*, NULL
,
1140 struct ip
*, ip
, struct ifnet
*, inifp
,
1141 struct ip
*, ip
, struct ip6_hdr
*, NULL
);
1143 ip
->ip_len
= ntohs(ip
->ip_len
) - hlen
;
1144 ip
->ip_off
= ntohs(ip
->ip_off
);
1145 ip_proto_dispatch_in(m
, hlen
, ip
->ip_p
, inject_filter_ref
);
1146 return IPINPUT_DONE
;
1149 if (m
->m_pkthdr
.len
< sizeof(struct ip
)) {
1150 OSAddAtomic(1, &ipstat
.ips_total
);
1151 OSAddAtomic(1, &ipstat
.ips_tooshort
);
1153 return IPINPUT_FREED
;
1156 if (m
->m_len
< sizeof(struct ip
) &&
1157 (m
= m_pullup(m
, sizeof(struct ip
))) == NULL
) {
1158 OSAddAtomic(1, &ipstat
.ips_total
);
1159 OSAddAtomic(1, &ipstat
.ips_toosmall
);
1160 return IPINPUT_FREED
;
1163 ip
= mtod(m
, struct ip
*);
1166 KERNEL_DEBUG(DBG_LAYER_BEG
, ip
->ip_dst
.s_addr
, ip
->ip_src
.s_addr
,
1167 ip
->ip_p
, ip
->ip_off
, ip
->ip_len
);
1169 if (IP_VHL_V(ip
->ip_vhl
) != IPVERSION
) {
1170 OSAddAtomic(1, &ipstat
.ips_total
);
1171 OSAddAtomic(1, &ipstat
.ips_badvers
);
1172 KERNEL_DEBUG(DBG_LAYER_END
, 0, 0, 0, 0, 0);
1174 return IPINPUT_FREED
;
1177 hlen
= IP_VHL_HL(ip
->ip_vhl
) << 2;
1178 if (hlen
< sizeof(struct ip
)) {
1179 OSAddAtomic(1, &ipstat
.ips_total
);
1180 OSAddAtomic(1, &ipstat
.ips_badhlen
);
1181 KERNEL_DEBUG(DBG_LAYER_END
, 0, 0, 0, 0, 0);
1183 return IPINPUT_FREED
;
1186 if (hlen
> m
->m_len
) {
1187 if ((m
= m_pullup(m
, hlen
)) == NULL
) {
1188 OSAddAtomic(1, &ipstat
.ips_total
);
1189 OSAddAtomic(1, &ipstat
.ips_badhlen
);
1190 KERNEL_DEBUG(DBG_LAYER_END
, 0, 0, 0, 0, 0);
1191 return IPINPUT_FREED
;
1193 ip
= mtod(m
, struct ip
*);
1197 /* 127/8 must not appear on wire - RFC1122 */
1198 if ((ntohl(ip
->ip_dst
.s_addr
) >> IN_CLASSA_NSHIFT
) == IN_LOOPBACKNET
||
1199 (ntohl(ip
->ip_src
.s_addr
) >> IN_CLASSA_NSHIFT
) == IN_LOOPBACKNET
) {
1201 * Allow for the following exceptions:
1203 * 1. If the packet was sent to loopback (i.e. rcvif
1204 * would have been set earlier at output time.)
1206 * 2. If the packet was sent out on loopback from a local
1207 * source address which belongs to a non-loopback
1208 * interface (i.e. rcvif may not necessarily be a
1209 * loopback interface, hence the test for PKTF_LOOP.)
1210 * Unlike IPv6, there is no interface scope ID, and
1211 * therefore we don't care so much about PKTF_IFINFO.
1213 if (!(inifp
->if_flags
& IFF_LOOPBACK
) &&
1214 !(m
->m_pkthdr
.pkt_flags
& PKTF_LOOP
)) {
1215 OSAddAtomic(1, &ipstat
.ips_total
);
1216 OSAddAtomic(1, &ipstat
.ips_badaddr
);
1217 KERNEL_DEBUG(DBG_LAYER_END
, 0, 0, 0, 0, 0);
1219 return IPINPUT_FREED
;
1223 /* IPv4 Link-Local Addresses as defined in RFC3927 */
1224 if ((IN_LINKLOCAL(ntohl(ip
->ip_dst
.s_addr
)) ||
1225 IN_LINKLOCAL(ntohl(ip
->ip_src
.s_addr
)))) {
1226 ip_linklocal_stat
.iplls_in_total
++;
1227 if (ip
->ip_ttl
!= MAXTTL
) {
1228 OSAddAtomic(1, &ip_linklocal_stat
.iplls_in_badttl
);
1229 /* Silently drop link local traffic with bad TTL */
1230 if (!ip_linklocal_in_allowbadttl
) {
1231 OSAddAtomic(1, &ipstat
.ips_total
);
1232 KERNEL_DEBUG(DBG_LAYER_END
, 0, 0, 0, 0, 0);
1234 return IPINPUT_FREED
;
1239 if (ip_cksum(m
, hlen
)) {
1240 OSAddAtomic(1, &ipstat
.ips_total
);
1241 KERNEL_DEBUG(DBG_LAYER_END
, 0, 0, 0, 0, 0);
1243 return IPINPUT_FREED
;
1246 DTRACE_IP6(receive
, struct mbuf
*, m
, struct inpcb
*, NULL
,
1247 struct ip
*, ip
, struct ifnet
*, inifp
,
1248 struct ip
*, ip
, struct ip6_hdr
*, NULL
);
1251 * Convert fields to host representation.
1253 #if BYTE_ORDER != BIG_ENDIAN
1257 if (ip
->ip_len
< hlen
) {
1258 OSAddAtomic(1, &ipstat
.ips_total
);
1259 OSAddAtomic(1, &ipstat
.ips_badlen
);
1260 KERNEL_DEBUG(DBG_LAYER_END
, 0, 0, 0, 0, 0);
1262 return IPINPUT_FREED
;
1265 #if BYTE_ORDER != BIG_ENDIAN
1270 * Check that the amount of data in the buffers
1271 * is as at least much as the IP header would have us expect.
1272 * Trim mbufs if longer than we expect.
1273 * Drop packet if shorter than we expect.
1275 if (m
->m_pkthdr
.len
< ip
->ip_len
) {
1276 OSAddAtomic(1, &ipstat
.ips_total
);
1277 OSAddAtomic(1, &ipstat
.ips_tooshort
);
1278 KERNEL_DEBUG(DBG_LAYER_END
, 0, 0, 0, 0, 0);
1280 return IPINPUT_FREED
;
1283 if (m
->m_pkthdr
.len
> ip
->ip_len
) {
1284 ip_input_adjust(m
, ip
, inifp
);
1287 /* for netstat route statistics */
1288 src_ip
= ip
->ip_src
;
1289 len
= m
->m_pkthdr
.len
;
1295 /* Invoke inbound packet filter */
1296 if (PF_IS_ENABLED
) {
1298 ip_input_cpout_args(args
, &args1
, &init
);
1299 ip
= mtod(m
, struct ip
*);
1300 src_ip
= ip
->ip_src
;
1303 error
= pf_af_hook(inifp
, NULL
, &m
, AF_INET
, TRUE
, &args1
);
1305 error
= pf_af_hook(inifp
, NULL
, &m
, AF_INET
, TRUE
, NULL
);
1306 #endif /* DUMMYNET */
1307 if (error
!= 0 || m
== NULL
) {
1309 panic("%s: unexpected packet %p\n",
1313 /* Already freed by callee */
1314 ip_input_update_nstat(inifp
, src_ip
, 1, len
);
1315 KERNEL_DEBUG(DBG_LAYER_END
, 0, 0, 0, 0, 0);
1316 OSAddAtomic(1, &ipstat
.ips_total
);
1317 return IPINPUT_FREED
;
1319 ip
= mtod(m
, struct ip
*);
1320 hlen
= IP_VHL_HL(ip
->ip_vhl
) << 2;
1322 ip_input_cpin_args(&args1
, args
);
1327 if (ipsec_bypass
== 0 && ipsec_gethist(m
, NULL
)) {
1328 retval
= IPINPUT_DONTCHAIN
; /* XXX scope for chaining here? */
1336 #endif /* DUMMYNET */
1338 * Check if we want to allow this packet to be processed.
1339 * Consider it to be bad if not.
1341 if (fw_enable
&& IPFW_LOADED
) {
1342 #if IPFIREWALL_FORWARD
1344 * If we've been forwarded from the output side, then
1345 * skip the firewall a second time
1347 if (args
->fwai_next_hop
) {
1349 return IPINPUT_DONTCHAIN
;
1351 #endif /* IPFIREWALL_FORWARD */
1352 ip_input_cpout_args(args
, &args1
, &init
);
1355 i
= ip_fw_chk_ptr(&args1
);
1358 if ((i
& IP_FW_PORT_DENY_FLAG
) || m
== NULL
) { /* drop */
1362 ip_input_update_nstat(inifp
, src_ip
, 1, len
);
1363 KERNEL_DEBUG(DBG_LAYER_END
, 0, 0, 0, 0, 0);
1364 OSAddAtomic(1, &ipstat
.ips_total
);
1365 return IPINPUT_FREED
;
1367 ip
= mtod(m
, struct ip
*); /* just in case m changed */
1369 ip_input_cpin_args(&args1
, args
);
1371 if (i
== 0 && args
->fwai_next_hop
== NULL
) { /* common case */
1375 if (DUMMYNET_LOADED
&& (i
& IP_FW_PORT_DYNT_FLAG
) != 0) {
1376 /* Send packet to the appropriate pipe */
1377 ip_dn_io_ptr(m
, i
& 0xffff, DN_TO_IP_IN
, &args1
,
1379 ip_input_update_nstat(inifp
, src_ip
, 1, len
);
1380 KERNEL_DEBUG(DBG_LAYER_END
, 0, 0, 0, 0, 0);
1381 OSAddAtomic(1, &ipstat
.ips_total
);
1382 return IPINPUT_FREED
;
1384 #endif /* DUMMYNET */
1386 if (i
!= 0 && (i
& IP_FW_PORT_DYNT_FLAG
) == 0) {
1387 /* Divert or tee packet */
1390 return IPINPUT_DONTCHAIN
;
1393 #if IPFIREWALL_FORWARD
1394 if (i
== 0 && args
->fwai_next_hop
!= NULL
) {
1395 retval
= IPINPUT_DONTCHAIN
;
1400 * if we get here, the packet must be dropped
1402 ip_input_update_nstat(inifp
, src_ip
, 1, len
);
1403 KERNEL_DEBUG(DBG_LAYER_END
, 0, 0, 0, 0, 0);
1405 OSAddAtomic(1, &ipstat
.ips_total
);
1406 return IPINPUT_FREED
;
1408 #endif /* IPFIREWALL */
1409 #if IPSEC | IPFIREWALL
1413 * Process options and, if not destined for us,
1414 * ship it on. ip_dooptions returns 1 when an
1415 * error was detected (causing an icmp message
1416 * to be sent and the original packet to be freed).
1418 ip_nhops
= 0; /* for source routed packets */
1420 if (hlen
> sizeof(struct ip
) &&
1421 ip_dooptions(m
, 0, args
->fwai_next_hop
)) {
1422 #else /* !IPFIREWALL */
1423 if (hlen
> sizeof(struct ip
) && ip_dooptions(m
, 0, NULL
)) {
1424 #endif /* !IPFIREWALL */
1425 ip_input_update_nstat(inifp
, src_ip
, 1, len
);
1426 KERNEL_DEBUG(DBG_LAYER_END
, 0, 0, 0, 0, 0);
1427 OSAddAtomic(1, &ipstat
.ips_total
);
1428 return IPINPUT_FREED
;
1432 * Don't chain fragmented packets as the process of determining
1433 * if it is our fragment or someone else's plus the complexity of
1434 * divert and fw args makes it harder to do chaining.
1436 if (ip
->ip_off
& ~(IP_DF
| IP_RF
)) {
1437 return IPINPUT_DONTCHAIN
;
1440 /* Allow DHCP/BootP responses through */
1441 if ((inifp
->if_eflags
& IFEF_AUTOCONFIGURING
) &&
1442 hlen
== sizeof(struct ip
) && ip
->ip_p
== IPPROTO_UDP
) {
1443 struct udpiphdr
*ui
;
1445 if (m
->m_len
< sizeof(struct udpiphdr
) &&
1446 (m
= m_pullup(m
, sizeof(struct udpiphdr
))) == NULL
) {
1447 OSAddAtomic(1, &udpstat
.udps_hdrops
);
1448 KERNEL_DEBUG(DBG_LAYER_END
, 0, 0, 0, 0, 0);
1449 OSAddAtomic(1, &ipstat
.ips_total
);
1450 return IPINPUT_FREED
;
1453 ui
= mtod(m
, struct udpiphdr
*);
1454 if (ntohs(ui
->ui_dport
) == IPPORT_BOOTPC
) {
1455 ip_setdstifaddr_info(m
, inifp
->if_index
, NULL
);
1456 return IPINPUT_DONTCHAIN
;
1460 /* Avoid chaining raw sockets as ipsec checks occur later for them */
1461 if (ip_protox
[ip
->ip_p
]->pr_flags
& PR_LASTHDR
) {
1462 return IPINPUT_DONTCHAIN
;
1466 #if !defined(__i386__) && !defined(__x86_64__)
1469 return IPINPUT_FREED
;
1474 * Because the call to m_pullup() may freem the mbuf, the function frees the mbuf packet
1475 * chain before it return IP_CHECK_IF_DROP
1477 static ip_check_if_result_t
1478 ip_input_check_interface(struct mbuf
**mp
, struct ip
*ip
, struct ifnet
*inifp
)
1480 struct mbuf
*m
= *mp
;
1481 struct in_ifaddr
*ia
= NULL
;
1482 struct in_ifaddr
*best_ia
= NULL
;
1483 struct ifnet
*match_ifp
= NULL
;
1484 ip_check_if_result_t result
= IP_CHECK_IF_NONE
;
1487 * Host broadcast and all network broadcast addresses are always a match
1489 if (ip
->ip_dst
.s_addr
== (u_int32_t
)INADDR_BROADCAST
||
1490 ip
->ip_dst
.s_addr
== INADDR_ANY
) {
1491 ip_input_setdst_chain(m
, inifp
->if_index
, NULL
);
1492 return IP_CHECK_IF_OURS
;
1496 * Check for a match in the hash bucket.
1498 lck_rw_lock_shared(in_ifaddr_rwlock
);
1499 TAILQ_FOREACH(ia
, INADDR_HASH(ip
->ip_dst
.s_addr
), ia_hash
) {
1500 if (IA_SIN(ia
)->sin_addr
.s_addr
== ip
->ip_dst
.s_addr
) {
1502 match_ifp
= best_ia
->ia_ifp
;
1504 if (ia
->ia_ifp
== inifp
|| (inifp
->if_flags
& IFF_LOOPBACK
) ||
1505 (m
->m_pkthdr
.pkt_flags
& PKTF_LOOP
)) {
1507 * A locally originated packet or packet from the loopback
1508 * interface is always an exact interface address match
1514 * Continue the loop in case there's a exact match with another
1519 if (best_ia
!= NULL
) {
1520 if (match_ifp
!= inifp
&& ipforwarding
== 0 &&
1521 ((ip_checkinterface
== IP_CHECKINTERFACE_HYBRID_ES
&&
1522 (match_ifp
->if_family
== IFNET_FAMILY_IPSEC
||
1523 match_ifp
->if_family
== IFNET_FAMILY_UTUN
)) ||
1524 ip_checkinterface
== IP_CHECKINTERFACE_STRONG_ES
)) {
1526 * Drop when interface address check is strict and forwarding
1529 result
= IP_CHECK_IF_DROP
;
1531 result
= IP_CHECK_IF_OURS
;
1532 ip_input_setdst_chain(m
, 0, best_ia
);
1535 lck_rw_done(in_ifaddr_rwlock
);
1537 if (result
== IP_CHECK_IF_NONE
&& (inifp
->if_flags
& IFF_BROADCAST
)) {
1539 * Check for broadcast addresses.
1541 * Only accept broadcast packets that arrive via the matching
1542 * interface. Reception of forwarded directed broadcasts would be
1543 * handled via ip_forward() and ether_frameout() with the loopback
1544 * into the stack for SIMPLEX interfaces handled by ether_frameout().
1548 ifnet_lock_shared(inifp
);
1549 TAILQ_FOREACH(ifa
, &inifp
->if_addrhead
, ifa_link
) {
1550 if (ifa
->ifa_addr
->sa_family
!= AF_INET
) {
1554 if (satosin(&ia
->ia_broadaddr
)->sin_addr
.s_addr
== ip
->ip_dst
.s_addr
||
1555 ia
->ia_netbroadcast
.s_addr
== ip
->ip_dst
.s_addr
) {
1556 ip_input_setdst_chain(m
, 0, ia
);
1557 result
= IP_CHECK_IF_OURS
;
1562 ifnet_lock_done(inifp
);
1565 /* Allow DHCP/BootP responses through */
1566 if (result
== IP_CHECK_IF_NONE
&& (inifp
->if_eflags
& IFEF_AUTOCONFIGURING
) &&
1567 ip
->ip_p
== IPPROTO_UDP
&& (IP_VHL_HL(ip
->ip_vhl
) << 2) == sizeof(struct ip
)) {
1568 struct udpiphdr
*ui
;
1570 if (m
->m_len
< sizeof(struct udpiphdr
)) {
1571 if ((m
= m_pullup(m
, sizeof(struct udpiphdr
))) == NULL
) {
1572 OSAddAtomic(1, &udpstat
.udps_hdrops
);
1574 return IP_CHECK_IF_DROP
;
1577 * m_pullup can return a different mbuf
1580 ip
= mtod(m
, struct ip
*);
1582 ui
= mtod(m
, struct udpiphdr
*);
1583 if (ntohs(ui
->ui_dport
) == IPPORT_BOOTPC
) {
1584 ASSERT(m
->m_nextpkt
== NULL
);
1585 ip_setdstifaddr_info(m
, inifp
->if_index
, NULL
);
1586 result
= IP_CHECK_IF_OURS
;
1591 if (result
== IP_CHECK_IF_NONE
) {
1592 if (ipforwarding
== 0) {
1593 result
= IP_CHECK_IF_DROP
;
1595 result
= IP_CHECK_IF_FORWARD
;
1596 ip_input_setdst_chain(m
, inifp
->if_index
, NULL
);
1600 if (result
== IP_CHECK_IF_OURS
&& match_ifp
!= inifp
) {
1601 ipstat
.ips_rcv_if_weak_match
++;
1603 /* Logging is too noisy when forwarding is enabled */
1604 if (ip_checkinterface_debug
!= 0 && ipforwarding
== 0) {
1605 char src_str
[MAX_IPv4_STR_LEN
];
1606 char dst_str
[MAX_IPv4_STR_LEN
];
1608 inet_ntop(AF_INET
, &ip
->ip_src
, src_str
, sizeof(src_str
));
1609 inet_ntop(AF_INET
, &ip
->ip_dst
, dst_str
, sizeof(dst_str
));
1610 os_log_info(OS_LOG_DEFAULT
,
1611 "%s: weak ES interface match to %s for packet from %s to %s proto %u received via %s",
1612 __func__
, best_ia
->ia_ifp
->if_xname
, src_str
, dst_str
, ip
->ip_p
, inifp
->if_xname
);
1614 } else if (result
== IP_CHECK_IF_DROP
) {
1615 if (ip_checkinterface_debug
> 0) {
1616 char src_str
[MAX_IPv4_STR_LEN
];
1617 char dst_str
[MAX_IPv4_STR_LEN
];
1619 inet_ntop(AF_INET
, &ip
->ip_src
, src_str
, sizeof(src_str
));
1620 inet_ntop(AF_INET
, &ip
->ip_dst
, dst_str
, sizeof(dst_str
));
1621 os_log_info(OS_LOG_DEFAULT
,
1622 "%s: no interface match for packet from %s to %s proto %u received via %s",
1623 __func__
, src_str
, dst_str
, ip
->ip_p
, inifp
->if_xname
);
1625 struct mbuf
*tmp_mbuf
= m
;
1626 while (tmp_mbuf
!= NULL
) {
1627 ipstat
.ips_rcv_if_no_match
++;
1628 tmp_mbuf
= tmp_mbuf
->m_nextpkt
;
1638 ip_input_second_pass(struct mbuf
*m
, struct ifnet
*inifp
, u_int32_t div_info
,
1639 int npkts_in_chain
, int bytes_in_chain
, struct ip_fw_in_args
*args
, int ours
)
1641 struct mbuf
*tmp_mbuf
= NULL
;
1645 #pragma unused (args)
1649 #pragma unused (div_info)
1652 struct ip
*ip
= mtod(m
, struct ip
*);
1653 hlen
= IP_VHL_HL(ip
->ip_vhl
) << 2;
1655 OSAddAtomic(npkts_in_chain
, &ipstat
.ips_total
);
1658 * Naively assume we can attribute inbound data to the route we would
1659 * use to send to this destination. Asymmetric routing breaks this
1660 * assumption, but it still allows us to account for traffic from
1661 * a remote node in the routing table.
1662 * this has a very significant performance impact so we bypass
1663 * if nstat_collect is disabled. We may also bypass if the
1664 * protocol is tcp in the future because tcp will have a route that
1665 * we can use to attribute the data to. That does mean we would not
1666 * account for forwarded tcp traffic.
1668 ip_input_update_nstat(inifp
, ip
->ip_src
, npkts_in_chain
,
1676 * Check our list of addresses, to see if the packet is for us.
1677 * If we don't have any addresses, assume any unicast packet
1678 * we receive might be for us (and let the upper layers deal
1682 if (TAILQ_EMPTY(&in_ifaddrhead
)) {
1683 while (tmp_mbuf
!= NULL
) {
1684 if (!(tmp_mbuf
->m_flags
& (M_MCAST
| M_BCAST
))) {
1685 ip_setdstifaddr_info(tmp_mbuf
, inifp
->if_index
,
1688 tmp_mbuf
= mbuf_nextpkt(tmp_mbuf
);
1694 * Enable a consistency check between the destination address
1695 * and the arrival interface for a unicast packet (the RFC 1122
1696 * strong ES model) if IP forwarding is disabled and the packet
1697 * is not locally generated and the packet is not subject to
1700 * XXX - Checking also should be disabled if the destination
1701 * address is ipnat'ed to a different interface.
1703 * XXX - Checking is incompatible with IP aliases added
1704 * to the loopback interface instead of the interface where
1705 * the packets are received.
1707 if (!IN_MULTICAST(ntohl(ip
->ip_dst
.s_addr
))) {
1708 ip_check_if_result_t ip_check_if_result
= IP_CHECK_IF_NONE
;
1710 ip_check_if_result
= ip_input_check_interface(&m
, ip
, inifp
);
1711 ASSERT(ip_check_if_result
!= IP_CHECK_IF_NONE
);
1712 if (ip_check_if_result
== IP_CHECK_IF_OURS
) {
1714 } else if (ip_check_if_result
== IP_CHECK_IF_DROP
) {
1718 struct in_multi
*inm
;
1720 * See if we belong to the destination multicast group on the
1721 * arrival interface.
1723 in_multihead_lock_shared();
1724 IN_LOOKUP_MULTI(&ip
->ip_dst
, inifp
, inm
);
1725 in_multihead_lock_done();
1727 OSAddAtomic(npkts_in_chain
, &ipstat
.ips_notmember
);
1729 KERNEL_DEBUG(DBG_LAYER_END
, 0, 0, 0, 0, 0);
1732 ip_input_setdst_chain(m
, inifp
->if_index
, NULL
);
1738 struct mbuf
*nxt_mbuf
= NULL
;
1739 while (tmp_mbuf
!= NULL
) {
1740 nxt_mbuf
= mbuf_nextpkt(tmp_mbuf
);
1742 * Not for us; forward if possible and desirable.
1744 mbuf_setnextpkt(tmp_mbuf
, NULL
);
1745 if (ipforwarding
== 0) {
1746 OSAddAtomic(1, &ipstat
.ips_cantforward
);
1750 ip_forward(tmp_mbuf
, 0, args
->fwai_next_hop
);
1752 ip_forward(tmp_mbuf
, 0, NULL
);
1755 tmp_mbuf
= nxt_mbuf
;
1757 KERNEL_DEBUG(DBG_LAYER_END
, 0, 0, 0, 0, 0);
1760 ip
= mtod(m
, struct ip
*); /* in case it changed */
1762 * If offset or IP_MF are set, must reassemble.
1764 if (ip
->ip_off
& ~(IP_DF
| IP_RF
)) {
1765 VERIFY(npkts_in_chain
== 1);
1767 * ip_reass() will return a different mbuf, and update
1768 * the divert info in div_info and args->fwai_divert_rule.
1771 m
= ip_reass(m
, (u_int16_t
*)&div_info
, &args
->fwai_divert_rule
);
1778 ip
= mtod(m
, struct ip
*);
1779 /* Get the header length of the reassembled packet */
1780 hlen
= IP_VHL_HL(ip
->ip_vhl
) << 2;
1782 /* Restore original checksum before diverting packet */
1783 if (div_info
!= 0) {
1784 VERIFY(npkts_in_chain
== 1);
1785 #if BYTE_ORDER != BIG_ENDIAN
1790 ip
->ip_sum
= ip_cksum_hdr_in(m
, hlen
);
1791 #if BYTE_ORDER != BIG_ENDIAN
1800 * Further protocols expect the packet length to be w/o the
1807 * Divert or tee packet to the divert protocol if required.
1809 * If div_info is zero then cookie should be too, so we shouldn't
1810 * need to clear them here. Assume divert_packet() does so also.
1812 if (div_info
!= 0) {
1813 struct mbuf
*clone
= NULL
;
1814 VERIFY(npkts_in_chain
== 1);
1816 /* Clone packet if we're doing a 'tee' */
1817 if (div_info
& IP_FW_PORT_TEE_FLAG
) {
1818 clone
= m_dup(m
, M_DONTWAIT
);
1821 /* Restore packet header fields to original values */
1824 #if BYTE_ORDER != BIG_ENDIAN
1828 /* Deliver packet to divert input routine */
1829 OSAddAtomic(1, &ipstat
.ips_delivered
);
1830 divert_packet(m
, 1, div_info
& 0xffff, args
->fwai_divert_rule
);
1832 /* If 'tee', continue with original packet */
1833 if (clone
== NULL
) {
1837 ip
= mtod(m
, struct ip
*);
1843 * enforce IPsec policy checking if we are seeing last header.
1844 * note that we do not visit this with protocols with pcb layer
1845 * code - like udp/tcp/raw ip.
1847 if (ipsec_bypass
== 0 && (ip_protox
[ip
->ip_p
]->pr_flags
& PR_LASTHDR
)) {
1848 VERIFY(npkts_in_chain
== 1);
1849 if (ipsec4_in_reject(m
, NULL
)) {
1850 IPSEC_STAT_INCREMENT(ipsecstat
.in_polvio
);
1857 * Switch out to protocol's input routine.
1859 OSAddAtomic(npkts_in_chain
, &ipstat
.ips_delivered
);
1862 if (args
->fwai_next_hop
&& ip
->ip_p
== IPPROTO_TCP
) {
1863 /* TCP needs IPFORWARD info if available */
1864 struct m_tag
*fwd_tag
;
1865 struct ip_fwd_tag
*ipfwd_tag
;
1867 VERIFY(npkts_in_chain
== 1);
1868 fwd_tag
= m_tag_create(KERNEL_MODULE_TAG_ID
,
1869 KERNEL_TAG_TYPE_IPFORWARD
, sizeof(*ipfwd_tag
),
1871 if (fwd_tag
== NULL
) {
1875 ipfwd_tag
= (struct ip_fwd_tag
*)(fwd_tag
+ 1);
1876 ipfwd_tag
->next_hop
= args
->fwai_next_hop
;
1878 m_tag_prepend(m
, fwd_tag
);
1880 KERNEL_DEBUG(DBG_LAYER_END
, ip
->ip_dst
.s_addr
,
1881 ip
->ip_src
.s_addr
, ip
->ip_p
, ip
->ip_off
, ip
->ip_len
);
1883 /* TCP deals with its own locking */
1884 ip_proto_dispatch_in(m
, hlen
, ip
->ip_p
, 0);
1886 KERNEL_DEBUG(DBG_LAYER_END
, ip
->ip_dst
.s_addr
,
1887 ip
->ip_src
.s_addr
, ip
->ip_p
, ip
->ip_off
, ip
->ip_len
);
1889 ip_input_dispatch_chain(m
);
1891 #else /* !IPFIREWALL */
1892 ip_input_dispatch_chain(m
);
1894 #endif /* !IPFIREWALL */
1895 KERNEL_DEBUG(DBG_LAYER_END
, 0, 0, 0, 0, 0);
1898 KERNEL_DEBUG(DBG_LAYER_END
, 0, 0, 0, 0, 0);
1903 ip_input_process_list(struct mbuf
*packet_list
)
1905 pktchain_elm_t pktchain_tbl
[PKTTBL_SZ
];
1907 struct mbuf
*packet
= NULL
;
1908 struct mbuf
*modm
= NULL
; /* modified mbuf */
1910 u_int32_t div_info
= 0;
1912 #if (DEBUG || DEVELOPMENT)
1913 struct timeval start_tv
;
1914 #endif /* (DEBUG || DEVELOPMENT) */
1917 struct ip_fw_in_args args
;
1919 if (ip_chaining
== 0) {
1920 struct mbuf
*m
= packet_list
;
1921 #if (DEBUG || DEVELOPMENT)
1922 if (ip_input_measure
) {
1923 net_perf_start_time(&net_perf
, &start_tv
);
1925 #endif /* (DEBUG || DEVELOPMENT) */
1928 packet_list
= mbuf_nextpkt(m
);
1929 mbuf_setnextpkt(m
, NULL
);
1934 #if (DEBUG || DEVELOPMENT)
1935 if (ip_input_measure
) {
1936 net_perf_measure_time(&net_perf
, &start_tv
, num_pkts
);
1938 #endif /* (DEBUG || DEVELOPMENT) */
1941 #if (DEBUG || DEVELOPMENT)
1942 if (ip_input_measure
) {
1943 net_perf_start_time(&net_perf
, &start_tv
);
1945 #endif /* (DEBUG || DEVELOPMENT) */
1947 bzero(&pktchain_tbl
, sizeof(pktchain_tbl
));
1948 restart_list_process
:
1950 for (packet
= packet_list
; packet
; packet
= packet_list
) {
1951 packet_list
= mbuf_nextpkt(packet
);
1952 mbuf_setnextpkt(packet
, NULL
);
1957 bzero(&args
, sizeof(args
));
1959 retval
= ip_input_first_pass(packet
, &div_info
, &args
,
1962 if (retval
== IPINPUT_DOCHAIN
) {
1966 packet
= ip_chain_insert(packet
, &pktchain_tbl
[0]);
1967 if (packet
== NULL
) {
1968 ipstat
.ips_rxc_chained
++;
1970 if (chain
> ip_chainsz
) {
1974 ipstat
.ips_rxc_collisions
++;
1977 } else if (retval
== IPINPUT_DONTCHAIN
) {
1978 /* in order to preserve order, exit from chaining */
1982 ipstat
.ips_rxc_notchain
++;
1985 /* packet was freed or delivered, do nothing. */
1989 /* do second pass here for pktchain_tbl */
1991 ip_input_second_pass_loop_tbl(&pktchain_tbl
[0], &args
);
1996 * equivalent update in chaining case if performed in
1997 * ip_input_second_pass_loop_tbl().
1999 #if (DEBUG || DEVELOPMENT)
2000 if (ip_input_measure
) {
2001 net_perf_histogram(&net_perf
, 1);
2003 #endif /* (DEBUG || DEVELOPMENT) */
2004 ip_input_second_pass(packet
, packet
->m_pkthdr
.rcvif
, div_info
,
2005 1, packet
->m_pkthdr
.len
, &args
, ours
);
2009 goto restart_list_process
;
2012 #if (DEBUG || DEVELOPMENT)
2013 if (ip_input_measure
) {
2014 net_perf_measure_time(&net_perf
, &start_tv
, num_pkts
);
2016 #endif /* (DEBUG || DEVELOPMENT) */
2019 * Ip input routine. Checksum and byte swap header. If fragmented
2020 * try to reassemble. Process options. Pass to next level.
2023 ip_input(struct mbuf
*m
)
2029 struct ip_fw_args args
;
2032 ipfilter_t inject_filter_ref
= NULL
;
2033 struct ifnet
*inifp
;
2035 /* Check if the mbuf is still valid after interface filter processing */
2036 MBUF_INPUT_CHECK(m
, m
->m_pkthdr
.rcvif
);
2037 inifp
= m
->m_pkthdr
.rcvif
;
2038 VERIFY(inifp
!= NULL
);
2040 ipstat
.ips_rxc_notlist
++;
2042 /* Perform IP header alignment fixup, if needed */
2043 IP_HDR_ALIGNMENT_FIXUP(m
, inifp
, goto bad
);
2045 m
->m_pkthdr
.pkt_flags
&= ~PKTF_FORWARDED
;
2047 #if IPFIREWALL || DUMMYNET
2048 bzero(&args
, sizeof(struct ip_fw_args
));
2051 * Don't bother searching for tag(s) if there's none.
2053 if (SLIST_EMPTY(&m
->m_pkthdr
.tags
)) {
2054 goto ipfw_tags_done
;
2057 /* Grab info from mtags prepended to the chain */
2059 if ((tag
= m_tag_locate(m
, KERNEL_MODULE_TAG_ID
,
2060 KERNEL_TAG_TYPE_DUMMYNET
, NULL
)) != NULL
) {
2061 struct dn_pkt_tag
*dn_tag
;
2063 dn_tag
= (struct dn_pkt_tag
*)(tag
+ 1);
2064 args
.fwa_ipfw_rule
= dn_tag
->dn_ipfw_rule
;
2065 args
.fwa_pf_rule
= dn_tag
->dn_pf_rule
;
2067 m_tag_delete(m
, tag
);
2069 #endif /* DUMMYNET */
2072 if ((tag
= m_tag_locate(m
, KERNEL_MODULE_TAG_ID
,
2073 KERNEL_TAG_TYPE_DIVERT
, NULL
)) != NULL
) {
2074 struct divert_tag
*div_tag
;
2076 div_tag
= (struct divert_tag
*)(tag
+ 1);
2077 args
.fwa_divert_rule
= div_tag
->cookie
;
2079 m_tag_delete(m
, tag
);
2083 if ((tag
= m_tag_locate(m
, KERNEL_MODULE_TAG_ID
,
2084 KERNEL_TAG_TYPE_IPFORWARD
, NULL
)) != NULL
) {
2085 struct ip_fwd_tag
*ipfwd_tag
;
2087 ipfwd_tag
= (struct ip_fwd_tag
*)(tag
+ 1);
2088 args
.fwa_next_hop
= ipfwd_tag
->next_hop
;
2090 m_tag_delete(m
, tag
);
2094 if (m
== NULL
|| !(m
->m_flags
& M_PKTHDR
)) {
2095 panic("ip_input no HDR");
2100 if (args
.fwa_ipfw_rule
|| args
.fwa_pf_rule
) {
2101 /* dummynet already filtered us */
2102 ip
= mtod(m
, struct ip
*);
2103 hlen
= IP_VHL_HL(ip
->ip_vhl
) << 2;
2104 inject_filter_ref
= ipf_get_inject_filter(m
);
2106 if (args
.fwa_ipfw_rule
) {
2109 #endif /* IPFIREWALL */
2110 if (args
.fwa_pf_rule
) {
2114 #endif /* DUMMYNET */
2116 #endif /* IPFIREWALL || DUMMYNET */
2119 * No need to process packet twice if we've already seen it.
2121 if (!SLIST_EMPTY(&m
->m_pkthdr
.tags
)) {
2122 inject_filter_ref
= ipf_get_inject_filter(m
);
2124 if (inject_filter_ref
!= NULL
) {
2125 ip
= mtod(m
, struct ip
*);
2126 hlen
= IP_VHL_HL(ip
->ip_vhl
) << 2;
2128 DTRACE_IP6(receive
, struct mbuf
*, m
, struct inpcb
*, NULL
,
2129 struct ip
*, ip
, struct ifnet
*, inifp
,
2130 struct ip
*, ip
, struct ip6_hdr
*, NULL
);
2132 ip
->ip_len
= ntohs(ip
->ip_len
) - hlen
;
2133 ip
->ip_off
= ntohs(ip
->ip_off
);
2134 ip_proto_dispatch_in(m
, hlen
, ip
->ip_p
, inject_filter_ref
);
2138 OSAddAtomic(1, &ipstat
.ips_total
);
2139 if (m
->m_pkthdr
.len
< sizeof(struct ip
)) {
2143 if (m
->m_len
< sizeof(struct ip
) &&
2144 (m
= m_pullup(m
, sizeof(struct ip
))) == NULL
) {
2145 OSAddAtomic(1, &ipstat
.ips_toosmall
);
2148 ip
= mtod(m
, struct ip
*);
2150 KERNEL_DEBUG(DBG_LAYER_BEG
, ip
->ip_dst
.s_addr
, ip
->ip_src
.s_addr
,
2151 ip
->ip_p
, ip
->ip_off
, ip
->ip_len
);
2153 if (IP_VHL_V(ip
->ip_vhl
) != IPVERSION
) {
2154 OSAddAtomic(1, &ipstat
.ips_badvers
);
2158 hlen
= IP_VHL_HL(ip
->ip_vhl
) << 2;
2159 if (hlen
< sizeof(struct ip
)) { /* minimum header length */
2160 OSAddAtomic(1, &ipstat
.ips_badhlen
);
2163 if (hlen
> m
->m_len
) {
2164 if ((m
= m_pullup(m
, hlen
)) == NULL
) {
2165 OSAddAtomic(1, &ipstat
.ips_badhlen
);
2168 ip
= mtod(m
, struct ip
*);
2171 /* 127/8 must not appear on wire - RFC1122 */
2172 if ((ntohl(ip
->ip_dst
.s_addr
) >> IN_CLASSA_NSHIFT
) == IN_LOOPBACKNET
||
2173 (ntohl(ip
->ip_src
.s_addr
) >> IN_CLASSA_NSHIFT
) == IN_LOOPBACKNET
) {
2175 * Allow for the following exceptions:
2177 * 1. If the packet was sent to loopback (i.e. rcvif
2178 * would have been set earlier at output time.)
2180 * 2. If the packet was sent out on loopback from a local
2181 * source address which belongs to a non-loopback
2182 * interface (i.e. rcvif may not necessarily be a
2183 * loopback interface, hence the test for PKTF_LOOP.)
2184 * Unlike IPv6, there is no interface scope ID, and
2185 * therefore we don't care so much about PKTF_IFINFO.
2187 if (!(inifp
->if_flags
& IFF_LOOPBACK
) &&
2188 !(m
->m_pkthdr
.pkt_flags
& PKTF_LOOP
)) {
2189 OSAddAtomic(1, &ipstat
.ips_badaddr
);
2194 /* IPv4 Link-Local Addresses as defined in RFC3927 */
2195 if ((IN_LINKLOCAL(ntohl(ip
->ip_dst
.s_addr
)) ||
2196 IN_LINKLOCAL(ntohl(ip
->ip_src
.s_addr
)))) {
2197 ip_linklocal_stat
.iplls_in_total
++;
2198 if (ip
->ip_ttl
!= MAXTTL
) {
2199 OSAddAtomic(1, &ip_linklocal_stat
.iplls_in_badttl
);
2200 /* Silently drop link local traffic with bad TTL */
2201 if (!ip_linklocal_in_allowbadttl
) {
2207 sum
= ip_cksum(m
, hlen
);
2212 DTRACE_IP6(receive
, struct mbuf
*, m
, struct inpcb
*, NULL
,
2213 struct ip
*, ip
, struct ifnet
*, inifp
,
2214 struct ip
*, ip
, struct ip6_hdr
*, NULL
);
2217 * Naively assume we can attribute inbound data to the route we would
2218 * use to send to this destination. Asymmetric routing breaks this
2219 * assumption, but it still allows us to account for traffic from
2220 * a remote node in the routing table.
2221 * this has a very significant performance impact so we bypass
2222 * if nstat_collect is disabled. We may also bypass if the
2223 * protocol is tcp in the future because tcp will have a route that
2224 * we can use to attribute the data to. That does mean we would not
2225 * account for forwarded tcp traffic.
2227 if (nstat_collect
) {
2228 struct rtentry
*rt
=
2229 ifnet_cached_rtlookup_inet(inifp
, ip
->ip_src
);
2231 nstat_route_rx(rt
, 1, m
->m_pkthdr
.len
, 0);
2237 * Convert fields to host representation.
2239 #if BYTE_ORDER != BIG_ENDIAN
2243 if (ip
->ip_len
< hlen
) {
2244 OSAddAtomic(1, &ipstat
.ips_badlen
);
2248 #if BYTE_ORDER != BIG_ENDIAN
2252 * Check that the amount of data in the buffers
2253 * is as at least much as the IP header would have us expect.
2254 * Trim mbufs if longer than we expect.
2255 * Drop packet if shorter than we expect.
2257 if (m
->m_pkthdr
.len
< ip
->ip_len
) {
2259 OSAddAtomic(1, &ipstat
.ips_tooshort
);
2262 if (m
->m_pkthdr
.len
> ip
->ip_len
) {
2263 ip_input_adjust(m
, ip
, inifp
);
2270 /* Invoke inbound packet filter */
2271 if (PF_IS_ENABLED
) {
2274 error
= pf_af_hook(inifp
, NULL
, &m
, AF_INET
, TRUE
, &args
);
2276 error
= pf_af_hook(inifp
, NULL
, &m
, AF_INET
, TRUE
, NULL
);
2277 #endif /* DUMMYNET */
2278 if (error
!= 0 || m
== NULL
) {
2280 panic("%s: unexpected packet %p\n",
2284 /* Already freed by callee */
2287 ip
= mtod(m
, struct ip
*);
2288 hlen
= IP_VHL_HL(ip
->ip_vhl
) << 2;
2293 if (ipsec_bypass
== 0 && ipsec_gethist(m
, NULL
)) {
2301 #endif /* DUMMYNET */
2303 * Check if we want to allow this packet to be processed.
2304 * Consider it to be bad if not.
2306 if (fw_enable
&& IPFW_LOADED
) {
2307 #if IPFIREWALL_FORWARD
2309 * If we've been forwarded from the output side, then
2310 * skip the firewall a second time
2312 if (args
.fwa_next_hop
) {
2315 #endif /* IPFIREWALL_FORWARD */
2319 i
= ip_fw_chk_ptr(&args
);
2322 if ((i
& IP_FW_PORT_DENY_FLAG
) || m
== NULL
) { /* drop */
2328 ip
= mtod(m
, struct ip
*); /* just in case m changed */
2330 if (i
== 0 && args
.fwa_next_hop
== NULL
) { /* common case */
2334 if (DUMMYNET_LOADED
&& (i
& IP_FW_PORT_DYNT_FLAG
) != 0) {
2335 /* Send packet to the appropriate pipe */
2336 ip_dn_io_ptr(m
, i
& 0xffff, DN_TO_IP_IN
, &args
,
2340 #endif /* DUMMYNET */
2342 if (i
!= 0 && (i
& IP_FW_PORT_DYNT_FLAG
) == 0) {
2343 /* Divert or tee packet */
2348 #if IPFIREWALL_FORWARD
2349 if (i
== 0 && args
.fwa_next_hop
!= NULL
) {
2354 * if we get here, the packet must be dropped
2359 #endif /* IPFIREWALL */
2360 #if IPSEC | IPFIREWALL
2364 * Process options and, if not destined for us,
2365 * ship it on. ip_dooptions returns 1 when an
2366 * error was detected (causing an icmp message
2367 * to be sent and the original packet to be freed).
2369 ip_nhops
= 0; /* for source routed packets */
2371 if (hlen
> sizeof(struct ip
) &&
2372 ip_dooptions(m
, 0, args
.fwa_next_hop
)) {
2373 #else /* !IPFIREWALL */
2374 if (hlen
> sizeof(struct ip
) && ip_dooptions(m
, 0, NULL
)) {
2375 #endif /* !IPFIREWALL */
2380 * Check our list of addresses, to see if the packet is for us.
2381 * If we don't have any addresses, assume any unicast packet
2382 * we receive might be for us (and let the upper layers deal
2385 if (TAILQ_EMPTY(&in_ifaddrhead
) && !(m
->m_flags
& (M_MCAST
| M_BCAST
))) {
2386 ip_setdstifaddr_info(m
, inifp
->if_index
, NULL
);
2391 * Enable a consistency check between the destination address
2392 * and the arrival interface for a unicast packet (the RFC 1122
2393 * strong ES model) if IP forwarding is disabled and the packet
2394 * is not locally generated and the packet is not subject to
2397 * XXX - Checking also should be disabled if the destination
2398 * address is ipnat'ed to a different interface.
2400 * XXX - Checking is incompatible with IP aliases added
2401 * to the loopback interface instead of the interface where
2402 * the packets are received.
2404 if (!IN_MULTICAST(ntohl(ip
->ip_dst
.s_addr
))) {
2405 ip_check_if_result_t check_if_result
= IP_CHECK_IF_NONE
;
2407 check_if_result
= ip_input_check_interface(&m
, ip
, inifp
);
2408 ASSERT(check_if_result
!= IP_CHECK_IF_NONE
);
2409 if (check_if_result
== IP_CHECK_IF_OURS
) {
2411 } else if (check_if_result
== IP_CHECK_IF_DROP
) {
2415 struct in_multi
*inm
;
2417 * See if we belong to the destination multicast group on the
2418 * arrival interface.
2420 in_multihead_lock_shared();
2421 IN_LOOKUP_MULTI(&ip
->ip_dst
, inifp
, inm
);
2422 in_multihead_lock_done();
2424 OSAddAtomic(1, &ipstat
.ips_notmember
);
2428 ip_setdstifaddr_info(m
, inifp
->if_index
, NULL
);
2434 * Not for us; forward if possible and desirable.
2436 if (ipforwarding
== 0) {
2437 OSAddAtomic(1, &ipstat
.ips_cantforward
);
2441 ip_forward(m
, 0, args
.fwa_next_hop
);
2443 ip_forward(m
, 0, NULL
);
2450 * If offset or IP_MF are set, must reassemble.
2452 if (ip
->ip_off
& ~(IP_DF
| IP_RF
)) {
2454 * ip_reass() will return a different mbuf, and update
2455 * the divert info in div_info and args.fwa_divert_rule.
2458 m
= ip_reass(m
, (u_int16_t
*)&div_info
, &args
.fwa_divert_rule
);
2465 ip
= mtod(m
, struct ip
*);
2466 /* Get the header length of the reassembled packet */
2467 hlen
= IP_VHL_HL(ip
->ip_vhl
) << 2;
2469 /* Restore original checksum before diverting packet */
2470 if (div_info
!= 0) {
2471 #if BYTE_ORDER != BIG_ENDIAN
2476 ip
->ip_sum
= ip_cksum_hdr_in(m
, hlen
);
2477 #if BYTE_ORDER != BIG_ENDIAN
2486 * Further protocols expect the packet length to be w/o the
2493 * Divert or tee packet to the divert protocol if required.
2495 * If div_info is zero then cookie should be too, so we shouldn't
2496 * need to clear them here. Assume divert_packet() does so also.
2498 if (div_info
!= 0) {
2499 struct mbuf
*clone
= NULL
;
2501 /* Clone packet if we're doing a 'tee' */
2502 if (div_info
& IP_FW_PORT_TEE_FLAG
) {
2503 clone
= m_dup(m
, M_DONTWAIT
);
2506 /* Restore packet header fields to original values */
2509 #if BYTE_ORDER != BIG_ENDIAN
2513 /* Deliver packet to divert input routine */
2514 OSAddAtomic(1, &ipstat
.ips_delivered
);
2515 divert_packet(m
, 1, div_info
& 0xffff, args
.fwa_divert_rule
);
2517 /* If 'tee', continue with original packet */
2518 if (clone
== NULL
) {
2522 ip
= mtod(m
, struct ip
*);
2528 * enforce IPsec policy checking if we are seeing last header.
2529 * note that we do not visit this with protocols with pcb layer
2530 * code - like udp/tcp/raw ip.
2532 if (ipsec_bypass
== 0 && (ip_protox
[ip
->ip_p
]->pr_flags
& PR_LASTHDR
)) {
2533 if (ipsec4_in_reject(m
, NULL
)) {
2534 IPSEC_STAT_INCREMENT(ipsecstat
.in_polvio
);
2541 * Switch out to protocol's input routine.
2543 OSAddAtomic(1, &ipstat
.ips_delivered
);
2546 if (args
.fwa_next_hop
&& ip
->ip_p
== IPPROTO_TCP
) {
2547 /* TCP needs IPFORWARD info if available */
2548 struct m_tag
*fwd_tag
;
2549 struct ip_fwd_tag
*ipfwd_tag
;
2551 fwd_tag
= m_tag_create(KERNEL_MODULE_TAG_ID
,
2552 KERNEL_TAG_TYPE_IPFORWARD
, sizeof(*ipfwd_tag
),
2554 if (fwd_tag
== NULL
) {
2558 ipfwd_tag
= (struct ip_fwd_tag
*)(fwd_tag
+ 1);
2559 ipfwd_tag
->next_hop
= args
.fwa_next_hop
;
2561 m_tag_prepend(m
, fwd_tag
);
2563 KERNEL_DEBUG(DBG_LAYER_END
, ip
->ip_dst
.s_addr
,
2564 ip
->ip_src
.s_addr
, ip
->ip_p
, ip
->ip_off
, ip
->ip_len
);
2566 /* TCP deals with its own locking */
2567 ip_proto_dispatch_in(m
, hlen
, ip
->ip_p
, 0);
2569 KERNEL_DEBUG(DBG_LAYER_END
, ip
->ip_dst
.s_addr
,
2570 ip
->ip_src
.s_addr
, ip
->ip_p
, ip
->ip_off
, ip
->ip_len
);
2572 if ((sw_lro
) && (ip
->ip_p
== IPPROTO_TCP
)) {
2573 m
= tcp_lro(m
, hlen
);
2579 ip_proto_dispatch_in(m
, hlen
, ip
->ip_p
, 0);
2581 #else /* !IPFIREWALL */
2582 if ((sw_lro
) && (ip
->ip_p
== IPPROTO_TCP
)) {
2583 m
= tcp_lro(m
, hlen
);
2588 ip_proto_dispatch_in(m
, hlen
, ip
->ip_p
, 0);
2589 #endif /* !IPFIREWALL */
2593 KERNEL_DEBUG(DBG_LAYER_END
, 0, 0, 0, 0, 0);
2598 ipq_updateparams(void)
2600 LCK_MTX_ASSERT(&ipqlock
, LCK_MTX_ASSERT_OWNED
);
2602 * -1 for unlimited allocation.
2608 * Positive number for specific bound.
2611 ipq_limit
= maxnipq
;
2614 * Zero specifies no further fragment queue allocation -- set the
2615 * bound very low, but rely on implementation elsewhere to actually
2616 * prevent allocation and reclaim current queues.
2622 * Arm the purge timer if not already and if there's work to do
2624 frag_sched_timeout();
2628 sysctl_maxnipq SYSCTL_HANDLER_ARGS
2630 #pragma unused(arg1, arg2)
2633 lck_mtx_lock(&ipqlock
);
2635 error
= sysctl_handle_int(oidp
, &i
, 0, req
);
2636 if (error
|| req
->newptr
== USER_ADDR_NULL
) {
2640 if (i
< -1 || i
> (nmbclusters
/ 4)) {
2647 lck_mtx_unlock(&ipqlock
);
2652 sysctl_maxfragsperpacket SYSCTL_HANDLER_ARGS
2654 #pragma unused(arg1, arg2)
2657 lck_mtx_lock(&ipqlock
);
2658 i
= maxfragsperpacket
;
2659 error
= sysctl_handle_int(oidp
, &i
, 0, req
);
2660 if (error
|| req
->newptr
== USER_ADDR_NULL
) {
2663 maxfragsperpacket
= i
;
2664 ipq_updateparams(); /* see if we need to arm timer */
2666 lck_mtx_unlock(&ipqlock
);
2671 * Take incoming datagram fragment and try to reassemble it into
2672 * whole datagram. If a chain for reassembly of this datagram already
2673 * exists, then it is given as fp; otherwise have to make a chain.
2675 * When IPDIVERT enabled, keep additional state with each packet that
2676 * tells us if we need to divert or tee the packet we're building.
2678 * The IP header is *NOT* adjusted out of iplen (but in host byte order).
2680 static struct mbuf
*
2682 ip_reass(struct mbuf
*m
,
2685 #else /* IPDIVERT_44 */
2687 #endif /* IPDIVERT_44 */
2688 u_int16_t
*divcookie
)
2689 #else /* IPDIVERT */
2690 ip_reass(struct mbuf
*m
)
2691 #endif /* IPDIVERT */
2694 struct mbuf
*p
, *q
, *nq
, *t
;
2695 struct ipq
*fp
= NULL
;
2696 struct ipqhead
*head
;
2699 uint32_t csum
, csum_flags
;
2703 MBUFQ_INIT(&dfq
); /* for deferred frees */
2705 /* If maxnipq or maxfragsperpacket is 0, never accept fragments. */
2706 if (maxnipq
== 0 || maxfragsperpacket
== 0) {
2707 ipstat
.ips_fragments
++;
2708 ipstat
.ips_fragdropped
++;
2711 lck_mtx_lock(&ipqlock
);
2712 frag_sched_timeout(); /* purge stale fragments */
2713 lck_mtx_unlock(&ipqlock
);
2718 ip
= mtod(m
, struct ip
*);
2719 hlen
= IP_VHL_HL(ip
->ip_vhl
) << 2;
2721 lck_mtx_lock(&ipqlock
);
2723 hash
= IPREASS_HASH(ip
->ip_src
.s_addr
, ip
->ip_id
);
2727 * Look for queue of fragments
2730 TAILQ_FOREACH(fp
, head
, ipq_list
) {
2731 if (ip
->ip_id
== fp
->ipq_id
&&
2732 ip
->ip_src
.s_addr
== fp
->ipq_src
.s_addr
&&
2733 ip
->ip_dst
.s_addr
== fp
->ipq_dst
.s_addr
&&
2735 mac_ipq_label_compare(m
, fp
) &&
2737 ip
->ip_p
== fp
->ipq_p
) {
2745 * Attempt to trim the number of allocated fragment queues if it
2746 * exceeds the administrative limit.
2748 if ((nipq
> (unsigned)maxnipq
) && (maxnipq
> 0)) {
2750 * drop something from the tail of the current queue
2751 * before proceeding further
2753 struct ipq
*fq
= TAILQ_LAST(head
, ipqhead
);
2754 if (fq
== NULL
) { /* gak */
2755 for (i
= 0; i
< IPREASS_NHASH
; i
++) {
2756 struct ipq
*r
= TAILQ_LAST(&ipq
[i
], ipqhead
);
2758 ipstat
.ips_fragtimeout
+= r
->ipq_nfrags
;
2759 frag_freef(&ipq
[i
], r
);
2764 ipstat
.ips_fragtimeout
+= fq
->ipq_nfrags
;
2765 frag_freef(head
, fq
);
2771 * Leverage partial checksum offload for IP fragments. Narrow down
2772 * the scope to cover only UDP without IP options, as that is the
2775 * Perform 1's complement adjustment of octets that got included/
2776 * excluded in the hardware-calculated checksum value. Ignore cases
2777 * where the value includes the entire IPv4 header span, as the sum
2778 * for those octets would already be 0 by the time we get here; IP
2779 * has already performed its header checksum validation. Also take
2780 * care of any trailing bytes and subtract out their partial sum.
2782 if (ip
->ip_p
== IPPROTO_UDP
&& hlen
== sizeof(struct ip
) &&
2783 (m
->m_pkthdr
.csum_flags
&
2784 (CSUM_DATA_VALID
| CSUM_PARTIAL
| CSUM_PSEUDO_HDR
)) ==
2785 (CSUM_DATA_VALID
| CSUM_PARTIAL
)) {
2786 uint32_t start
= m
->m_pkthdr
.csum_rx_start
;
2787 int32_t trailer
= (m_pktlen(m
) - ip
->ip_len
);
2788 uint32_t swbytes
= (uint32_t)trailer
;
2790 csum
= m
->m_pkthdr
.csum_rx_val
;
2792 ASSERT(trailer
>= 0);
2793 if ((start
!= 0 && start
!= hlen
) || trailer
!= 0) {
2794 uint32_t datalen
= ip
->ip_len
- hlen
;
2796 #if BYTE_ORDER != BIG_ENDIAN
2801 #endif /* BYTE_ORDER != BIG_ENDIAN */
2802 /* callee folds in sum */
2803 csum
= m_adj_sum16(m
, start
, hlen
, datalen
, csum
);
2805 swbytes
+= (hlen
- start
);
2807 swbytes
+= (start
- hlen
);
2809 #if BYTE_ORDER != BIG_ENDIAN
2814 #endif /* BYTE_ORDER != BIG_ENDIAN */
2816 csum_flags
= m
->m_pkthdr
.csum_flags
;
2819 udp_in_cksum_stats(swbytes
);
2829 /* Invalidate checksum */
2830 m
->m_pkthdr
.csum_flags
&= ~CSUM_DATA_VALID
;
2832 ipstat
.ips_fragments
++;
2835 * Adjust ip_len to not reflect header,
2836 * convert offset of this to bytes.
2839 if (ip
->ip_off
& IP_MF
) {
2841 * Make sure that fragments have a data length
2842 * that's a non-zero multiple of 8 bytes.
2844 if (ip
->ip_len
== 0 || (ip
->ip_len
& 0x7) != 0) {
2845 OSAddAtomic(1, &ipstat
.ips_toosmall
);
2847 * Reassembly queue may have been found if previous
2848 * fragments were valid; given that this one is bad,
2849 * we need to drop it. Make sure to set fp to NULL
2850 * if not already, since we don't want to decrement
2851 * ipq_nfrags as it doesn't include this packet.
2856 m
->m_flags
|= M_FRAG
;
2858 /* Clear the flag in case packet comes from loopback */
2859 m
->m_flags
&= ~M_FRAG
;
2863 m
->m_pkthdr
.pkt_hdr
= ip
;
2865 /* Previous ip_reass() started here. */
2867 * Presence of header sizes in mbufs
2868 * would confuse code below.
2874 * If first fragment to arrive, create a reassembly queue.
2877 fp
= ipq_alloc(M_DONTWAIT
);
2882 if (mac_ipq_label_init(fp
, M_NOWAIT
) != 0) {
2887 mac_ipq_label_associate(m
, fp
);
2889 TAILQ_INSERT_HEAD(head
, fp
, ipq_list
);
2892 fp
->ipq_ttl
= IPFRAGTTL
;
2893 fp
->ipq_p
= ip
->ip_p
;
2894 fp
->ipq_id
= ip
->ip_id
;
2895 fp
->ipq_src
= ip
->ip_src
;
2896 fp
->ipq_dst
= ip
->ip_dst
;
2898 m
->m_nextpkt
= NULL
;
2900 * If the first fragment has valid checksum offload
2901 * info, the rest of fragments are eligible as well.
2903 if (csum_flags
!= 0) {
2904 fp
->ipq_csum
= csum
;
2905 fp
->ipq_csum_flags
= csum_flags
;
2909 * Transfer firewall instructions to the fragment structure.
2910 * Only trust info in the fragment at offset 0.
2912 if (ip
->ip_off
== 0) {
2914 fp
->ipq_div_info
= *divinfo
;
2916 fp
->ipq_divert
= *divinfo
;
2918 fp
->ipq_div_cookie
= *divcookie
;
2922 #endif /* IPDIVERT */
2923 m
= NULL
; /* nothing to return */
2928 mac_ipq_label_update(m
, fp
);
2932 #define GETIP(m) ((struct ip *)((m)->m_pkthdr.pkt_hdr))
2935 * Handle ECN by comparing this segment with the first one;
2936 * if CE is set, do not lose CE.
2937 * drop if CE and not-ECT are mixed for the same packet.
2939 ecn
= ip
->ip_tos
& IPTOS_ECN_MASK
;
2940 ecn0
= GETIP(fp
->ipq_frags
)->ip_tos
& IPTOS_ECN_MASK
;
2941 if (ecn
== IPTOS_ECN_CE
) {
2942 if (ecn0
== IPTOS_ECN_NOTECT
) {
2945 if (ecn0
!= IPTOS_ECN_CE
) {
2946 GETIP(fp
->ipq_frags
)->ip_tos
|= IPTOS_ECN_CE
;
2949 if (ecn
== IPTOS_ECN_NOTECT
&& ecn0
!= IPTOS_ECN_NOTECT
) {
2954 * Find a segment which begins after this one does.
2956 for (p
= NULL
, q
= fp
->ipq_frags
; q
; p
= q
, q
= q
->m_nextpkt
) {
2957 if (GETIP(q
)->ip_off
> ip
->ip_off
) {
2963 * If there is a preceding segment, it may provide some of
2964 * our data already. If so, drop the data from the incoming
2965 * segment. If it provides all of our data, drop us, otherwise
2966 * stick new segment in the proper place.
2968 * If some of the data is dropped from the preceding
2969 * segment, then it's checksum is invalidated.
2972 i
= GETIP(p
)->ip_off
+ GETIP(p
)->ip_len
- ip
->ip_off
;
2974 if (i
>= ip
->ip_len
) {
2978 fp
->ipq_csum_flags
= 0;
2982 m
->m_nextpkt
= p
->m_nextpkt
;
2985 m
->m_nextpkt
= fp
->ipq_frags
;
2990 * While we overlap succeeding segments trim them or,
2991 * if they are completely covered, dequeue them.
2993 for (; q
!= NULL
&& ip
->ip_off
+ ip
->ip_len
> GETIP(q
)->ip_off
;
2995 i
= (ip
->ip_off
+ ip
->ip_len
) - GETIP(q
)->ip_off
;
2996 if (i
< GETIP(q
)->ip_len
) {
2997 GETIP(q
)->ip_len
-= i
;
2998 GETIP(q
)->ip_off
+= i
;
3000 fp
->ipq_csum_flags
= 0;
3005 ipstat
.ips_fragdropped
++;
3007 /* defer freeing until after lock is dropped */
3008 MBUFQ_ENQUEUE(&dfq
, q
);
3012 * If this fragment contains similar checksum offload info
3013 * as that of the existing ones, accumulate checksum. Otherwise,
3014 * invalidate checksum offload info for the entire datagram.
3016 if (csum_flags
!= 0 && csum_flags
== fp
->ipq_csum_flags
) {
3017 fp
->ipq_csum
+= csum
;
3018 } else if (fp
->ipq_csum_flags
!= 0) {
3019 fp
->ipq_csum_flags
= 0;
3024 * Transfer firewall instructions to the fragment structure.
3025 * Only trust info in the fragment at offset 0.
3027 if (ip
->ip_off
== 0) {
3029 fp
->ipq_div_info
= *divinfo
;
3031 fp
->ipq_divert
= *divinfo
;
3033 fp
->ipq_div_cookie
= *divcookie
;
3037 #endif /* IPDIVERT */
3040 * Check for complete reassembly and perform frag per packet
3043 * Frag limiting is performed here so that the nth frag has
3044 * a chance to complete the packet before we drop the packet.
3045 * As a result, n+1 frags are actually allowed per packet, but
3046 * only n will ever be stored. (n = maxfragsperpacket.)
3050 for (p
= NULL
, q
= fp
->ipq_frags
; q
; p
= q
, q
= q
->m_nextpkt
) {
3051 if (GETIP(q
)->ip_off
!= next
) {
3052 if (fp
->ipq_nfrags
> maxfragsperpacket
) {
3053 ipstat
.ips_fragdropped
+= fp
->ipq_nfrags
;
3054 frag_freef(head
, fp
);
3056 m
= NULL
; /* nothing to return */
3059 next
+= GETIP(q
)->ip_len
;
3061 /* Make sure the last packet didn't have the IP_MF flag */
3062 if (p
->m_flags
& M_FRAG
) {
3063 if (fp
->ipq_nfrags
> maxfragsperpacket
) {
3064 ipstat
.ips_fragdropped
+= fp
->ipq_nfrags
;
3065 frag_freef(head
, fp
);
3067 m
= NULL
; /* nothing to return */
3072 * Reassembly is complete. Make sure the packet is a sane size.
3076 if (next
+ (IP_VHL_HL(ip
->ip_vhl
) << 2) > IP_MAXPACKET
) {
3077 ipstat
.ips_toolong
++;
3078 ipstat
.ips_fragdropped
+= fp
->ipq_nfrags
;
3079 frag_freef(head
, fp
);
3080 m
= NULL
; /* nothing to return */
3085 * Concatenate fragments.
3092 q
->m_nextpkt
= NULL
;
3093 for (q
= nq
; q
!= NULL
; q
= nq
) {
3095 q
->m_nextpkt
= NULL
;
3100 * Store partial hardware checksum info from the fragment queue;
3101 * the receive start offset is set to 20 bytes (see code at the
3102 * top of this routine.)
3104 if (fp
->ipq_csum_flags
!= 0) {
3105 csum
= fp
->ipq_csum
;
3109 m
->m_pkthdr
.csum_rx_val
= csum
;
3110 m
->m_pkthdr
.csum_rx_start
= sizeof(struct ip
);
3111 m
->m_pkthdr
.csum_flags
= fp
->ipq_csum_flags
;
3112 } else if ((m
->m_pkthdr
.rcvif
->if_flags
& IFF_LOOPBACK
) ||
3113 (m
->m_pkthdr
.pkt_flags
& PKTF_LOOP
)) {
3114 /* loopback checksums are always OK */
3115 m
->m_pkthdr
.csum_data
= 0xffff;
3116 m
->m_pkthdr
.csum_flags
=
3117 CSUM_DATA_VALID
| CSUM_PSEUDO_HDR
|
3118 CSUM_IP_CHECKED
| CSUM_IP_VALID
;
3123 * Extract firewall instructions from the fragment structure.
3126 *divinfo
= fp
->ipq_div_info
;
3128 *divinfo
= fp
->ipq_divert
;
3130 *divcookie
= fp
->ipq_div_cookie
;
3131 #endif /* IPDIVERT */
3134 mac_mbuf_label_associate_ipq(fp
, m
);
3135 mac_ipq_label_destroy(fp
);
3138 * Create header for new ip packet by modifying header of first
3139 * packet; dequeue and discard fragment reassembly header.
3140 * Make header visible.
3142 ip
->ip_len
= (IP_VHL_HL(ip
->ip_vhl
) << 2) + next
;
3143 ip
->ip_src
= fp
->ipq_src
;
3144 ip
->ip_dst
= fp
->ipq_dst
;
3146 fp
->ipq_frags
= NULL
; /* return to caller as 'm' */
3147 frag_freef(head
, fp
);
3150 m
->m_len
+= (IP_VHL_HL(ip
->ip_vhl
) << 2);
3151 m
->m_data
-= (IP_VHL_HL(ip
->ip_vhl
) << 2);
3152 /* some debugging cruft by sklower, below, will go away soon */
3153 if (m
->m_flags
& M_PKTHDR
) { /* XXX this should be done elsewhere */
3156 ipstat
.ips_reassembled
++;
3158 /* arm the purge timer if not already and if there's work to do */
3159 frag_sched_timeout();
3160 lck_mtx_unlock(&ipqlock
);
3161 /* perform deferred free (if needed) now that lock is dropped */
3162 if (!MBUFQ_EMPTY(&dfq
)) {
3165 VERIFY(MBUFQ_EMPTY(&dfq
));
3170 /* arm the purge timer if not already and if there's work to do */
3171 frag_sched_timeout();
3172 lck_mtx_unlock(&ipqlock
);
3173 /* perform deferred free (if needed) */
3174 if (!MBUFQ_EMPTY(&dfq
)) {
3177 VERIFY(MBUFQ_EMPTY(&dfq
));
3184 #endif /* IPDIVERT */
3185 ipstat
.ips_fragdropped
++;
3189 /* arm the purge timer if not already and if there's work to do */
3190 frag_sched_timeout();
3191 lck_mtx_unlock(&ipqlock
);
3193 /* perform deferred free (if needed) */
3194 if (!MBUFQ_EMPTY(&dfq
)) {
3197 VERIFY(MBUFQ_EMPTY(&dfq
));
3203 * Free a fragment reassembly header and all
3204 * associated datagrams.
3207 frag_freef(struct ipqhead
*fhp
, struct ipq
*fp
)
3209 LCK_MTX_ASSERT(&ipqlock
, LCK_MTX_ASSERT_OWNED
);
3212 if (fp
->ipq_frags
!= NULL
) {
3213 m_freem_list(fp
->ipq_frags
);
3214 fp
->ipq_frags
= NULL
;
3216 TAILQ_REMOVE(fhp
, fp
, ipq_list
);
3222 * IP reassembly timer processing
3225 frag_timeout(void *arg
)
3232 * Update coarse-grained networking timestamp (in sec.); the idea
3233 * is to piggy-back on the timeout callout to update the counter
3234 * returnable via net_uptime().
3236 net_update_uptime();
3238 lck_mtx_lock(&ipqlock
);
3239 for (i
= 0; i
< IPREASS_NHASH
; i
++) {
3240 for (fp
= TAILQ_FIRST(&ipq
[i
]); fp
;) {
3244 fp
= TAILQ_NEXT(fp
, ipq_list
);
3245 if (--fpp
->ipq_ttl
== 0) {
3246 ipstat
.ips_fragtimeout
+= fpp
->ipq_nfrags
;
3247 frag_freef(&ipq
[i
], fpp
);
3252 * If we are over the maximum number of fragments
3253 * (due to the limit being lowered), drain off
3254 * enough to get down to the new limit.
3256 if (maxnipq
>= 0 && nipq
> (unsigned)maxnipq
) {
3257 for (i
= 0; i
< IPREASS_NHASH
; i
++) {
3258 while (nipq
> (unsigned)maxnipq
&&
3259 !TAILQ_EMPTY(&ipq
[i
])) {
3260 ipstat
.ips_fragdropped
+=
3261 TAILQ_FIRST(&ipq
[i
])->ipq_nfrags
;
3262 frag_freef(&ipq
[i
], TAILQ_FIRST(&ipq
[i
]));
3266 /* re-arm the purge timer if there's work to do */
3267 frag_timeout_run
= 0;
3268 frag_sched_timeout();
3269 lck_mtx_unlock(&ipqlock
);
3273 frag_sched_timeout(void)
3275 LCK_MTX_ASSERT(&ipqlock
, LCK_MTX_ASSERT_OWNED
);
3277 if (!frag_timeout_run
&& nipq
> 0) {
3278 frag_timeout_run
= 1;
3279 timeout(frag_timeout
, NULL
, hz
);
3284 * Drain off all datagram fragments.
3291 lck_mtx_lock(&ipqlock
);
3292 for (i
= 0; i
< IPREASS_NHASH
; i
++) {
3293 while (!TAILQ_EMPTY(&ipq
[i
])) {
3294 ipstat
.ips_fragdropped
+=
3295 TAILQ_FIRST(&ipq
[i
])->ipq_nfrags
;
3296 frag_freef(&ipq
[i
], TAILQ_FIRST(&ipq
[i
]));
3299 lck_mtx_unlock(&ipqlock
);
3309 * See comments in ipq_updateparams(). Keep the count separate
3310 * from nipq since the latter represents the elements already
3311 * in the reassembly queues.
3313 if (ipq_limit
> 0 && ipq_count
> ipq_limit
) {
3317 t
= m_get(how
, MT_FTABLE
);
3319 atomic_add_32(&ipq_count
, 1);
3320 fp
= mtod(t
, struct ipq
*);
3321 bzero(fp
, sizeof(*fp
));
3329 ipq_free(struct ipq
*fp
)
3331 (void) m_free(dtom(fp
));
3332 atomic_add_32(&ipq_count
, -1);
3341 frag_drain(); /* fragments */
3342 in_rtqdrain(); /* protocol cloned routes */
3343 in_arpdrain(NULL
); /* cloned routes: ARP */
3347 * Do option processing on a datagram,
3348 * possibly discarding it if bad options are encountered,
3349 * or forwarding it if source-routed.
3350 * The pass argument is used when operating in the IPSTEALTH
3351 * mode to tell what options to process:
3352 * [LS]SRR (pass 0) or the others (pass 1).
3353 * The reason for as many as two passes is that when doing IPSTEALTH,
3354 * non-routing options should be processed only if the packet is for us.
3355 * Returns 1 if packet has been forwarded/freed,
3356 * 0 if the packet should be processed further.
3359 ip_dooptions(struct mbuf
*m
, int pass
, struct sockaddr_in
*next_hop
)
3361 #pragma unused(pass)
3362 struct ip
*ip
= mtod(m
, struct ip
*);
3364 struct ip_timestamp
*ipt
;
3365 struct in_ifaddr
*ia
;
3366 int opt
, optlen
, cnt
, off
, code
, type
= ICMP_PARAMPROB
, forward
= 0;
3367 struct in_addr
*sin
, dst
;
3369 struct sockaddr_in ipaddr
= {
3370 .sin_len
= sizeof(ipaddr
),
3371 .sin_family
= AF_INET
,
3373 .sin_addr
= { .s_addr
= 0 },
3377 /* Expect 32-bit aligned data pointer on strict-align platforms */
3378 MBUF_STRICT_DATA_ALIGNMENT_CHECK_32(m
);
3381 cp
= (u_char
*)(ip
+ 1);
3382 cnt
= (IP_VHL_HL(ip
->ip_vhl
) << 2) - sizeof(struct ip
);
3383 for (; cnt
> 0; cnt
-= optlen
, cp
+= optlen
) {
3384 opt
= cp
[IPOPT_OPTVAL
];
3385 if (opt
== IPOPT_EOL
) {
3388 if (opt
== IPOPT_NOP
) {
3391 if (cnt
< IPOPT_OLEN
+ sizeof(*cp
)) {
3392 code
= &cp
[IPOPT_OLEN
] - (u_char
*)ip
;
3395 optlen
= cp
[IPOPT_OLEN
];
3396 if (optlen
< IPOPT_OLEN
+ sizeof(*cp
) ||
3398 code
= &cp
[IPOPT_OLEN
] - (u_char
*)ip
;
3407 * Source routing with record.
3408 * Find interface with current destination address.
3409 * If none on this machine then drop if strictly routed,
3410 * or do nothing if loosely routed.
3411 * Record interface address and bring up next address
3412 * component. If strictly routed make sure next
3413 * address is on directly accessible net.
3417 if (optlen
< IPOPT_OFFSET
+ sizeof(*cp
)) {
3418 code
= &cp
[IPOPT_OLEN
] - (u_char
*)ip
;
3421 if ((off
= cp
[IPOPT_OFFSET
]) < IPOPT_MINOFF
) {
3422 code
= &cp
[IPOPT_OFFSET
] - (u_char
*)ip
;
3425 ipaddr
.sin_addr
= ip
->ip_dst
;
3426 ia
= (struct in_ifaddr
*)ifa_ifwithaddr(SA(&ipaddr
));
3428 if (opt
== IPOPT_SSRR
) {
3429 type
= ICMP_UNREACH
;
3430 code
= ICMP_UNREACH_SRCFAIL
;
3433 if (!ip_dosourceroute
) {
3434 goto nosourcerouting
;
3437 * Loose routing, and not at next destination
3438 * yet; nothing to do except forward.
3442 IFA_REMREF(&ia
->ia_ifa
);
3445 off
--; /* 0 origin */
3446 if (off
> optlen
- (int)sizeof(struct in_addr
)) {
3448 * End of source route. Should be for us.
3450 if (!ip_acceptsourceroute
) {
3451 goto nosourcerouting
;
3453 save_rte(cp
, ip
->ip_src
);
3457 if (!ip_dosourceroute
) {
3459 char buf
[MAX_IPv4_STR_LEN
];
3460 char buf2
[MAX_IPv4_STR_LEN
];
3462 * Acting as a router, so generate ICMP
3466 "attempted source route from %s "
3468 inet_ntop(AF_INET
, &ip
->ip_src
,
3470 inet_ntop(AF_INET
, &ip
->ip_dst
,
3471 buf2
, sizeof(buf2
)));
3472 type
= ICMP_UNREACH
;
3473 code
= ICMP_UNREACH_SRCFAIL
;
3477 * Not acting as a router,
3480 OSAddAtomic(1, &ipstat
.ips_cantforward
);
3487 * locate outgoing interface
3489 (void) memcpy(&ipaddr
.sin_addr
, cp
+ off
,
3490 sizeof(ipaddr
.sin_addr
));
3492 if (opt
== IPOPT_SSRR
) {
3493 #define INA struct in_ifaddr *
3494 if ((ia
= (INA
)ifa_ifwithdstaddr(
3495 SA(&ipaddr
))) == NULL
) {
3496 ia
= (INA
)ifa_ifwithnet(SA(&ipaddr
));
3499 ia
= ip_rtaddr(ipaddr
.sin_addr
);
3502 type
= ICMP_UNREACH
;
3503 code
= ICMP_UNREACH_SRCFAIL
;
3506 ip
->ip_dst
= ipaddr
.sin_addr
;
3507 IFA_LOCK(&ia
->ia_ifa
);
3508 (void) memcpy(cp
+ off
, &(IA_SIN(ia
)->sin_addr
),
3509 sizeof(struct in_addr
));
3510 IFA_UNLOCK(&ia
->ia_ifa
);
3511 IFA_REMREF(&ia
->ia_ifa
);
3513 cp
[IPOPT_OFFSET
] += sizeof(struct in_addr
);
3515 * Let ip_intr's mcast routing check handle mcast pkts
3517 forward
= !IN_MULTICAST(ntohl(ip
->ip_dst
.s_addr
));
3521 if (optlen
< IPOPT_OFFSET
+ sizeof(*cp
)) {
3522 code
= &cp
[IPOPT_OFFSET
] - (u_char
*)ip
;
3525 if ((off
= cp
[IPOPT_OFFSET
]) < IPOPT_MINOFF
) {
3526 code
= &cp
[IPOPT_OFFSET
] - (u_char
*)ip
;
3530 * If no space remains, ignore.
3532 off
--; /* 0 origin */
3533 if (off
> optlen
- (int)sizeof(struct in_addr
)) {
3536 (void) memcpy(&ipaddr
.sin_addr
, &ip
->ip_dst
,
3537 sizeof(ipaddr
.sin_addr
));
3539 * locate outgoing interface; if we're the destination,
3540 * use the incoming interface (should be same).
3542 if ((ia
= (INA
)ifa_ifwithaddr(SA(&ipaddr
))) == NULL
) {
3543 if ((ia
= ip_rtaddr(ipaddr
.sin_addr
)) == NULL
) {
3544 type
= ICMP_UNREACH
;
3545 code
= ICMP_UNREACH_HOST
;
3549 IFA_LOCK(&ia
->ia_ifa
);
3550 (void) memcpy(cp
+ off
, &(IA_SIN(ia
)->sin_addr
),
3551 sizeof(struct in_addr
));
3552 IFA_UNLOCK(&ia
->ia_ifa
);
3553 IFA_REMREF(&ia
->ia_ifa
);
3555 cp
[IPOPT_OFFSET
] += sizeof(struct in_addr
);
3559 code
= cp
- (u_char
*)ip
;
3560 ipt
= (struct ip_timestamp
*)(void *)cp
;
3561 if (ipt
->ipt_len
< 4 || ipt
->ipt_len
> 40) {
3562 code
= (u_char
*)&ipt
->ipt_len
- (u_char
*)ip
;
3565 if (ipt
->ipt_ptr
< 5) {
3566 code
= (u_char
*)&ipt
->ipt_ptr
- (u_char
*)ip
;
3570 ipt
->ipt_len
- (int)sizeof(int32_t)) {
3571 if (++ipt
->ipt_oflw
== 0) {
3572 code
= (u_char
*)&ipt
->ipt_ptr
-
3578 sin
= (struct in_addr
*)(void *)(cp
+ ipt
->ipt_ptr
- 1);
3579 switch (ipt
->ipt_flg
) {
3580 case IPOPT_TS_TSONLY
:
3583 case IPOPT_TS_TSANDADDR
:
3584 if (ipt
->ipt_ptr
- 1 + sizeof(n_time
) +
3585 sizeof(struct in_addr
) > ipt
->ipt_len
) {
3586 code
= (u_char
*)&ipt
->ipt_ptr
-
3590 ipaddr
.sin_addr
= dst
;
3591 ia
= (INA
)ifaof_ifpforaddr(SA(&ipaddr
),
3596 IFA_LOCK(&ia
->ia_ifa
);
3597 (void) memcpy(sin
, &IA_SIN(ia
)->sin_addr
,
3598 sizeof(struct in_addr
));
3599 IFA_UNLOCK(&ia
->ia_ifa
);
3600 ipt
->ipt_ptr
+= sizeof(struct in_addr
);
3601 IFA_REMREF(&ia
->ia_ifa
);
3605 case IPOPT_TS_PRESPEC
:
3606 if (ipt
->ipt_ptr
- 1 + sizeof(n_time
) +
3607 sizeof(struct in_addr
) > ipt
->ipt_len
) {
3608 code
= (u_char
*)&ipt
->ipt_ptr
-
3612 (void) memcpy(&ipaddr
.sin_addr
, sin
,
3613 sizeof(struct in_addr
));
3614 if ((ia
= (struct in_ifaddr
*)ifa_ifwithaddr(
3615 SA(&ipaddr
))) == NULL
) {
3618 IFA_REMREF(&ia
->ia_ifa
);
3620 ipt
->ipt_ptr
+= sizeof(struct in_addr
);
3624 /* XXX can't take &ipt->ipt_flg */
3625 code
= (u_char
*)&ipt
->ipt_ptr
-
3630 (void) memcpy(cp
+ ipt
->ipt_ptr
- 1, &ntime
,
3632 ipt
->ipt_ptr
+= sizeof(n_time
);
3635 if (forward
&& ipforwarding
) {
3636 ip_forward(m
, 1, next_hop
);
3641 icmp_error(m
, type
, code
, 0, 0);
3642 OSAddAtomic(1, &ipstat
.ips_badoptions
);
3647 * Check for the presence of the IP Router Alert option [RFC2113]
3648 * in the header of an IPv4 datagram.
3650 * This call is not intended for use from the forwarding path; it is here
3651 * so that protocol domains may check for the presence of the option.
3652 * Given how FreeBSD's IPv4 stack is currently structured, the Router Alert
3653 * option does not have much relevance to the implementation, though this
3654 * may change in future.
3655 * Router alert options SHOULD be passed if running in IPSTEALTH mode and
3656 * we are not the endpoint.
3657 * Length checks on individual options should already have been peformed
3658 * by ip_dooptions() therefore they are folded under DIAGNOSTIC here.
3660 * Return zero if not present or options are invalid, non-zero if present.
3663 ip_checkrouteralert(struct mbuf
*m
)
3665 struct ip
*ip
= mtod(m
, struct ip
*);
3667 int opt
, optlen
, cnt
, found_ra
;
3670 cp
= (u_char
*)(ip
+ 1);
3671 cnt
= (IP_VHL_HL(ip
->ip_vhl
) << 2) - sizeof(struct ip
);
3672 for (; cnt
> 0; cnt
-= optlen
, cp
+= optlen
) {
3673 opt
= cp
[IPOPT_OPTVAL
];
3674 if (opt
== IPOPT_EOL
) {
3677 if (opt
== IPOPT_NOP
) {
3681 if (cnt
< IPOPT_OLEN
+ sizeof(*cp
)) {
3685 optlen
= cp
[IPOPT_OLEN
];
3687 if (optlen
< IPOPT_OLEN
+ sizeof(*cp
) || optlen
> cnt
) {
3695 if (optlen
!= IPOPT_OFFSET
+ sizeof(uint16_t) ||
3696 (*((uint16_t *)(void *)&cp
[IPOPT_OFFSET
]) != 0)) {
3711 * Given address of next destination (final or next hop),
3712 * return internet address info of interface to be used to get there.
3715 ip_rtaddr(struct in_addr dst
)
3717 struct sockaddr_in
*sin
;
3718 struct ifaddr
*rt_ifa
;
3721 bzero(&ro
, sizeof(ro
));
3722 sin
= SIN(&ro
.ro_dst
);
3723 sin
->sin_family
= AF_INET
;
3724 sin
->sin_len
= sizeof(*sin
);
3725 sin
->sin_addr
= dst
;
3727 rtalloc_ign(&ro
, RTF_PRCLONING
);
3728 if (ro
.ro_rt
== NULL
) {
3734 if ((rt_ifa
= ro
.ro_rt
->rt_ifa
) != NULL
) {
3737 RT_UNLOCK(ro
.ro_rt
);
3740 return (struct in_ifaddr
*)rt_ifa
;
3744 * Save incoming source route for use in replies,
3745 * to be picked up later by ip_srcroute if the receiver is interested.
3748 save_rte(u_char
*option
, struct in_addr dst
)
3752 olen
= option
[IPOPT_OLEN
];
3755 printf("save_rte: olen %d\n", olen
);
3758 if (olen
> sizeof(ip_srcrt
) - (1 + sizeof(dst
))) {
3761 bcopy(option
, ip_srcrt
.srcopt
, olen
);
3762 ip_nhops
= (olen
- IPOPT_OFFSET
- 1) / sizeof(struct in_addr
);
3767 * Retrieve incoming source route for use in replies,
3768 * in the same form used by setsockopt.
3769 * The first hop is placed before the options, will be removed later.
3774 struct in_addr
*p
, *q
;
3777 if (ip_nhops
== 0) {
3781 m
= m_get(M_DONTWAIT
, MT_HEADER
);
3786 #define OPTSIZ (sizeof (ip_srcrt.nop) + sizeof (ip_srcrt.srcopt))
3788 /* length is (nhops+1)*sizeof(addr) + sizeof(nop + srcrt header) */
3789 m
->m_len
= ip_nhops
* sizeof(struct in_addr
) +
3790 sizeof(struct in_addr
) + OPTSIZ
;
3793 printf("ip_srcroute: nhops %d mlen %d", ip_nhops
, m
->m_len
);
3798 * First save first hop for return route
3800 p
= &ip_srcrt
.route
[ip_nhops
- 1];
3801 *(mtod(m
, struct in_addr
*)) = *p
--;
3805 (u_int32_t
)ntohl(mtod(m
, struct in_addr
*)->s_addr
));
3810 * Copy option fields and padding (nop) to mbuf.
3812 ip_srcrt
.nop
= IPOPT_NOP
;
3813 ip_srcrt
.srcopt
[IPOPT_OFFSET
] = IPOPT_MINOFF
;
3814 (void) memcpy(mtod(m
, caddr_t
) + sizeof(struct in_addr
),
3815 &ip_srcrt
.nop
, OPTSIZ
);
3816 q
= (struct in_addr
*)(void *)(mtod(m
, caddr_t
) +
3817 sizeof(struct in_addr
) + OPTSIZ
);
3820 * Record return path as an IP source route,
3821 * reversing the path (pointers are now aligned).
3823 while (p
>= ip_srcrt
.route
) {
3826 printf(" %lx", (u_int32_t
)ntohl(q
->s_addr
));
3832 * Last hop goes to final destination.
3837 printf(" %lx\n", (u_int32_t
)ntohl(q
->s_addr
));
3844 * Strip out IP options, at higher level protocol in the kernel.
3847 ip_stripoptions(struct mbuf
*m
)
3850 struct ip
*ip
= mtod(m
, struct ip
*);
3854 /* Expect 32-bit aligned data pointer on strict-align platforms */
3855 MBUF_STRICT_DATA_ALIGNMENT_CHECK_32(m
);
3857 /* use bcopy() since it supports overlapping range */
3858 olen
= (IP_VHL_HL(ip
->ip_vhl
) << 2) - sizeof(struct ip
);
3859 opts
= (caddr_t
)(ip
+ 1);
3860 i
= m
->m_len
- (sizeof(struct ip
) + olen
);
3861 bcopy(opts
+ olen
, opts
, (unsigned)i
);
3863 if (m
->m_flags
& M_PKTHDR
) {
3864 m
->m_pkthdr
.len
-= olen
;
3866 ip
->ip_vhl
= IP_MAKE_VHL(IPVERSION
, sizeof(struct ip
) >> 2);
3869 * We expect ip_{off,len} to be in host order by now, and
3870 * that the original IP header length has been subtracted
3871 * out from ip_len. Temporarily adjust ip_len for checksum
3872 * recalculation, and restore it afterwards.
3874 ip
->ip_len
+= sizeof(struct ip
);
3876 /* recompute checksum now that IP header is smaller */
3877 #if BYTE_ORDER != BIG_ENDIAN
3880 #endif /* BYTE_ORDER != BIG_ENDIAN */
3881 ip
->ip_sum
= in_cksum_hdr(ip
);
3882 #if BYTE_ORDER != BIG_ENDIAN
3885 #endif /* BYTE_ORDER != BIG_ENDIAN */
3887 ip
->ip_len
-= sizeof(struct ip
);
3890 * Given that we've just stripped IP options from the header,
3891 * we need to adjust the start offset accordingly if this
3892 * packet had gone thru partial checksum offload.
3894 if ((m
->m_pkthdr
.csum_flags
& (CSUM_DATA_VALID
| CSUM_PARTIAL
)) ==
3895 (CSUM_DATA_VALID
| CSUM_PARTIAL
)) {
3896 if (m
->m_pkthdr
.csum_rx_start
>= (sizeof(struct ip
) + olen
)) {
3897 /* most common case */
3898 m
->m_pkthdr
.csum_rx_start
-= olen
;
3900 /* compute checksum in software instead */
3901 m
->m_pkthdr
.csum_flags
&= ~CSUM_DATA_VALID
;
3902 m
->m_pkthdr
.csum_data
= 0;
3903 ipstat
.ips_adj_hwcsum_clr
++;
3908 u_char inetctlerrmap
[PRC_NCMDS
] = {
3910 0, EMSGSIZE
, EHOSTDOWN
, EHOSTUNREACH
,
3911 ENETUNREACH
, EHOSTUNREACH
, ECONNREFUSED
, ECONNREFUSED
,
3912 EMSGSIZE
, EHOSTUNREACH
, 0, 0,
3913 0, 0, EHOSTUNREACH
, 0,
3914 ENOPROTOOPT
, ECONNREFUSED
3918 sysctl_ipforwarding SYSCTL_HANDLER_ARGS
3920 #pragma unused(arg1, arg2)
3921 int i
, was_ipforwarding
= ipforwarding
;
3923 i
= sysctl_handle_int(oidp
, oidp
->oid_arg1
, oidp
->oid_arg2
, req
);
3924 if (i
!= 0 || req
->newptr
== USER_ADDR_NULL
) {
3928 if (was_ipforwarding
&& !ipforwarding
) {
3929 /* clean up IPv4 forwarding cached routes */
3930 ifnet_head_lock_shared();
3931 for (i
= 0; i
<= if_index
; i
++) {
3932 struct ifnet
*ifp
= ifindex2ifnet
[i
];
3934 lck_mtx_lock(&ifp
->if_cached_route_lock
);
3935 ROUTE_RELEASE(&ifp
->if_fwd_route
);
3936 bzero(&ifp
->if_fwd_route
,
3937 sizeof(ifp
->if_fwd_route
));
3938 lck_mtx_unlock(&ifp
->if_cached_route_lock
);
3948 * Similar to inp_route_{copyout,copyin} routines except that these copy
3949 * out the cached IPv4 forwarding route from struct ifnet instead of the
3950 * inpcb. See comments for those routines for explanations.
3953 ip_fwd_route_copyout(struct ifnet
*ifp
, struct route
*dst
)
3955 struct route
*src
= &ifp
->if_fwd_route
;
3957 lck_mtx_lock_spin(&ifp
->if_cached_route_lock
);
3958 lck_mtx_convert_spin(&ifp
->if_cached_route_lock
);
3960 /* Minor sanity check */
3961 if (src
->ro_rt
!= NULL
&& rt_key(src
->ro_rt
)->sa_family
!= AF_INET
) {
3962 panic("%s: wrong or corrupted route: %p", __func__
, src
);
3965 route_copyout(dst
, src
, sizeof(*dst
));
3967 lck_mtx_unlock(&ifp
->if_cached_route_lock
);
3971 ip_fwd_route_copyin(struct ifnet
*ifp
, struct route
*src
)
3973 struct route
*dst
= &ifp
->if_fwd_route
;
3975 lck_mtx_lock_spin(&ifp
->if_cached_route_lock
);
3976 lck_mtx_convert_spin(&ifp
->if_cached_route_lock
);
3978 /* Minor sanity check */
3979 if (src
->ro_rt
!= NULL
&& rt_key(src
->ro_rt
)->sa_family
!= AF_INET
) {
3980 panic("%s: wrong or corrupted route: %p", __func__
, src
);
3983 if (ifp
->if_fwd_cacheok
) {
3984 route_copyin(src
, dst
, sizeof(*src
));
3987 lck_mtx_unlock(&ifp
->if_cached_route_lock
);
3991 * Forward a packet. If some error occurs return the sender
3992 * an icmp packet. Note we can't always generate a meaningful
3993 * icmp message because icmp doesn't have a large enough repertoire
3994 * of codes and types.
3996 * If not forwarding, just drop the packet. This could be confusing
3997 * if ipforwarding was zero but some routing protocol was advancing
3998 * us as a gateway to somewhere. However, we must let the routing
3999 * protocol deal with that.
4001 * The srcrt parameter indicates whether the packet is being forwarded
4002 * via a source route.
4005 ip_forward(struct mbuf
*m
, int srcrt
, struct sockaddr_in
*next_hop
)
4008 #pragma unused(next_hop)
4010 struct ip
*ip
= mtod(m
, struct ip
*);
4011 struct sockaddr_in
*sin
;
4013 struct route fwd_rt
;
4014 int error
, type
= 0, code
= 0;
4017 struct in_addr pkt_dst
;
4018 u_int32_t nextmtu
= 0, len
;
4019 struct ip_out_args ipoa
;
4020 struct ifnet
*rcvifp
= m
->m_pkthdr
.rcvif
;
4022 bzero(&ipoa
, sizeof(ipoa
));
4023 ipoa
.ipoa_boundif
= IFSCOPE_NONE
;
4024 ipoa
.ipoa_sotc
= SO_TC_UNSPEC
;
4025 ipoa
.ipoa_netsvctype
= _NET_SERVICE_TYPE_UNSPEC
;
4028 struct secpolicy
*sp
= NULL
;
4032 struct pf_mtag
*pf_mtag
;
4038 * Cache the destination address of the packet; this may be
4039 * changed by use of 'ipfw fwd'.
4041 pkt_dst
= ((next_hop
!= NULL
) ? next_hop
->sin_addr
: ip
->ip_dst
);
4042 #else /* !IPFIREWALL */
4043 pkt_dst
= ip
->ip_dst
;
4044 #endif /* !IPFIREWALL */
4048 printf("forward: src %lx dst %lx ttl %x\n",
4049 (u_int32_t
)ip
->ip_src
.s_addr
, (u_int32_t
)pkt_dst
.s_addr
,
4054 if (m
->m_flags
& (M_BCAST
| M_MCAST
) || !in_canforward(pkt_dst
)) {
4055 OSAddAtomic(1, &ipstat
.ips_cantforward
);
4061 #endif /* IPSTEALTH */
4062 if (ip
->ip_ttl
<= IPTTLDEC
) {
4063 icmp_error(m
, ICMP_TIMXCEED
, ICMP_TIMXCEED_INTRANS
,
4069 #endif /* IPSTEALTH */
4072 pf_mtag
= pf_find_mtag(m
);
4073 if (pf_mtag
!= NULL
&& pf_mtag
->pftag_rtableid
!= IFSCOPE_NONE
) {
4074 ipoa
.ipoa_boundif
= pf_mtag
->pftag_rtableid
;
4075 ipoa
.ipoa_flags
|= IPOAF_BOUND_IF
;
4079 ip_fwd_route_copyout(rcvifp
, &fwd_rt
);
4081 sin
= SIN(&fwd_rt
.ro_dst
);
4082 if (ROUTE_UNUSABLE(&fwd_rt
) || pkt_dst
.s_addr
!= sin
->sin_addr
.s_addr
) {
4083 ROUTE_RELEASE(&fwd_rt
);
4085 sin
->sin_family
= AF_INET
;
4086 sin
->sin_len
= sizeof(*sin
);
4087 sin
->sin_addr
= pkt_dst
;
4089 rtalloc_scoped_ign(&fwd_rt
, RTF_PRCLONING
, ipoa
.ipoa_boundif
);
4090 if (fwd_rt
.ro_rt
== NULL
) {
4091 icmp_error(m
, ICMP_UNREACH
, ICMP_UNREACH_HOST
, dest
, 0);
4098 * Save the IP header and at most 8 bytes of the payload,
4099 * in case we need to generate an ICMP message to the src.
4101 * We don't use m_copy() because it might return a reference
4102 * to a shared cluster. Both this function and ip_output()
4103 * assume exclusive access to the IP header in `m', so any
4104 * data in a cluster may change before we reach icmp_error().
4106 MGET(mcopy
, M_DONTWAIT
, m
->m_type
);
4107 if (mcopy
!= NULL
) {
4108 M_COPY_PKTHDR(mcopy
, m
);
4109 mcopy
->m_len
= imin((IP_VHL_HL(ip
->ip_vhl
) << 2) + 8,
4111 m_copydata(m
, 0, mcopy
->m_len
, mtod(mcopy
, caddr_t
));
4116 #endif /* IPSTEALTH */
4117 ip
->ip_ttl
-= IPTTLDEC
;
4120 #endif /* IPSTEALTH */
4123 * If forwarding packet using same interface that it came in on,
4124 * perhaps should send a redirect to sender to shortcut a hop.
4125 * Only send redirect if source is sending directly to us,
4126 * and if packet was not source routed (or has any options).
4127 * Also, don't send redirect if forwarding using a default route
4128 * or a route modified by a redirect.
4131 if (rt
->rt_ifp
== m
->m_pkthdr
.rcvif
&&
4132 !(rt
->rt_flags
& (RTF_DYNAMIC
| RTF_MODIFIED
)) &&
4133 satosin(rt_key(rt
))->sin_addr
.s_addr
!= INADDR_ANY
&&
4134 ipsendredirects
&& !srcrt
&& rt
->rt_ifa
!= NULL
) {
4135 struct in_ifaddr
*ia
= (struct in_ifaddr
*)rt
->rt_ifa
;
4136 u_int32_t src
= ntohl(ip
->ip_src
.s_addr
);
4138 /* Become a regular mutex */
4139 RT_CONVERT_LOCK(rt
);
4140 IFA_LOCK_SPIN(&ia
->ia_ifa
);
4141 if ((src
& ia
->ia_subnetmask
) == ia
->ia_subnet
) {
4142 if (rt
->rt_flags
& RTF_GATEWAY
) {
4143 dest
= satosin(rt
->rt_gateway
)->sin_addr
.s_addr
;
4145 dest
= pkt_dst
.s_addr
;
4148 * Router requirements says to only send
4151 type
= ICMP_REDIRECT
;
4152 code
= ICMP_REDIRECT_HOST
;
4155 printf("redirect (%d) to %lx\n", code
,
4160 IFA_UNLOCK(&ia
->ia_ifa
);
4165 if (next_hop
!= NULL
) {
4166 /* Pass IPFORWARD info if available */
4168 struct ip_fwd_tag
*ipfwd_tag
;
4170 tag
= m_tag_create(KERNEL_MODULE_TAG_ID
,
4171 KERNEL_TAG_TYPE_IPFORWARD
,
4172 sizeof(*ipfwd_tag
), M_NOWAIT
, m
);
4179 ipfwd_tag
= (struct ip_fwd_tag
*)(tag
+ 1);
4180 ipfwd_tag
->next_hop
= next_hop
;
4182 m_tag_prepend(m
, tag
);
4184 #endif /* IPFIREWALL */
4186 /* Mark this packet as being forwarded from another interface */
4187 m
->m_pkthdr
.pkt_flags
|= PKTF_FORWARDED
;
4190 error
= ip_output(m
, NULL
, &fwd_rt
, IP_FORWARDING
| IP_OUTARGS
,
4193 /* Refresh rt since the route could have changed while in IP */
4197 OSAddAtomic(1, &ipstat
.ips_cantforward
);
4200 * Increment stats on the source interface; the ones
4201 * for destination interface has been taken care of
4202 * during output above by virtue of PKTF_FORWARDED.
4204 rcvifp
->if_fpackets
++;
4205 rcvifp
->if_fbytes
+= len
;
4207 OSAddAtomic(1, &ipstat
.ips_forward
);
4209 OSAddAtomic(1, &ipstat
.ips_redirectsent
);
4211 if (mcopy
!= NULL
) {
4213 * If we didn't have to go thru ipflow and
4214 * the packet was successfully consumed by
4215 * ip_output, the mcopy is rather a waste;
4216 * this could be further optimized.
4223 if (mcopy
== NULL
) {
4228 case 0: /* forwarded, but need redirect */
4229 /* type, code set above */
4232 case ENETUNREACH
: /* shouldn't happen, checked above */
4237 type
= ICMP_UNREACH
;
4238 code
= ICMP_UNREACH_HOST
;
4242 type
= ICMP_UNREACH
;
4243 code
= ICMP_UNREACH_NEEDFRAG
;
4249 if (rt
->rt_ifp
!= NULL
) {
4250 nextmtu
= rt
->rt_ifp
->if_mtu
;
4260 * If the packet is routed over IPsec tunnel, tell the
4261 * originator the tunnel MTU.
4262 * tunnel MTU = if MTU - sizeof(IP) - ESP/AH hdrsiz
4265 sp
= ipsec4_getpolicybyaddr(mcopy
, IPSEC_DIR_OUTBOUND
,
4266 IP_FORWARDING
, &ipsecerror
);
4273 * find the correct route for outer IPv4
4274 * header, compute tunnel MTU.
4278 if (sp
->req
!= NULL
&&
4279 sp
->req
->saidx
.mode
== IPSEC_MODE_TUNNEL
) {
4280 struct secasindex saidx
;
4281 struct secasvar
*sav
;
4286 /* count IPsec header size */
4287 ipsechdr
= ipsec_hdrsiz(sp
);
4289 ipm
= mtod(mcopy
, struct ip
*);
4290 bcopy(&sp
->req
->saidx
, &saidx
, sizeof(saidx
));
4291 saidx
.mode
= sp
->req
->saidx
.mode
;
4292 saidx
.reqid
= sp
->req
->saidx
.reqid
;
4293 sin
= SIN(&saidx
.src
);
4294 if (sin
->sin_len
== 0) {
4295 sin
->sin_len
= sizeof(*sin
);
4296 sin
->sin_family
= AF_INET
;
4297 sin
->sin_port
= IPSEC_PORT_ANY
;
4298 bcopy(&ipm
->ip_src
, &sin
->sin_addr
,
4299 sizeof(sin
->sin_addr
));
4301 sin
= SIN(&saidx
.dst
);
4302 if (sin
->sin_len
== 0) {
4303 sin
->sin_len
= sizeof(*sin
);
4304 sin
->sin_family
= AF_INET
;
4305 sin
->sin_port
= IPSEC_PORT_ANY
;
4306 bcopy(&ipm
->ip_dst
, &sin
->sin_addr
,
4307 sizeof(sin
->sin_addr
));
4309 sav
= key_allocsa_policy(&saidx
);
4311 lck_mtx_lock(sadb_mutex
);
4312 if (sav
->sah
!= NULL
) {
4313 ro
= (struct route
*)&sav
->sah
->sa_route
;
4314 if (ro
->ro_rt
!= NULL
) {
4316 if (ro
->ro_rt
->rt_ifp
!= NULL
) {
4317 nextmtu
= ro
->ro_rt
->
4319 nextmtu
-= ipsechdr
;
4321 RT_UNLOCK(ro
->ro_rt
);
4324 key_freesav(sav
, KEY_SADB_LOCKED
);
4325 lck_mtx_unlock(sadb_mutex
);
4328 key_freesp(sp
, KEY_SADB_UNLOCKED
);
4334 * A router should not generate ICMP_SOURCEQUENCH as
4335 * required in RFC1812 Requirements for IP Version 4 Routers.
4336 * Source quench could be a big problem under DoS attacks,
4337 * or if the underlying interface is rate-limited.
4338 * Those who need source quench packets may re-enable them
4339 * via the net.inet.ip.sendsourcequench sysctl.
4341 if (ip_sendsourcequench
== 0) {
4345 type
= ICMP_SOURCEQUENCH
;
4350 case EACCES
: /* ipfw denied packet */
4355 if (type
== ICMP_UNREACH
&& code
== ICMP_UNREACH_NEEDFRAG
) {
4356 OSAddAtomic(1, &ipstat
.ips_cantfrag
);
4359 icmp_error(mcopy
, type
, code
, dest
, nextmtu
);
4361 ip_fwd_route_copyin(rcvifp
, &fwd_rt
);
4365 ip_savecontrol(struct inpcb
*inp
, struct mbuf
**mp
, struct ip
*ip
,
4369 if (inp
->inp_socket
->so_options
& SO_TIMESTAMP
) {
4373 mp
= sbcreatecontrol_mbuf((caddr_t
)&tv
, sizeof(tv
),
4374 SCM_TIMESTAMP
, SOL_SOCKET
, mp
);
4379 if (inp
->inp_socket
->so_options
& SO_TIMESTAMP_MONOTONIC
) {
4382 time
= mach_absolute_time();
4383 mp
= sbcreatecontrol_mbuf((caddr_t
)&time
, sizeof(time
),
4384 SCM_TIMESTAMP_MONOTONIC
, SOL_SOCKET
, mp
);
4389 if (inp
->inp_socket
->so_options
& SO_TIMESTAMP_CONTINUOUS
) {
4392 time
= mach_continuous_time();
4393 mp
= sbcreatecontrol_mbuf((caddr_t
)&time
, sizeof(time
),
4394 SCM_TIMESTAMP_CONTINUOUS
, SOL_SOCKET
, mp
);
4399 if (inp
->inp_flags
& INP_RECVDSTADDR
) {
4400 mp
= sbcreatecontrol_mbuf((caddr_t
)&ip
->ip_dst
,
4401 sizeof(struct in_addr
), IP_RECVDSTADDR
, IPPROTO_IP
, mp
);
4409 * Moving these out of udp_input() made them even more broken
4410 * than they already were.
4412 /* options were tossed already */
4413 if (inp
->inp_flags
& INP_RECVOPTS
) {
4414 mp
= sbcreatecontrol_mbuf((caddr_t
)opts_deleted_above
,
4415 sizeof(struct in_addr
), IP_RECVOPTS
, IPPROTO_IP
, mp
);
4420 /* ip_srcroute doesn't do what we want here, need to fix */
4421 if (inp
->inp_flags
& INP_RECVRETOPTS
) {
4422 mp
= sbcreatecontrol_mbuf((caddr_t
)ip_srcroute(),
4423 sizeof(struct in_addr
), IP_RECVRETOPTS
, IPPROTO_IP
, mp
);
4429 if (inp
->inp_flags
& INP_RECVIF
) {
4431 uint8_t sdlbuf
[SOCK_MAXADDRLEN
+ 1];
4432 struct sockaddr_dl
*sdl2
= SDL(&sdlbuf
);
4435 * Make sure to accomodate the largest possible
4436 * size of SA(if_lladdr)->sa_len.
4438 _CASSERT(sizeof(sdlbuf
) == (SOCK_MAXADDRLEN
+ 1));
4440 ifnet_head_lock_shared();
4441 if ((ifp
= m
->m_pkthdr
.rcvif
) != NULL
&&
4442 ifp
->if_index
&& (ifp
->if_index
<= if_index
)) {
4443 struct ifaddr
*ifa
= ifnet_addrs
[ifp
->if_index
- 1];
4444 struct sockaddr_dl
*sdp
;
4446 if (!ifa
|| !ifa
->ifa_addr
) {
4451 sdp
= SDL(ifa
->ifa_addr
);
4453 * Change our mind and don't try copy.
4455 if (sdp
->sdl_family
!= AF_LINK
) {
4459 /* the above _CASSERT ensures sdl_len fits in sdlbuf */
4460 bcopy(sdp
, sdl2
, sdp
->sdl_len
);
4465 offsetof(struct sockaddr_dl
, sdl_data
[0]);
4466 sdl2
->sdl_family
= AF_LINK
;
4467 sdl2
->sdl_index
= 0;
4468 sdl2
->sdl_nlen
= sdl2
->sdl_alen
= sdl2
->sdl_slen
= 0;
4471 mp
= sbcreatecontrol_mbuf((caddr_t
)sdl2
, sdl2
->sdl_len
,
4472 IP_RECVIF
, IPPROTO_IP
, mp
);
4477 if (inp
->inp_flags
& INP_RECVTTL
) {
4478 mp
= sbcreatecontrol_mbuf((caddr_t
)&ip
->ip_ttl
,
4479 sizeof(ip
->ip_ttl
), IP_RECVTTL
, IPPROTO_IP
, mp
);
4484 if (inp
->inp_socket
->so_flags
& SOF_RECV_TRAFFIC_CLASS
) {
4485 int tc
= m_get_traffic_class(m
);
4487 mp
= sbcreatecontrol_mbuf((caddr_t
)&tc
, sizeof(tc
),
4488 SO_TRAFFIC_CLASS
, SOL_SOCKET
, mp
);
4493 if (inp
->inp_flags
& INP_PKTINFO
) {
4494 struct in_pktinfo pi
;
4496 bzero(&pi
, sizeof(struct in_pktinfo
));
4497 bcopy(&ip
->ip_dst
, &pi
.ipi_addr
, sizeof(struct in_addr
));
4498 pi
.ipi_ifindex
= (m
!= NULL
&& m
->m_pkthdr
.rcvif
!= NULL
) ?
4499 m
->m_pkthdr
.rcvif
->if_index
: 0;
4501 mp
= sbcreatecontrol_mbuf((caddr_t
)&pi
,
4502 sizeof(struct in_pktinfo
), IP_RECVPKTINFO
, IPPROTO_IP
, mp
);
4507 if (inp
->inp_flags
& INP_RECVTOS
) {
4508 mp
= sbcreatecontrol_mbuf((caddr_t
)&ip
->ip_tos
,
4509 sizeof(u_char
), IP_RECVTOS
, IPPROTO_IP
, mp
);
4517 ipstat
.ips_pktdropcntrl
++;
4521 static inline u_short
4522 ip_cksum(struct mbuf
*m
, int hlen
)
4526 if (m
->m_pkthdr
.csum_flags
& CSUM_IP_CHECKED
) {
4527 sum
= !(m
->m_pkthdr
.csum_flags
& CSUM_IP_VALID
);
4528 } else if (!(m
->m_pkthdr
.rcvif
->if_flags
& IFF_LOOPBACK
) &&
4529 !(m
->m_pkthdr
.pkt_flags
& PKTF_LOOP
)) {
4531 * The packet arrived on an interface which isn't capable
4532 * of performing IP header checksum; compute it now.
4534 sum
= ip_cksum_hdr_in(m
, hlen
);
4537 m
->m_pkthdr
.csum_flags
|= (CSUM_DATA_VALID
| CSUM_PSEUDO_HDR
|
4538 CSUM_IP_CHECKED
| CSUM_IP_VALID
);
4539 m
->m_pkthdr
.csum_data
= 0xffff;
4543 OSAddAtomic(1, &ipstat
.ips_badsum
);
4550 ip_getstat SYSCTL_HANDLER_ARGS
4552 #pragma unused(oidp, arg1, arg2)
4553 if (req
->oldptr
== USER_ADDR_NULL
) {
4554 req
->oldlen
= (size_t)sizeof(struct ipstat
);
4557 return SYSCTL_OUT(req
, &ipstat
, MIN(sizeof(ipstat
), req
->oldlen
));
4561 ip_setsrcifaddr_info(struct mbuf
*m
, uint32_t src_idx
, struct in_ifaddr
*ia
)
4563 VERIFY(m
->m_flags
& M_PKTHDR
);
4566 * If the source ifaddr is specified, pick up the information
4567 * from there; otherwise just grab the passed-in ifindex as the
4568 * caller may not have the ifaddr available.
4571 m
->m_pkthdr
.pkt_flags
|= PKTF_IFAINFO
;
4572 m
->m_pkthdr
.src_ifindex
= ia
->ia_ifp
->if_index
;
4574 m
->m_pkthdr
.src_ifindex
= src_idx
;
4576 m
->m_pkthdr
.pkt_flags
|= PKTF_IFAINFO
;
4582 ip_setdstifaddr_info(struct mbuf
*m
, uint32_t dst_idx
, struct in_ifaddr
*ia
)
4584 VERIFY(m
->m_flags
& M_PKTHDR
);
4587 * If the destination ifaddr is specified, pick up the information
4588 * from there; otherwise just grab the passed-in ifindex as the
4589 * caller may not have the ifaddr available.
4592 m
->m_pkthdr
.pkt_flags
|= PKTF_IFAINFO
;
4593 m
->m_pkthdr
.dst_ifindex
= ia
->ia_ifp
->if_index
;
4595 m
->m_pkthdr
.dst_ifindex
= dst_idx
;
4597 m
->m_pkthdr
.pkt_flags
|= PKTF_IFAINFO
;
4603 ip_getsrcifaddr_info(struct mbuf
*m
, uint32_t *src_idx
, uint32_t *iaf
)
4605 VERIFY(m
->m_flags
& M_PKTHDR
);
4607 if (!(m
->m_pkthdr
.pkt_flags
& PKTF_IFAINFO
)) {
4611 if (src_idx
!= NULL
) {
4612 *src_idx
= m
->m_pkthdr
.src_ifindex
;
4623 ip_getdstifaddr_info(struct mbuf
*m
, uint32_t *dst_idx
, uint32_t *iaf
)
4625 VERIFY(m
->m_flags
& M_PKTHDR
);
4627 if (!(m
->m_pkthdr
.pkt_flags
& PKTF_IFAINFO
)) {
4631 if (dst_idx
!= NULL
) {
4632 *dst_idx
= m
->m_pkthdr
.dst_ifindex
;
4643 * Protocol input handler for IPPROTO_GRE.
4646 gre_input(struct mbuf
*m
, int off
)
4648 gre_input_func_t fn
= gre_input_func
;
4651 * If there is a registered GRE input handler, pass mbuf to it.
4654 lck_mtx_unlock(inet_domain_mutex
);
4655 m
= fn(m
, off
, (mtod(m
, struct ip
*))->ip_p
);
4656 lck_mtx_lock(inet_domain_mutex
);
4660 * If no matching tunnel that is up is found, we inject
4661 * the mbuf to raw ip socket to see if anyone picks it up.
4669 * Private KPI for PPP/PPTP.
4672 ip_gre_register_input(gre_input_func_t fn
)
4674 lck_mtx_lock(inet_domain_mutex
);
4675 gre_input_func
= fn
;
4676 lck_mtx_unlock(inet_domain_mutex
);
4681 #if (DEBUG || DEVELOPMENT)
4683 sysctl_reset_ip_input_stats SYSCTL_HANDLER_ARGS
4685 #pragma unused(arg1, arg2)
4688 i
= ip_input_measure
;
4689 error
= sysctl_handle_int(oidp
, &i
, 0, req
);
4690 if (error
|| req
->newptr
== USER_ADDR_NULL
) {
4694 if (i
< 0 || i
> 1) {
4698 if (ip_input_measure
!= i
&& i
== 1) {
4699 net_perf_initialize(&net_perf
, ip_input_measure_bins
);
4701 ip_input_measure
= i
;
4707 sysctl_ip_input_measure_bins SYSCTL_HANDLER_ARGS
4709 #pragma unused(arg1, arg2)
4713 i
= ip_input_measure_bins
;
4714 error
= sysctl_handle_quad(oidp
, &i
, 0, req
);
4715 if (error
|| req
->newptr
== USER_ADDR_NULL
) {
4719 if (!net_perf_validate_bins(i
)) {
4723 ip_input_measure_bins
= i
;
4729 sysctl_ip_input_getperf SYSCTL_HANDLER_ARGS
4731 #pragma unused(oidp, arg1, arg2)
4732 if (req
->oldptr
== USER_ADDR_NULL
) {
4733 req
->oldlen
= (size_t)sizeof(struct ipstat
);
4736 return SYSCTL_OUT(req
, &net_perf
, MIN(sizeof(net_perf
), req
->oldlen
));
4738 #endif /* (DEBUG || DEVELOPMENT) */
4741 sysctl_ip_checkinterface SYSCTL_HANDLER_ARGS
4743 #pragma unused(arg1, arg2)
4746 i
= ip_checkinterface
;
4747 error
= sysctl_handle_int(oidp
, &i
, 0, req
);
4748 if (error
!= 0 || req
->newptr
== USER_ADDR_NULL
) {
4753 case IP_CHECKINTERFACE_WEAK_ES
:
4754 case IP_CHECKINTERFACE_HYBRID_ES
:
4755 case IP_CHECKINTERFACE_STRONG_ES
:
4756 if (ip_checkinterface
!= i
) {
4757 ip_checkinterface
= i
;
4758 os_log(OS_LOG_DEFAULT
, "%s: ip_checkinterface is now %d\n",
4759 __func__
, ip_checkinterface
);