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