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