]> git.saurik.com Git - apple/xnu.git/blob - bsd/netinet/ip_input.c
1cdd96affd587207d1956599d0508083c17f4271
[apple/xnu.git] / bsd / netinet / ip_input.c
1 /*
2 * Copyright (c) 2000-2019 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 netstat route statistics */
1229 src_ip = ip->ip_src;
1230 len = m->m_pkthdr.len;
1231
1232 #if DUMMYNET
1233 check_with_pf:
1234 #endif
1235 #if PF
1236 /* Invoke inbound packet filter */
1237 if (PF_IS_ENABLED) {
1238 int error;
1239 ip_input_cpout_args(args, &args1, &init);
1240 ip = mtod(m, struct ip *);
1241 src_ip = ip->ip_src;
1242
1243 #if DUMMYNET
1244 error = pf_af_hook(inifp, NULL, &m, AF_INET, TRUE, &args1);
1245 #else
1246 error = pf_af_hook(inifp, NULL, &m, AF_INET, TRUE, NULL);
1247 #endif /* DUMMYNET */
1248 if (error != 0 || m == NULL) {
1249 if (m != NULL) {
1250 panic("%s: unexpected packet %p\n",
1251 __func__, m);
1252 /* NOTREACHED */
1253 }
1254 /* Already freed by callee */
1255 ip_input_update_nstat(inifp, src_ip, 1, len);
1256 KERNEL_DEBUG(DBG_LAYER_END, 0, 0, 0, 0, 0);
1257 OSAddAtomic(1, &ipstat.ips_total);
1258 return IPINPUT_FREED;
1259 }
1260 ip = mtod(m, struct ip *);
1261 hlen = IP_VHL_HL(ip->ip_vhl) << 2;
1262 *modm = m;
1263 ip_input_cpin_args(&args1, args);
1264 }
1265 #endif /* PF */
1266
1267 #if IPSEC
1268 if (ipsec_bypass == 0 && ipsec_gethist(m, NULL)) {
1269 retval = IPINPUT_DONTCHAIN; /* XXX scope for chaining here? */
1270 goto pass;
1271 }
1272 #endif
1273
1274 #if IPFIREWALL
1275 #if DUMMYNET
1276 iphack:
1277 #endif /* DUMMYNET */
1278 /*
1279 * Check if we want to allow this packet to be processed.
1280 * Consider it to be bad if not.
1281 */
1282 if (fw_enable && IPFW_LOADED) {
1283 #if IPFIREWALL_FORWARD
1284 /*
1285 * If we've been forwarded from the output side, then
1286 * skip the firewall a second time
1287 */
1288 if (args->fwai_next_hop) {
1289 *ours = 1;
1290 return IPINPUT_DONTCHAIN;
1291 }
1292 #endif /* IPFIREWALL_FORWARD */
1293 ip_input_cpout_args(args, &args1, &init);
1294 args1.fwa_m = m;
1295
1296 i = ip_fw_chk_ptr(&args1);
1297 m = args1.fwa_m;
1298
1299 if ((i & IP_FW_PORT_DENY_FLAG) || m == NULL) { /* drop */
1300 if (m) {
1301 m_freem(m);
1302 }
1303 ip_input_update_nstat(inifp, src_ip, 1, len);
1304 KERNEL_DEBUG(DBG_LAYER_END, 0, 0, 0, 0, 0);
1305 OSAddAtomic(1, &ipstat.ips_total);
1306 return IPINPUT_FREED;
1307 }
1308 ip = mtod(m, struct ip *); /* just in case m changed */
1309 *modm = m;
1310 ip_input_cpin_args(&args1, args);
1311
1312 if (i == 0 && args->fwai_next_hop == NULL) { /* common case */
1313 goto pass;
1314 }
1315 #if DUMMYNET
1316 if (DUMMYNET_LOADED && (i & IP_FW_PORT_DYNT_FLAG) != 0) {
1317 /* Send packet to the appropriate pipe */
1318 ip_dn_io_ptr(m, i & 0xffff, DN_TO_IP_IN, &args1,
1319 DN_CLIENT_IPFW);
1320 ip_input_update_nstat(inifp, src_ip, 1, len);
1321 KERNEL_DEBUG(DBG_LAYER_END, 0, 0, 0, 0, 0);
1322 OSAddAtomic(1, &ipstat.ips_total);
1323 return IPINPUT_FREED;
1324 }
1325 #endif /* DUMMYNET */
1326 #if IPDIVERT
1327 if (i != 0 && (i & IP_FW_PORT_DYNT_FLAG) == 0) {
1328 /* Divert or tee packet */
1329 *div_info = i;
1330 *ours = 1;
1331 return IPINPUT_DONTCHAIN;
1332 }
1333 #endif
1334 #if IPFIREWALL_FORWARD
1335 if (i == 0 && args->fwai_next_hop != NULL) {
1336 retval = IPINPUT_DONTCHAIN;
1337 goto pass;
1338 }
1339 #endif
1340 /*
1341 * if we get here, the packet must be dropped
1342 */
1343 ip_input_update_nstat(inifp, src_ip, 1, len);
1344 KERNEL_DEBUG(DBG_LAYER_END, 0, 0, 0, 0, 0);
1345 m_freem(m);
1346 OSAddAtomic(1, &ipstat.ips_total);
1347 return IPINPUT_FREED;
1348 }
1349 #endif /* IPFIREWALL */
1350 #if IPSEC | IPFIREWALL
1351 pass:
1352 #endif
1353 /*
1354 * Process options and, if not destined for us,
1355 * ship it on. ip_dooptions returns 1 when an
1356 * error was detected (causing an icmp message
1357 * to be sent and the original packet to be freed).
1358 */
1359 ip_nhops = 0; /* for source routed packets */
1360 #if IPFIREWALL
1361 if (hlen > sizeof(struct ip) &&
1362 ip_dooptions(m, 0, args->fwai_next_hop)) {
1363 #else /* !IPFIREWALL */
1364 if (hlen > sizeof(struct ip) && ip_dooptions(m, 0, NULL)) {
1365 #endif /* !IPFIREWALL */
1366 ip_input_update_nstat(inifp, src_ip, 1, len);
1367 KERNEL_DEBUG(DBG_LAYER_END, 0, 0, 0, 0, 0);
1368 OSAddAtomic(1, &ipstat.ips_total);
1369 return IPINPUT_FREED;
1370 }
1371
1372 /*
1373 * Don't chain fragmented packets as the process of determining
1374 * if it is our fragment or someone else's plus the complexity of
1375 * divert and fw args makes it harder to do chaining.
1376 */
1377 if (ip->ip_off & ~(IP_DF | IP_RF)) {
1378 return IPINPUT_DONTCHAIN;
1379 }
1380
1381 /* Allow DHCP/BootP responses through */
1382 if ((inifp->if_eflags & IFEF_AUTOCONFIGURING) &&
1383 hlen == sizeof(struct ip) && ip->ip_p == IPPROTO_UDP) {
1384 struct udpiphdr *ui;
1385
1386 if (m->m_len < sizeof(struct udpiphdr) &&
1387 (m = m_pullup(m, sizeof(struct udpiphdr))) == NULL) {
1388 OSAddAtomic(1, &udpstat.udps_hdrops);
1389 KERNEL_DEBUG(DBG_LAYER_END, 0, 0, 0, 0, 0);
1390 OSAddAtomic(1, &ipstat.ips_total);
1391 return IPINPUT_FREED;
1392 }
1393 *modm = m;
1394 ui = mtod(m, struct udpiphdr *);
1395 if (ntohs(ui->ui_dport) == IPPORT_BOOTPC) {
1396 ip_setdstifaddr_info(m, inifp->if_index, NULL);
1397 return IPINPUT_DONTCHAIN;
1398 }
1399 }
1400
1401 /* Avoid chaining raw sockets as ipsec checks occur later for them */
1402 if (ip_protox[ip->ip_p]->pr_flags & PR_LASTHDR) {
1403 return IPINPUT_DONTCHAIN;
1404 }
1405
1406 return retval;
1407 #if !defined(__i386__) && !defined(__x86_64__)
1408 bad:
1409 m_freem(m);
1410 return IPINPUT_FREED;
1411 #endif
1412 }
1413
1414 static void
1415 ip_input_second_pass(struct mbuf *m, struct ifnet *inifp, u_int32_t div_info,
1416 int npkts_in_chain, int bytes_in_chain, struct ip_fw_in_args *args, int ours)
1417 {
1418 unsigned int checkif;
1419 struct mbuf *tmp_mbuf = NULL;
1420 struct in_ifaddr *ia = NULL;
1421 struct in_addr pkt_dst;
1422 unsigned int hlen;
1423
1424 #if !IPFIREWALL
1425 #pragma unused (args)
1426 #endif
1427
1428 #if !IPDIVERT
1429 #pragma unused (div_info)
1430 #endif
1431
1432 struct ip *ip = mtod(m, struct ip *);
1433 hlen = IP_VHL_HL(ip->ip_vhl) << 2;
1434
1435 OSAddAtomic(npkts_in_chain, &ipstat.ips_total);
1436
1437 /*
1438 * Naively assume we can attribute inbound data to the route we would
1439 * use to send to this destination. Asymmetric routing breaks this
1440 * assumption, but it still allows us to account for traffic from
1441 * a remote node in the routing table.
1442 * this has a very significant performance impact so we bypass
1443 * if nstat_collect is disabled. We may also bypass if the
1444 * protocol is tcp in the future because tcp will have a route that
1445 * we can use to attribute the data to. That does mean we would not
1446 * account for forwarded tcp traffic.
1447 */
1448 ip_input_update_nstat(inifp, ip->ip_src, npkts_in_chain,
1449 bytes_in_chain);
1450
1451 if (ours) {
1452 goto ours;
1453 }
1454
1455 /*
1456 * Check our list of addresses, to see if the packet is for us.
1457 * If we don't have any addresses, assume any unicast packet
1458 * we receive might be for us (and let the upper layers deal
1459 * with it).
1460 */
1461 tmp_mbuf = m;
1462 if (TAILQ_EMPTY(&in_ifaddrhead)) {
1463 while (tmp_mbuf) {
1464 if (!(tmp_mbuf->m_flags & (M_MCAST | M_BCAST))) {
1465 ip_setdstifaddr_info(tmp_mbuf, inifp->if_index,
1466 NULL);
1467 }
1468 tmp_mbuf = mbuf_nextpkt(tmp_mbuf);
1469 }
1470 goto ours;
1471 }
1472 /*
1473 * Cache the destination address of the packet; this may be
1474 * changed by use of 'ipfw fwd'.
1475 */
1476 #if IPFIREWALL
1477 pkt_dst = args->fwai_next_hop == NULL ?
1478 ip->ip_dst : args->fwai_next_hop->sin_addr;
1479 #else /* !IPFIREWALL */
1480 pkt_dst = ip->ip_dst;
1481 #endif /* !IPFIREWALL */
1482
1483 /*
1484 * Enable a consistency check between the destination address
1485 * and the arrival interface for a unicast packet (the RFC 1122
1486 * strong ES model) if IP forwarding is disabled and the packet
1487 * is not locally generated and the packet is not subject to
1488 * 'ipfw fwd'.
1489 *
1490 * XXX - Checking also should be disabled if the destination
1491 * address is ipnat'ed to a different interface.
1492 *
1493 * XXX - Checking is incompatible with IP aliases added
1494 * to the loopback interface instead of the interface where
1495 * the packets are received.
1496 */
1497 checkif = ip_checkinterface && (ipforwarding == 0) &&
1498 !(inifp->if_flags & IFF_LOOPBACK) &&
1499 !(m->m_pkthdr.pkt_flags & PKTF_LOOP)
1500 #if IPFIREWALL
1501 && (args->fwai_next_hop == NULL);
1502 #else /* !IPFIREWALL */
1503 ;
1504 #endif /* !IPFIREWALL */
1505
1506 /*
1507 * Check for exact addresses in the hash bucket.
1508 */
1509 lck_rw_lock_shared(in_ifaddr_rwlock);
1510 TAILQ_FOREACH(ia, INADDR_HASH(pkt_dst.s_addr), ia_hash) {
1511 /*
1512 * If the address matches, verify that the packet
1513 * arrived via the correct interface if checking is
1514 * enabled.
1515 */
1516 if (IA_SIN(ia)->sin_addr.s_addr == pkt_dst.s_addr &&
1517 (!checkif || ia->ia_ifp == inifp)) {
1518 ip_input_setdst_chain(m, 0, ia);
1519 lck_rw_done(in_ifaddr_rwlock);
1520 goto ours;
1521 }
1522 }
1523 lck_rw_done(in_ifaddr_rwlock);
1524
1525 /*
1526 * Check for broadcast addresses.
1527 *
1528 * Only accept broadcast packets that arrive via the matching
1529 * interface. Reception of forwarded directed broadcasts would be
1530 * handled via ip_forward() and ether_frameout() with the loopback
1531 * into the stack for SIMPLEX interfaces handled by ether_frameout().
1532 */
1533 if (inifp->if_flags & IFF_BROADCAST) {
1534 struct ifaddr *ifa;
1535
1536 ifnet_lock_shared(inifp);
1537 TAILQ_FOREACH(ifa, &inifp->if_addrhead, ifa_link) {
1538 if (ifa->ifa_addr->sa_family != AF_INET) {
1539 continue;
1540 }
1541 ia = ifatoia(ifa);
1542 if (satosin(&ia->ia_broadaddr)->sin_addr.s_addr ==
1543 pkt_dst.s_addr || ia->ia_netbroadcast.s_addr ==
1544 pkt_dst.s_addr) {
1545 ip_input_setdst_chain(m, 0, ia);
1546 ifnet_lock_done(inifp);
1547 goto ours;
1548 }
1549 }
1550 ifnet_lock_done(inifp);
1551 }
1552
1553 if (IN_MULTICAST(ntohl(ip->ip_dst.s_addr))) {
1554 struct in_multi *inm;
1555 /*
1556 * See if we belong to the destination multicast group on the
1557 * arrival interface.
1558 */
1559 in_multihead_lock_shared();
1560 IN_LOOKUP_MULTI(&ip->ip_dst, inifp, inm);
1561 in_multihead_lock_done();
1562 if (inm == NULL) {
1563 OSAddAtomic(npkts_in_chain, &ipstat.ips_notmember);
1564 m_freem_list(m);
1565 KERNEL_DEBUG(DBG_LAYER_END, 0, 0, 0, 0, 0);
1566 return;
1567 }
1568 ip_input_setdst_chain(m, inifp->if_index, NULL);
1569 INM_REMREF(inm);
1570 goto ours;
1571 }
1572
1573 if (ip->ip_dst.s_addr == (u_int32_t)INADDR_BROADCAST ||
1574 ip->ip_dst.s_addr == INADDR_ANY) {
1575 ip_input_setdst_chain(m, inifp->if_index, NULL);
1576 goto ours;
1577 }
1578
1579 if (ip->ip_p == IPPROTO_UDP) {
1580 struct udpiphdr *ui;
1581 ui = mtod(m, struct udpiphdr *);
1582 if (ntohs(ui->ui_dport) == IPPORT_BOOTPC) {
1583 goto ours;
1584 }
1585 }
1586
1587 tmp_mbuf = m;
1588 struct mbuf *nxt_mbuf = NULL;
1589 while (tmp_mbuf) {
1590 nxt_mbuf = mbuf_nextpkt(tmp_mbuf);
1591 /*
1592 * Not for us; forward if possible and desirable.
1593 */
1594 mbuf_setnextpkt(tmp_mbuf, NULL);
1595 if (ipforwarding == 0) {
1596 OSAddAtomic(1, &ipstat.ips_cantforward);
1597 m_freem(tmp_mbuf);
1598 } else {
1599 #if IPFIREWALL
1600 ip_forward(tmp_mbuf, 0, args->fwai_next_hop);
1601 #else
1602 ip_forward(tmp_mbuf, 0, NULL);
1603 #endif
1604 }
1605 tmp_mbuf = nxt_mbuf;
1606 }
1607 KERNEL_DEBUG(DBG_LAYER_END, 0, 0, 0, 0, 0);
1608 return;
1609 ours:
1610 /*
1611 * If offset or IP_MF are set, must reassemble.
1612 */
1613 if (ip->ip_off & ~(IP_DF | IP_RF)) {
1614 VERIFY(npkts_in_chain == 1);
1615 /*
1616 * ip_reass() will return a different mbuf, and update
1617 * the divert info in div_info and args->fwai_divert_rule.
1618 */
1619 #if IPDIVERT
1620 m = ip_reass(m, (u_int16_t *)&div_info, &args->fwai_divert_rule);
1621 #else
1622 m = ip_reass(m);
1623 #endif
1624 if (m == NULL) {
1625 return;
1626 }
1627 ip = mtod(m, struct ip *);
1628 /* Get the header length of the reassembled packet */
1629 hlen = IP_VHL_HL(ip->ip_vhl) << 2;
1630 #if IPDIVERT
1631 /* Restore original checksum before diverting packet */
1632 if (div_info != 0) {
1633 VERIFY(npkts_in_chain == 1);
1634 #if BYTE_ORDER != BIG_ENDIAN
1635 HTONS(ip->ip_len);
1636 HTONS(ip->ip_off);
1637 #endif
1638 ip->ip_sum = 0;
1639 ip->ip_sum = ip_cksum_hdr_in(m, hlen);
1640 #if BYTE_ORDER != BIG_ENDIAN
1641 NTOHS(ip->ip_off);
1642 NTOHS(ip->ip_len);
1643 #endif
1644 }
1645 #endif
1646 }
1647
1648 /*
1649 * Further protocols expect the packet length to be w/o the
1650 * IP header.
1651 */
1652 ip->ip_len -= hlen;
1653
1654 #if IPDIVERT
1655 /*
1656 * Divert or tee packet to the divert protocol if required.
1657 *
1658 * If div_info is zero then cookie should be too, so we shouldn't
1659 * need to clear them here. Assume divert_packet() does so also.
1660 */
1661 if (div_info != 0) {
1662 struct mbuf *clone = NULL;
1663 VERIFY(npkts_in_chain == 1);
1664
1665 /* Clone packet if we're doing a 'tee' */
1666 if (div_info & IP_FW_PORT_TEE_FLAG) {
1667 clone = m_dup(m, M_DONTWAIT);
1668 }
1669
1670 /* Restore packet header fields to original values */
1671 ip->ip_len += hlen;
1672
1673 #if BYTE_ORDER != BIG_ENDIAN
1674 HTONS(ip->ip_len);
1675 HTONS(ip->ip_off);
1676 #endif
1677 /* Deliver packet to divert input routine */
1678 OSAddAtomic(1, &ipstat.ips_delivered);
1679 divert_packet(m, 1, div_info & 0xffff, args->fwai_divert_rule);
1680
1681 /* If 'tee', continue with original packet */
1682 if (clone == NULL) {
1683 return;
1684 }
1685 m = clone;
1686 ip = mtod(m, struct ip *);
1687 }
1688 #endif
1689
1690 #if IPSEC
1691 /*
1692 * enforce IPsec policy checking if we are seeing last header.
1693 * note that we do not visit this with protocols with pcb layer
1694 * code - like udp/tcp/raw ip.
1695 */
1696 if (ipsec_bypass == 0 && (ip_protox[ip->ip_p]->pr_flags & PR_LASTHDR)) {
1697 VERIFY(npkts_in_chain == 1);
1698 if (ipsec4_in_reject(m, NULL)) {
1699 IPSEC_STAT_INCREMENT(ipsecstat.in_polvio);
1700 goto bad;
1701 }
1702 }
1703 #endif /* IPSEC */
1704
1705 /*
1706 * Switch out to protocol's input routine.
1707 */
1708 OSAddAtomic(npkts_in_chain, &ipstat.ips_delivered);
1709
1710 #if IPFIREWALL
1711 if (args->fwai_next_hop && ip->ip_p == IPPROTO_TCP) {
1712 /* TCP needs IPFORWARD info if available */
1713 struct m_tag *fwd_tag;
1714 struct ip_fwd_tag *ipfwd_tag;
1715
1716 VERIFY(npkts_in_chain == 1);
1717 fwd_tag = m_tag_create(KERNEL_MODULE_TAG_ID,
1718 KERNEL_TAG_TYPE_IPFORWARD, sizeof(*ipfwd_tag),
1719 M_NOWAIT, m);
1720 if (fwd_tag == NULL) {
1721 goto bad;
1722 }
1723
1724 ipfwd_tag = (struct ip_fwd_tag *)(fwd_tag + 1);
1725 ipfwd_tag->next_hop = args->fwai_next_hop;
1726
1727 m_tag_prepend(m, fwd_tag);
1728
1729 KERNEL_DEBUG(DBG_LAYER_END, ip->ip_dst.s_addr,
1730 ip->ip_src.s_addr, ip->ip_p, ip->ip_off, ip->ip_len);
1731
1732 /* TCP deals with its own locking */
1733 ip_proto_dispatch_in(m, hlen, ip->ip_p, 0);
1734 } else {
1735 KERNEL_DEBUG(DBG_LAYER_END, ip->ip_dst.s_addr,
1736 ip->ip_src.s_addr, ip->ip_p, ip->ip_off, ip->ip_len);
1737
1738 ip_input_dispatch_chain(m);
1739 }
1740 #else /* !IPFIREWALL */
1741 ip_input_dispatch_chain(m);
1742
1743 #endif /* !IPFIREWALL */
1744 KERNEL_DEBUG(DBG_LAYER_END, 0, 0, 0, 0, 0);
1745 return;
1746 bad:
1747 KERNEL_DEBUG(DBG_LAYER_END, 0, 0, 0, 0, 0);
1748 m_freem(m);
1749 }
1750
1751 void
1752 ip_input_process_list(struct mbuf *packet_list)
1753 {
1754 pktchain_elm_t pktchain_tbl[PKTTBL_SZ];
1755
1756 struct mbuf *packet = NULL;
1757 struct mbuf *modm = NULL; /* modified mbuf */
1758 int retval = 0;
1759 u_int32_t div_info = 0;
1760 int ours = 0;
1761 #if (DEBUG || DEVELOPMENT)
1762 struct timeval start_tv;
1763 #endif /* (DEBUG || DEVELOPMENT) */
1764 int num_pkts = 0;
1765 int chain = 0;
1766 struct ip_fw_in_args args;
1767
1768 if (ip_chaining == 0) {
1769 struct mbuf *m = packet_list;
1770 #if (DEBUG || DEVELOPMENT)
1771 if (ip_input_measure) {
1772 net_perf_start_time(&net_perf, &start_tv);
1773 }
1774 #endif /* (DEBUG || DEVELOPMENT) */
1775
1776 while (m) {
1777 packet_list = mbuf_nextpkt(m);
1778 mbuf_setnextpkt(m, NULL);
1779 ip_input(m);
1780 m = packet_list;
1781 num_pkts++;
1782 }
1783 #if (DEBUG || DEVELOPMENT)
1784 if (ip_input_measure) {
1785 net_perf_measure_time(&net_perf, &start_tv, num_pkts);
1786 }
1787 #endif /* (DEBUG || DEVELOPMENT) */
1788 return;
1789 }
1790 #if (DEBUG || DEVELOPMENT)
1791 if (ip_input_measure) {
1792 net_perf_start_time(&net_perf, &start_tv);
1793 }
1794 #endif /* (DEBUG || DEVELOPMENT) */
1795
1796 bzero(&pktchain_tbl, sizeof(pktchain_tbl));
1797 restart_list_process:
1798 chain = 0;
1799 for (packet = packet_list; packet; packet = packet_list) {
1800 packet_list = mbuf_nextpkt(packet);
1801 mbuf_setnextpkt(packet, NULL);
1802
1803 num_pkts++;
1804 modm = NULL;
1805 div_info = 0;
1806 bzero(&args, sizeof(args));
1807
1808 retval = ip_input_first_pass(packet, &div_info, &args,
1809 &ours, &modm);
1810
1811 if (retval == IPINPUT_DOCHAIN) {
1812 if (modm) {
1813 packet = modm;
1814 }
1815 packet = ip_chain_insert(packet, &pktchain_tbl[0]);
1816 if (packet == NULL) {
1817 ipstat.ips_rxc_chained++;
1818 chain++;
1819 if (chain > ip_chainsz) {
1820 break;
1821 }
1822 } else {
1823 ipstat.ips_rxc_collisions++;
1824 break;
1825 }
1826 } else if (retval == IPINPUT_DONTCHAIN) {
1827 /* in order to preserve order, exit from chaining */
1828 if (modm) {
1829 packet = modm;
1830 }
1831 ipstat.ips_rxc_notchain++;
1832 break;
1833 } else {
1834 /* packet was freed or delivered, do nothing. */
1835 }
1836 }
1837
1838 /* do second pass here for pktchain_tbl */
1839 if (chain) {
1840 ip_input_second_pass_loop_tbl(&pktchain_tbl[0], &args);
1841 }
1842
1843 if (packet) {
1844 /*
1845 * equivalent update in chaining case if performed in
1846 * ip_input_second_pass_loop_tbl().
1847 */
1848 #if (DEBUG || DEVELOPMENT)
1849 if (ip_input_measure) {
1850 net_perf_histogram(&net_perf, 1);
1851 }
1852 #endif /* (DEBUG || DEVELOPMENT) */
1853 ip_input_second_pass(packet, packet->m_pkthdr.rcvif, div_info,
1854 1, packet->m_pkthdr.len, &args, ours);
1855 }
1856
1857 if (packet_list) {
1858 goto restart_list_process;
1859 }
1860
1861 #if (DEBUG || DEVELOPMENT)
1862 if (ip_input_measure) {
1863 net_perf_measure_time(&net_perf, &start_tv, num_pkts);
1864 }
1865 #endif /* (DEBUG || DEVELOPMENT) */
1866 }
1867 /*
1868 * Ip input routine. Checksum and byte swap header. If fragmented
1869 * try to reassemble. Process options. Pass to next level.
1870 */
1871 void
1872 ip_input(struct mbuf *m)
1873 {
1874 struct ip *ip;
1875 struct in_ifaddr *ia = NULL;
1876 unsigned int hlen, checkif;
1877 u_short sum = 0;
1878 struct in_addr pkt_dst;
1879 #if IPFIREWALL
1880 int i;
1881 u_int32_t div_info = 0; /* packet divert/tee info */
1882 #endif
1883 #if IPFIREWALL || DUMMYNET
1884 struct ip_fw_args args;
1885 struct m_tag *tag;
1886 #endif
1887 ipfilter_t inject_filter_ref = NULL;
1888 struct ifnet *inifp;
1889
1890 /* Check if the mbuf is still valid after interface filter processing */
1891 MBUF_INPUT_CHECK(m, m->m_pkthdr.rcvif);
1892 inifp = m->m_pkthdr.rcvif;
1893 VERIFY(inifp != NULL);
1894
1895 ipstat.ips_rxc_notlist++;
1896
1897 /* Perform IP header alignment fixup, if needed */
1898 IP_HDR_ALIGNMENT_FIXUP(m, inifp, goto bad);
1899
1900 m->m_pkthdr.pkt_flags &= ~PKTF_FORWARDED;
1901
1902 #if IPFIREWALL || DUMMYNET
1903 bzero(&args, sizeof(struct ip_fw_args));
1904
1905 /*
1906 * Don't bother searching for tag(s) if there's none.
1907 */
1908 if (SLIST_EMPTY(&m->m_pkthdr.tags)) {
1909 goto ipfw_tags_done;
1910 }
1911
1912 /* Grab info from mtags prepended to the chain */
1913 #if DUMMYNET
1914 if ((tag = m_tag_locate(m, KERNEL_MODULE_TAG_ID,
1915 KERNEL_TAG_TYPE_DUMMYNET, NULL)) != NULL) {
1916 struct dn_pkt_tag *dn_tag;
1917
1918 dn_tag = (struct dn_pkt_tag *)(tag + 1);
1919 args.fwa_ipfw_rule = dn_tag->dn_ipfw_rule;
1920 args.fwa_pf_rule = dn_tag->dn_pf_rule;
1921
1922 m_tag_delete(m, tag);
1923 }
1924 #endif /* DUMMYNET */
1925
1926 #if IPDIVERT
1927 if ((tag = m_tag_locate(m, KERNEL_MODULE_TAG_ID,
1928 KERNEL_TAG_TYPE_DIVERT, NULL)) != NULL) {
1929 struct divert_tag *div_tag;
1930
1931 div_tag = (struct divert_tag *)(tag + 1);
1932 args.fwa_divert_rule = div_tag->cookie;
1933
1934 m_tag_delete(m, tag);
1935 }
1936 #endif
1937
1938 if ((tag = m_tag_locate(m, KERNEL_MODULE_TAG_ID,
1939 KERNEL_TAG_TYPE_IPFORWARD, NULL)) != NULL) {
1940 struct ip_fwd_tag *ipfwd_tag;
1941
1942 ipfwd_tag = (struct ip_fwd_tag *)(tag + 1);
1943 args.fwa_next_hop = ipfwd_tag->next_hop;
1944
1945 m_tag_delete(m, tag);
1946 }
1947
1948 #if DIAGNOSTIC
1949 if (m == NULL || !(m->m_flags & M_PKTHDR)) {
1950 panic("ip_input no HDR");
1951 }
1952 #endif
1953
1954 #if DUMMYNET
1955 if (args.fwa_ipfw_rule || args.fwa_pf_rule) {
1956 /* dummynet already filtered us */
1957 ip = mtod(m, struct ip *);
1958 hlen = IP_VHL_HL(ip->ip_vhl) << 2;
1959 inject_filter_ref = ipf_get_inject_filter(m);
1960 #if IPFIREWALL
1961 if (args.fwa_ipfw_rule) {
1962 goto iphack;
1963 }
1964 #endif /* IPFIREWALL */
1965 if (args.fwa_pf_rule) {
1966 goto check_with_pf;
1967 }
1968 }
1969 #endif /* DUMMYNET */
1970 ipfw_tags_done:
1971 #endif /* IPFIREWALL || DUMMYNET */
1972
1973 /*
1974 * No need to process packet twice if we've already seen it.
1975 */
1976 if (!SLIST_EMPTY(&m->m_pkthdr.tags)) {
1977 inject_filter_ref = ipf_get_inject_filter(m);
1978 }
1979 if (inject_filter_ref != NULL) {
1980 ip = mtod(m, struct ip *);
1981 hlen = IP_VHL_HL(ip->ip_vhl) << 2;
1982
1983 DTRACE_IP6(receive, struct mbuf *, m, struct inpcb *, NULL,
1984 struct ip *, ip, struct ifnet *, inifp,
1985 struct ip *, ip, struct ip6_hdr *, NULL);
1986
1987 ip->ip_len = ntohs(ip->ip_len) - hlen;
1988 ip->ip_off = ntohs(ip->ip_off);
1989 ip_proto_dispatch_in(m, hlen, ip->ip_p, inject_filter_ref);
1990 return;
1991 }
1992
1993 OSAddAtomic(1, &ipstat.ips_total);
1994 if (m->m_pkthdr.len < sizeof(struct ip)) {
1995 goto tooshort;
1996 }
1997
1998 if (m->m_len < sizeof(struct ip) &&
1999 (m = m_pullup(m, sizeof(struct ip))) == NULL) {
2000 OSAddAtomic(1, &ipstat.ips_toosmall);
2001 return;
2002 }
2003 ip = mtod(m, struct ip *);
2004
2005 KERNEL_DEBUG(DBG_LAYER_BEG, ip->ip_dst.s_addr, ip->ip_src.s_addr,
2006 ip->ip_p, ip->ip_off, ip->ip_len);
2007
2008 if (IP_VHL_V(ip->ip_vhl) != IPVERSION) {
2009 OSAddAtomic(1, &ipstat.ips_badvers);
2010 goto bad;
2011 }
2012
2013 hlen = IP_VHL_HL(ip->ip_vhl) << 2;
2014 if (hlen < sizeof(struct ip)) { /* minimum header length */
2015 OSAddAtomic(1, &ipstat.ips_badhlen);
2016 goto bad;
2017 }
2018 if (hlen > m->m_len) {
2019 if ((m = m_pullup(m, hlen)) == NULL) {
2020 OSAddAtomic(1, &ipstat.ips_badhlen);
2021 return;
2022 }
2023 ip = mtod(m, struct ip *);
2024 }
2025
2026 /* 127/8 must not appear on wire - RFC1122 */
2027 if ((ntohl(ip->ip_dst.s_addr) >> IN_CLASSA_NSHIFT) == IN_LOOPBACKNET ||
2028 (ntohl(ip->ip_src.s_addr) >> IN_CLASSA_NSHIFT) == IN_LOOPBACKNET) {
2029 /*
2030 * Allow for the following exceptions:
2031 *
2032 * 1. If the packet was sent to loopback (i.e. rcvif
2033 * would have been set earlier at output time.)
2034 *
2035 * 2. If the packet was sent out on loopback from a local
2036 * source address which belongs to a non-loopback
2037 * interface (i.e. rcvif may not necessarily be a
2038 * loopback interface, hence the test for PKTF_LOOP.)
2039 * Unlike IPv6, there is no interface scope ID, and
2040 * therefore we don't care so much about PKTF_IFINFO.
2041 */
2042 if (!(inifp->if_flags & IFF_LOOPBACK) &&
2043 !(m->m_pkthdr.pkt_flags & PKTF_LOOP)) {
2044 OSAddAtomic(1, &ipstat.ips_badaddr);
2045 goto bad;
2046 }
2047 }
2048
2049 /* IPv4 Link-Local Addresses as defined in RFC3927 */
2050 if ((IN_LINKLOCAL(ntohl(ip->ip_dst.s_addr)) ||
2051 IN_LINKLOCAL(ntohl(ip->ip_src.s_addr)))) {
2052 ip_linklocal_stat.iplls_in_total++;
2053 if (ip->ip_ttl != MAXTTL) {
2054 OSAddAtomic(1, &ip_linklocal_stat.iplls_in_badttl);
2055 /* Silently drop link local traffic with bad TTL */
2056 if (!ip_linklocal_in_allowbadttl) {
2057 goto bad;
2058 }
2059 }
2060 }
2061
2062 sum = ip_cksum(m, hlen);
2063 if (sum) {
2064 goto bad;
2065 }
2066
2067 DTRACE_IP6(receive, struct mbuf *, m, struct inpcb *, NULL,
2068 struct ip *, ip, struct ifnet *, inifp,
2069 struct ip *, ip, struct ip6_hdr *, NULL);
2070
2071 /*
2072 * Naively assume we can attribute inbound data to the route we would
2073 * use to send to this destination. Asymmetric routing breaks this
2074 * assumption, but it still allows us to account for traffic from
2075 * a remote node in the routing table.
2076 * this has a very significant performance impact so we bypass
2077 * if nstat_collect is disabled. We may also bypass if the
2078 * protocol is tcp in the future because tcp will have a route that
2079 * we can use to attribute the data to. That does mean we would not
2080 * account for forwarded tcp traffic.
2081 */
2082 if (nstat_collect) {
2083 struct rtentry *rt =
2084 ifnet_cached_rtlookup_inet(inifp, ip->ip_src);
2085 if (rt != NULL) {
2086 nstat_route_rx(rt, 1, m->m_pkthdr.len, 0);
2087 rtfree(rt);
2088 }
2089 }
2090
2091 /*
2092 * Convert fields to host representation.
2093 */
2094 #if BYTE_ORDER != BIG_ENDIAN
2095 NTOHS(ip->ip_len);
2096 #endif
2097
2098 if (ip->ip_len < hlen) {
2099 OSAddAtomic(1, &ipstat.ips_badlen);
2100 goto bad;
2101 }
2102
2103 #if BYTE_ORDER != BIG_ENDIAN
2104 NTOHS(ip->ip_off);
2105 #endif
2106 /*
2107 * Check that the amount of data in the buffers
2108 * is as at least much as the IP header would have us expect.
2109 * Trim mbufs if longer than we expect.
2110 * Drop packet if shorter than we expect.
2111 */
2112 if (m->m_pkthdr.len < ip->ip_len) {
2113 tooshort:
2114 OSAddAtomic(1, &ipstat.ips_tooshort);
2115 goto bad;
2116 }
2117 if (m->m_pkthdr.len > ip->ip_len) {
2118 ip_input_adjust(m, ip, inifp);
2119 }
2120
2121 #if DUMMYNET
2122 check_with_pf:
2123 #endif
2124 #if PF
2125 /* Invoke inbound packet filter */
2126 if (PF_IS_ENABLED) {
2127 int error;
2128 #if DUMMYNET
2129 error = pf_af_hook(inifp, NULL, &m, AF_INET, TRUE, &args);
2130 #else
2131 error = pf_af_hook(inifp, NULL, &m, AF_INET, TRUE, NULL);
2132 #endif /* DUMMYNET */
2133 if (error != 0 || m == NULL) {
2134 if (m != NULL) {
2135 panic("%s: unexpected packet %p\n",
2136 __func__, m);
2137 /* NOTREACHED */
2138 }
2139 /* Already freed by callee */
2140 return;
2141 }
2142 ip = mtod(m, struct ip *);
2143 hlen = IP_VHL_HL(ip->ip_vhl) << 2;
2144 }
2145 #endif /* PF */
2146
2147 #if IPSEC
2148 if (ipsec_bypass == 0 && ipsec_gethist(m, NULL)) {
2149 goto pass;
2150 }
2151 #endif
2152
2153 #if IPFIREWALL
2154 #if DUMMYNET
2155 iphack:
2156 #endif /* DUMMYNET */
2157 /*
2158 * Check if we want to allow this packet to be processed.
2159 * Consider it to be bad if not.
2160 */
2161 if (fw_enable && IPFW_LOADED) {
2162 #if IPFIREWALL_FORWARD
2163 /*
2164 * If we've been forwarded from the output side, then
2165 * skip the firewall a second time
2166 */
2167 if (args.fwa_next_hop) {
2168 goto ours;
2169 }
2170 #endif /* IPFIREWALL_FORWARD */
2171
2172 args.fwa_m = m;
2173
2174 i = ip_fw_chk_ptr(&args);
2175 m = args.fwa_m;
2176
2177 if ((i & IP_FW_PORT_DENY_FLAG) || m == NULL) { /* drop */
2178 if (m) {
2179 m_freem(m);
2180 }
2181 return;
2182 }
2183 ip = mtod(m, struct ip *); /* just in case m changed */
2184
2185 if (i == 0 && args.fwa_next_hop == NULL) { /* common case */
2186 goto pass;
2187 }
2188 #if DUMMYNET
2189 if (DUMMYNET_LOADED && (i & IP_FW_PORT_DYNT_FLAG) != 0) {
2190 /* Send packet to the appropriate pipe */
2191 ip_dn_io_ptr(m, i & 0xffff, DN_TO_IP_IN, &args,
2192 DN_CLIENT_IPFW);
2193 return;
2194 }
2195 #endif /* DUMMYNET */
2196 #if IPDIVERT
2197 if (i != 0 && (i & IP_FW_PORT_DYNT_FLAG) == 0) {
2198 /* Divert or tee packet */
2199 div_info = i;
2200 goto ours;
2201 }
2202 #endif
2203 #if IPFIREWALL_FORWARD
2204 if (i == 0 && args.fwa_next_hop != NULL) {
2205 goto pass;
2206 }
2207 #endif
2208 /*
2209 * if we get here, the packet must be dropped
2210 */
2211 m_freem(m);
2212 return;
2213 }
2214 #endif /* IPFIREWALL */
2215 #if IPSEC | IPFIREWALL
2216 pass:
2217 #endif
2218 /*
2219 * Process options and, if not destined for us,
2220 * ship it on. ip_dooptions returns 1 when an
2221 * error was detected (causing an icmp message
2222 * to be sent and the original packet to be freed).
2223 */
2224 ip_nhops = 0; /* for source routed packets */
2225 #if IPFIREWALL
2226 if (hlen > sizeof(struct ip) &&
2227 ip_dooptions(m, 0, args.fwa_next_hop)) {
2228 #else /* !IPFIREWALL */
2229 if (hlen > sizeof(struct ip) && ip_dooptions(m, 0, NULL)) {
2230 #endif /* !IPFIREWALL */
2231 return;
2232 }
2233
2234 /*
2235 * Check our list of addresses, to see if the packet is for us.
2236 * If we don't have any addresses, assume any unicast packet
2237 * we receive might be for us (and let the upper layers deal
2238 * with it).
2239 */
2240 if (TAILQ_EMPTY(&in_ifaddrhead) && !(m->m_flags & (M_MCAST | M_BCAST))) {
2241 ip_setdstifaddr_info(m, inifp->if_index, NULL);
2242 goto ours;
2243 }
2244
2245 /*
2246 * Cache the destination address of the packet; this may be
2247 * changed by use of 'ipfw fwd'.
2248 */
2249 #if IPFIREWALL
2250 pkt_dst = args.fwa_next_hop == NULL ?
2251 ip->ip_dst : args.fwa_next_hop->sin_addr;
2252 #else /* !IPFIREWALL */
2253 pkt_dst = ip->ip_dst;
2254 #endif /* !IPFIREWALL */
2255
2256 /*
2257 * Enable a consistency check between the destination address
2258 * and the arrival interface for a unicast packet (the RFC 1122
2259 * strong ES model) if IP forwarding is disabled and the packet
2260 * is not locally generated and the packet is not subject to
2261 * 'ipfw fwd'.
2262 *
2263 * XXX - Checking also should be disabled if the destination
2264 * address is ipnat'ed to a different interface.
2265 *
2266 * XXX - Checking is incompatible with IP aliases added
2267 * to the loopback interface instead of the interface where
2268 * the packets are received.
2269 */
2270 checkif = ip_checkinterface && (ipforwarding == 0) &&
2271 !(inifp->if_flags & IFF_LOOPBACK) &&
2272 !(m->m_pkthdr.pkt_flags & PKTF_LOOP)
2273 #if IPFIREWALL
2274 && (args.fwa_next_hop == NULL);
2275 #else /* !IPFIREWALL */
2276 ;
2277 #endif /* !IPFIREWALL */
2278
2279 /*
2280 * Check for exact addresses in the hash bucket.
2281 */
2282 lck_rw_lock_shared(in_ifaddr_rwlock);
2283 TAILQ_FOREACH(ia, INADDR_HASH(pkt_dst.s_addr), ia_hash) {
2284 /*
2285 * If the address matches, verify that the packet
2286 * arrived via the correct interface if checking is
2287 * enabled.
2288 */
2289 if (IA_SIN(ia)->sin_addr.s_addr == pkt_dst.s_addr &&
2290 (!checkif || ia->ia_ifp == inifp)) {
2291 ip_setdstifaddr_info(m, 0, ia);
2292 lck_rw_done(in_ifaddr_rwlock);
2293 goto ours;
2294 }
2295 }
2296 lck_rw_done(in_ifaddr_rwlock);
2297
2298 /*
2299 * Check for broadcast addresses.
2300 *
2301 * Only accept broadcast packets that arrive via the matching
2302 * interface. Reception of forwarded directed broadcasts would be
2303 * handled via ip_forward() and ether_frameout() with the loopback
2304 * into the stack for SIMPLEX interfaces handled by ether_frameout().
2305 */
2306 if (inifp->if_flags & IFF_BROADCAST) {
2307 struct ifaddr *ifa;
2308
2309 ifnet_lock_shared(inifp);
2310 TAILQ_FOREACH(ifa, &inifp->if_addrhead, ifa_link) {
2311 if (ifa->ifa_addr->sa_family != AF_INET) {
2312 continue;
2313 }
2314 ia = ifatoia(ifa);
2315 if (satosin(&ia->ia_broadaddr)->sin_addr.s_addr ==
2316 pkt_dst.s_addr || ia->ia_netbroadcast.s_addr ==
2317 pkt_dst.s_addr) {
2318 ip_setdstifaddr_info(m, 0, ia);
2319 ifnet_lock_done(inifp);
2320 goto ours;
2321 }
2322 }
2323 ifnet_lock_done(inifp);
2324 }
2325
2326 if (IN_MULTICAST(ntohl(ip->ip_dst.s_addr))) {
2327 struct in_multi *inm;
2328 /*
2329 * See if we belong to the destination multicast group on the
2330 * arrival interface.
2331 */
2332 in_multihead_lock_shared();
2333 IN_LOOKUP_MULTI(&ip->ip_dst, inifp, inm);
2334 in_multihead_lock_done();
2335 if (inm == NULL) {
2336 OSAddAtomic(1, &ipstat.ips_notmember);
2337 m_freem(m);
2338 return;
2339 }
2340 ip_setdstifaddr_info(m, inifp->if_index, NULL);
2341 INM_REMREF(inm);
2342 goto ours;
2343 }
2344 if (ip->ip_dst.s_addr == (u_int32_t)INADDR_BROADCAST ||
2345 ip->ip_dst.s_addr == INADDR_ANY) {
2346 ip_setdstifaddr_info(m, inifp->if_index, NULL);
2347 goto ours;
2348 }
2349
2350 /* Allow DHCP/BootP responses through */
2351 if ((inifp->if_eflags & IFEF_AUTOCONFIGURING) &&
2352 hlen == sizeof(struct ip) && ip->ip_p == IPPROTO_UDP) {
2353 struct udpiphdr *ui;
2354
2355 if (m->m_len < sizeof(struct udpiphdr) &&
2356 (m = m_pullup(m, sizeof(struct udpiphdr))) == NULL) {
2357 OSAddAtomic(1, &udpstat.udps_hdrops);
2358 return;
2359 }
2360 ui = mtod(m, struct udpiphdr *);
2361 if (ntohs(ui->ui_dport) == IPPORT_BOOTPC) {
2362 ip_setdstifaddr_info(m, inifp->if_index, NULL);
2363 goto ours;
2364 }
2365 ip = mtod(m, struct ip *); /* in case it changed */
2366 }
2367
2368 /*
2369 * Not for us; forward if possible and desirable.
2370 */
2371 if (ipforwarding == 0) {
2372 OSAddAtomic(1, &ipstat.ips_cantforward);
2373 m_freem(m);
2374 } else {
2375 #if IPFIREWALL
2376 ip_forward(m, 0, args.fwa_next_hop);
2377 #else
2378 ip_forward(m, 0, NULL);
2379 #endif
2380 }
2381 return;
2382
2383 ours:
2384 /*
2385 * If offset or IP_MF are set, must reassemble.
2386 */
2387 if (ip->ip_off & ~(IP_DF | IP_RF)) {
2388 /*
2389 * ip_reass() will return a different mbuf, and update
2390 * the divert info in div_info and args.fwa_divert_rule.
2391 */
2392 #if IPDIVERT
2393 m = ip_reass(m, (u_int16_t *)&div_info, &args.fwa_divert_rule);
2394 #else
2395 m = ip_reass(m);
2396 #endif
2397 if (m == NULL) {
2398 return;
2399 }
2400 ip = mtod(m, struct ip *);
2401 /* Get the header length of the reassembled packet */
2402 hlen = IP_VHL_HL(ip->ip_vhl) << 2;
2403 #if IPDIVERT
2404 /* Restore original checksum before diverting packet */
2405 if (div_info != 0) {
2406 #if BYTE_ORDER != BIG_ENDIAN
2407 HTONS(ip->ip_len);
2408 HTONS(ip->ip_off);
2409 #endif
2410 ip->ip_sum = 0;
2411 ip->ip_sum = ip_cksum_hdr_in(m, hlen);
2412 #if BYTE_ORDER != BIG_ENDIAN
2413 NTOHS(ip->ip_off);
2414 NTOHS(ip->ip_len);
2415 #endif
2416 }
2417 #endif
2418 }
2419
2420 /*
2421 * Further protocols expect the packet length to be w/o the
2422 * IP header.
2423 */
2424 ip->ip_len -= hlen;
2425
2426 #if IPDIVERT
2427 /*
2428 * Divert or tee packet to the divert protocol if required.
2429 *
2430 * If div_info is zero then cookie should be too, so we shouldn't
2431 * need to clear them here. Assume divert_packet() does so also.
2432 */
2433 if (div_info != 0) {
2434 struct mbuf *clone = NULL;
2435
2436 /* Clone packet if we're doing a 'tee' */
2437 if (div_info & IP_FW_PORT_TEE_FLAG) {
2438 clone = m_dup(m, M_DONTWAIT);
2439 }
2440
2441 /* Restore packet header fields to original values */
2442 ip->ip_len += hlen;
2443
2444 #if BYTE_ORDER != BIG_ENDIAN
2445 HTONS(ip->ip_len);
2446 HTONS(ip->ip_off);
2447 #endif
2448 /* Deliver packet to divert input routine */
2449 OSAddAtomic(1, &ipstat.ips_delivered);
2450 divert_packet(m, 1, div_info & 0xffff, args.fwa_divert_rule);
2451
2452 /* If 'tee', continue with original packet */
2453 if (clone == NULL) {
2454 return;
2455 }
2456 m = clone;
2457 ip = mtod(m, struct ip *);
2458 }
2459 #endif
2460
2461 #if IPSEC
2462 /*
2463 * enforce IPsec policy checking if we are seeing last header.
2464 * note that we do not visit this with protocols with pcb layer
2465 * code - like udp/tcp/raw ip.
2466 */
2467 if (ipsec_bypass == 0 && (ip_protox[ip->ip_p]->pr_flags & PR_LASTHDR)) {
2468 if (ipsec4_in_reject(m, NULL)) {
2469 IPSEC_STAT_INCREMENT(ipsecstat.in_polvio);
2470 goto bad;
2471 }
2472 }
2473 #endif /* IPSEC */
2474
2475 /*
2476 * Switch out to protocol's input routine.
2477 */
2478 OSAddAtomic(1, &ipstat.ips_delivered);
2479
2480 #if IPFIREWALL
2481 if (args.fwa_next_hop && ip->ip_p == IPPROTO_TCP) {
2482 /* TCP needs IPFORWARD info if available */
2483 struct m_tag *fwd_tag;
2484 struct ip_fwd_tag *ipfwd_tag;
2485
2486 fwd_tag = m_tag_create(KERNEL_MODULE_TAG_ID,
2487 KERNEL_TAG_TYPE_IPFORWARD, sizeof(*ipfwd_tag),
2488 M_NOWAIT, m);
2489 if (fwd_tag == NULL) {
2490 goto bad;
2491 }
2492
2493 ipfwd_tag = (struct ip_fwd_tag *)(fwd_tag + 1);
2494 ipfwd_tag->next_hop = args.fwa_next_hop;
2495
2496 m_tag_prepend(m, fwd_tag);
2497
2498 KERNEL_DEBUG(DBG_LAYER_END, ip->ip_dst.s_addr,
2499 ip->ip_src.s_addr, ip->ip_p, ip->ip_off, ip->ip_len);
2500
2501 /* TCP deals with its own locking */
2502 ip_proto_dispatch_in(m, hlen, ip->ip_p, 0);
2503 } else {
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 if ((sw_lro) && (ip->ip_p == IPPROTO_TCP)) {
2508 m = tcp_lro(m, hlen);
2509 if (m == NULL) {
2510 return;
2511 }
2512 }
2513
2514 ip_proto_dispatch_in(m, hlen, ip->ip_p, 0);
2515 }
2516 #else /* !IPFIREWALL */
2517 if ((sw_lro) && (ip->ip_p == IPPROTO_TCP)) {
2518 m = tcp_lro(m, hlen);
2519 if (m == NULL) {
2520 return;
2521 }
2522 }
2523 ip_proto_dispatch_in(m, hlen, ip->ip_p, 0);
2524 #endif /* !IPFIREWALL */
2525 return;
2526
2527 bad:
2528 KERNEL_DEBUG(DBG_LAYER_END, 0, 0, 0, 0, 0);
2529 m_freem(m);
2530 }
2531
2532 static void
2533 ipq_updateparams(void)
2534 {
2535 LCK_MTX_ASSERT(&ipqlock, LCK_MTX_ASSERT_OWNED);
2536 /*
2537 * -1 for unlimited allocation.
2538 */
2539 if (maxnipq < 0) {
2540 ipq_limit = 0;
2541 }
2542 /*
2543 * Positive number for specific bound.
2544 */
2545 if (maxnipq > 0) {
2546 ipq_limit = maxnipq;
2547 }
2548 /*
2549 * Zero specifies no further fragment queue allocation -- set the
2550 * bound very low, but rely on implementation elsewhere to actually
2551 * prevent allocation and reclaim current queues.
2552 */
2553 if (maxnipq == 0) {
2554 ipq_limit = 1;
2555 }
2556 /*
2557 * Arm the purge timer if not already and if there's work to do
2558 */
2559 frag_sched_timeout();
2560 }
2561
2562 static int
2563 sysctl_maxnipq SYSCTL_HANDLER_ARGS
2564 {
2565 #pragma unused(arg1, arg2)
2566 int error, i;
2567
2568 lck_mtx_lock(&ipqlock);
2569 i = maxnipq;
2570 error = sysctl_handle_int(oidp, &i, 0, req);
2571 if (error || req->newptr == USER_ADDR_NULL) {
2572 goto done;
2573 }
2574 /* impose bounds */
2575 if (i < -1 || i > (nmbclusters / 4)) {
2576 error = EINVAL;
2577 goto done;
2578 }
2579 maxnipq = i;
2580 ipq_updateparams();
2581 done:
2582 lck_mtx_unlock(&ipqlock);
2583 return error;
2584 }
2585
2586 static int
2587 sysctl_maxfragsperpacket SYSCTL_HANDLER_ARGS
2588 {
2589 #pragma unused(arg1, arg2)
2590 int error, i;
2591
2592 lck_mtx_lock(&ipqlock);
2593 i = maxfragsperpacket;
2594 error = sysctl_handle_int(oidp, &i, 0, req);
2595 if (error || req->newptr == USER_ADDR_NULL) {
2596 goto done;
2597 }
2598 maxfragsperpacket = i;
2599 ipq_updateparams(); /* see if we need to arm timer */
2600 done:
2601 lck_mtx_unlock(&ipqlock);
2602 return error;
2603 }
2604
2605 /*
2606 * Take incoming datagram fragment and try to reassemble it into
2607 * whole datagram. If a chain for reassembly of this datagram already
2608 * exists, then it is given as fp; otherwise have to make a chain.
2609 *
2610 * When IPDIVERT enabled, keep additional state with each packet that
2611 * tells us if we need to divert or tee the packet we're building.
2612 *
2613 * The IP header is *NOT* adjusted out of iplen (but in host byte order).
2614 */
2615 static struct mbuf *
2616 #if IPDIVERT
2617 ip_reass(struct mbuf *m,
2618 #ifdef IPDIVERT_44
2619 u_int32_t *divinfo,
2620 #else /* IPDIVERT_44 */
2621 u_int16_t *divinfo,
2622 #endif /* IPDIVERT_44 */
2623 u_int16_t *divcookie)
2624 #else /* IPDIVERT */
2625 ip_reass(struct mbuf *m)
2626 #endif /* IPDIVERT */
2627 {
2628 struct ip *ip;
2629 struct mbuf *p, *q, *nq, *t;
2630 struct ipq *fp = NULL;
2631 struct ipqhead *head;
2632 int i, hlen, next;
2633 u_int8_t ecn, ecn0;
2634 uint32_t csum, csum_flags;
2635 uint16_t hash;
2636 struct fq_head dfq;
2637
2638 MBUFQ_INIT(&dfq); /* for deferred frees */
2639
2640 /* If maxnipq or maxfragsperpacket is 0, never accept fragments. */
2641 if (maxnipq == 0 || maxfragsperpacket == 0) {
2642 ipstat.ips_fragments++;
2643 ipstat.ips_fragdropped++;
2644 m_freem(m);
2645 if (nipq > 0) {
2646 lck_mtx_lock(&ipqlock);
2647 frag_sched_timeout(); /* purge stale fragments */
2648 lck_mtx_unlock(&ipqlock);
2649 }
2650 return NULL;
2651 }
2652
2653 ip = mtod(m, struct ip *);
2654 hlen = IP_VHL_HL(ip->ip_vhl) << 2;
2655
2656 lck_mtx_lock(&ipqlock);
2657
2658 hash = IPREASS_HASH(ip->ip_src.s_addr, ip->ip_id);
2659 head = &ipq[hash];
2660
2661 /*
2662 * Look for queue of fragments
2663 * of this datagram.
2664 */
2665 TAILQ_FOREACH(fp, head, ipq_list) {
2666 if (ip->ip_id == fp->ipq_id &&
2667 ip->ip_src.s_addr == fp->ipq_src.s_addr &&
2668 ip->ip_dst.s_addr == fp->ipq_dst.s_addr &&
2669 #if CONFIG_MACF_NET
2670 mac_ipq_label_compare(m, fp) &&
2671 #endif
2672 ip->ip_p == fp->ipq_p) {
2673 goto found;
2674 }
2675 }
2676
2677 fp = NULL;
2678
2679 /*
2680 * Attempt to trim the number of allocated fragment queues if it
2681 * exceeds the administrative limit.
2682 */
2683 if ((nipq > (unsigned)maxnipq) && (maxnipq > 0)) {
2684 /*
2685 * drop something from the tail of the current queue
2686 * before proceeding further
2687 */
2688 struct ipq *fq = TAILQ_LAST(head, ipqhead);
2689 if (fq == NULL) { /* gak */
2690 for (i = 0; i < IPREASS_NHASH; i++) {
2691 struct ipq *r = TAILQ_LAST(&ipq[i], ipqhead);
2692 if (r) {
2693 ipstat.ips_fragtimeout += r->ipq_nfrags;
2694 frag_freef(&ipq[i], r);
2695 break;
2696 }
2697 }
2698 } else {
2699 ipstat.ips_fragtimeout += fq->ipq_nfrags;
2700 frag_freef(head, fq);
2701 }
2702 }
2703
2704 found:
2705 /*
2706 * Leverage partial checksum offload for IP fragments. Narrow down
2707 * the scope to cover only UDP without IP options, as that is the
2708 * most common case.
2709 *
2710 * Perform 1's complement adjustment of octets that got included/
2711 * excluded in the hardware-calculated checksum value. Ignore cases
2712 * where the value includes the entire IPv4 header span, as the sum
2713 * for those octets would already be 0 by the time we get here; IP
2714 * has already performed its header checksum validation. Also take
2715 * care of any trailing bytes and subtract out their partial sum.
2716 */
2717 if (ip->ip_p == IPPROTO_UDP && hlen == sizeof(struct ip) &&
2718 (m->m_pkthdr.csum_flags &
2719 (CSUM_DATA_VALID | CSUM_PARTIAL | CSUM_PSEUDO_HDR)) ==
2720 (CSUM_DATA_VALID | CSUM_PARTIAL)) {
2721 uint32_t start = m->m_pkthdr.csum_rx_start;
2722 int32_t trailer = (m_pktlen(m) - ip->ip_len);
2723 uint32_t swbytes = (uint32_t)trailer;
2724
2725 csum = m->m_pkthdr.csum_rx_val;
2726
2727 ASSERT(trailer >= 0);
2728 if ((start != 0 && start != hlen) || trailer != 0) {
2729 uint32_t datalen = ip->ip_len - hlen;
2730
2731 #if BYTE_ORDER != BIG_ENDIAN
2732 if (start < hlen) {
2733 HTONS(ip->ip_len);
2734 HTONS(ip->ip_off);
2735 }
2736 #endif /* BYTE_ORDER != BIG_ENDIAN */
2737 /* callee folds in sum */
2738 csum = m_adj_sum16(m, start, hlen, datalen, csum);
2739 if (hlen > start) {
2740 swbytes += (hlen - start);
2741 } else {
2742 swbytes += (start - hlen);
2743 }
2744 #if BYTE_ORDER != BIG_ENDIAN
2745 if (start < hlen) {
2746 NTOHS(ip->ip_off);
2747 NTOHS(ip->ip_len);
2748 }
2749 #endif /* BYTE_ORDER != BIG_ENDIAN */
2750 }
2751 csum_flags = m->m_pkthdr.csum_flags;
2752
2753 if (swbytes != 0) {
2754 udp_in_cksum_stats(swbytes);
2755 }
2756 if (trailer != 0) {
2757 m_adj(m, -trailer);
2758 }
2759 } else {
2760 csum = 0;
2761 csum_flags = 0;
2762 }
2763
2764 /* Invalidate checksum */
2765 m->m_pkthdr.csum_flags &= ~CSUM_DATA_VALID;
2766
2767 ipstat.ips_fragments++;
2768
2769 /*
2770 * Adjust ip_len to not reflect header,
2771 * convert offset of this to bytes.
2772 */
2773 ip->ip_len -= hlen;
2774 if (ip->ip_off & IP_MF) {
2775 /*
2776 * Make sure that fragments have a data length
2777 * that's a non-zero multiple of 8 bytes.
2778 */
2779 if (ip->ip_len == 0 || (ip->ip_len & 0x7) != 0) {
2780 OSAddAtomic(1, &ipstat.ips_toosmall);
2781 /*
2782 * Reassembly queue may have been found if previous
2783 * fragments were valid; given that this one is bad,
2784 * we need to drop it. Make sure to set fp to NULL
2785 * if not already, since we don't want to decrement
2786 * ipq_nfrags as it doesn't include this packet.
2787 */
2788 fp = NULL;
2789 goto dropfrag;
2790 }
2791 m->m_flags |= M_FRAG;
2792 } else {
2793 /* Clear the flag in case packet comes from loopback */
2794 m->m_flags &= ~M_FRAG;
2795 }
2796 ip->ip_off <<= 3;
2797
2798 m->m_pkthdr.pkt_hdr = ip;
2799
2800 /* Previous ip_reass() started here. */
2801 /*
2802 * Presence of header sizes in mbufs
2803 * would confuse code below.
2804 */
2805 m->m_data += hlen;
2806 m->m_len -= hlen;
2807
2808 /*
2809 * If first fragment to arrive, create a reassembly queue.
2810 */
2811 if (fp == NULL) {
2812 fp = ipq_alloc(M_DONTWAIT);
2813 if (fp == NULL) {
2814 goto dropfrag;
2815 }
2816 #if CONFIG_MACF_NET
2817 if (mac_ipq_label_init(fp, M_NOWAIT) != 0) {
2818 ipq_free(fp);
2819 fp = NULL;
2820 goto dropfrag;
2821 }
2822 mac_ipq_label_associate(m, fp);
2823 #endif
2824 TAILQ_INSERT_HEAD(head, fp, ipq_list);
2825 nipq++;
2826 fp->ipq_nfrags = 1;
2827 fp->ipq_ttl = IPFRAGTTL;
2828 fp->ipq_p = ip->ip_p;
2829 fp->ipq_id = ip->ip_id;
2830 fp->ipq_src = ip->ip_src;
2831 fp->ipq_dst = ip->ip_dst;
2832 fp->ipq_frags = m;
2833 m->m_nextpkt = NULL;
2834 /*
2835 * If the first fragment has valid checksum offload
2836 * info, the rest of fragments are eligible as well.
2837 */
2838 if (csum_flags != 0) {
2839 fp->ipq_csum = csum;
2840 fp->ipq_csum_flags = csum_flags;
2841 }
2842 #if IPDIVERT
2843 /*
2844 * Transfer firewall instructions to the fragment structure.
2845 * Only trust info in the fragment at offset 0.
2846 */
2847 if (ip->ip_off == 0) {
2848 #ifdef IPDIVERT_44
2849 fp->ipq_div_info = *divinfo;
2850 #else
2851 fp->ipq_divert = *divinfo;
2852 #endif
2853 fp->ipq_div_cookie = *divcookie;
2854 }
2855 *divinfo = 0;
2856 *divcookie = 0;
2857 #endif /* IPDIVERT */
2858 m = NULL; /* nothing to return */
2859 goto done;
2860 } else {
2861 fp->ipq_nfrags++;
2862 #if CONFIG_MACF_NET
2863 mac_ipq_label_update(m, fp);
2864 #endif
2865 }
2866
2867 #define GETIP(m) ((struct ip *)((m)->m_pkthdr.pkt_hdr))
2868
2869 /*
2870 * Handle ECN by comparing this segment with the first one;
2871 * if CE is set, do not lose CE.
2872 * drop if CE and not-ECT are mixed for the same packet.
2873 */
2874 ecn = ip->ip_tos & IPTOS_ECN_MASK;
2875 ecn0 = GETIP(fp->ipq_frags)->ip_tos & IPTOS_ECN_MASK;
2876 if (ecn == IPTOS_ECN_CE) {
2877 if (ecn0 == IPTOS_ECN_NOTECT) {
2878 goto dropfrag;
2879 }
2880 if (ecn0 != IPTOS_ECN_CE) {
2881 GETIP(fp->ipq_frags)->ip_tos |= IPTOS_ECN_CE;
2882 }
2883 }
2884 if (ecn == IPTOS_ECN_NOTECT && ecn0 != IPTOS_ECN_NOTECT) {
2885 goto dropfrag;
2886 }
2887
2888 /*
2889 * Find a segment which begins after this one does.
2890 */
2891 for (p = NULL, q = fp->ipq_frags; q; p = q, q = q->m_nextpkt) {
2892 if (GETIP(q)->ip_off > ip->ip_off) {
2893 break;
2894 }
2895 }
2896
2897 /*
2898 * If there is a preceding segment, it may provide some of
2899 * our data already. If so, drop the data from the incoming
2900 * segment. If it provides all of our data, drop us, otherwise
2901 * stick new segment in the proper place.
2902 *
2903 * If some of the data is dropped from the preceding
2904 * segment, then it's checksum is invalidated.
2905 */
2906 if (p) {
2907 i = GETIP(p)->ip_off + GETIP(p)->ip_len - ip->ip_off;
2908 if (i > 0) {
2909 if (i >= ip->ip_len) {
2910 goto dropfrag;
2911 }
2912 m_adj(m, i);
2913 fp->ipq_csum_flags = 0;
2914 ip->ip_off += i;
2915 ip->ip_len -= i;
2916 }
2917 m->m_nextpkt = p->m_nextpkt;
2918 p->m_nextpkt = m;
2919 } else {
2920 m->m_nextpkt = fp->ipq_frags;
2921 fp->ipq_frags = m;
2922 }
2923
2924 /*
2925 * While we overlap succeeding segments trim them or,
2926 * if they are completely covered, dequeue them.
2927 */
2928 for (; q != NULL && ip->ip_off + ip->ip_len > GETIP(q)->ip_off;
2929 q = nq) {
2930 i = (ip->ip_off + ip->ip_len) - GETIP(q)->ip_off;
2931 if (i < GETIP(q)->ip_len) {
2932 GETIP(q)->ip_len -= i;
2933 GETIP(q)->ip_off += i;
2934 m_adj(q, i);
2935 fp->ipq_csum_flags = 0;
2936 break;
2937 }
2938 nq = q->m_nextpkt;
2939 m->m_nextpkt = nq;
2940 ipstat.ips_fragdropped++;
2941 fp->ipq_nfrags--;
2942 /* defer freeing until after lock is dropped */
2943 MBUFQ_ENQUEUE(&dfq, q);
2944 }
2945
2946 /*
2947 * If this fragment contains similar checksum offload info
2948 * as that of the existing ones, accumulate checksum. Otherwise,
2949 * invalidate checksum offload info for the entire datagram.
2950 */
2951 if (csum_flags != 0 && csum_flags == fp->ipq_csum_flags) {
2952 fp->ipq_csum += csum;
2953 } else if (fp->ipq_csum_flags != 0) {
2954 fp->ipq_csum_flags = 0;
2955 }
2956
2957 #if IPDIVERT
2958 /*
2959 * Transfer firewall instructions to the fragment structure.
2960 * Only trust info in the fragment at offset 0.
2961 */
2962 if (ip->ip_off == 0) {
2963 #ifdef IPDIVERT_44
2964 fp->ipq_div_info = *divinfo;
2965 #else
2966 fp->ipq_divert = *divinfo;
2967 #endif
2968 fp->ipq_div_cookie = *divcookie;
2969 }
2970 *divinfo = 0;
2971 *divcookie = 0;
2972 #endif /* IPDIVERT */
2973
2974 /*
2975 * Check for complete reassembly and perform frag per packet
2976 * limiting.
2977 *
2978 * Frag limiting is performed here so that the nth frag has
2979 * a chance to complete the packet before we drop the packet.
2980 * As a result, n+1 frags are actually allowed per packet, but
2981 * only n will ever be stored. (n = maxfragsperpacket.)
2982 *
2983 */
2984 next = 0;
2985 for (p = NULL, q = fp->ipq_frags; q; p = q, q = q->m_nextpkt) {
2986 if (GETIP(q)->ip_off != next) {
2987 if (fp->ipq_nfrags > maxfragsperpacket) {
2988 ipstat.ips_fragdropped += fp->ipq_nfrags;
2989 frag_freef(head, fp);
2990 }
2991 m = NULL; /* nothing to return */
2992 goto done;
2993 }
2994 next += GETIP(q)->ip_len;
2995 }
2996 /* Make sure the last packet didn't have the IP_MF flag */
2997 if (p->m_flags & M_FRAG) {
2998 if (fp->ipq_nfrags > maxfragsperpacket) {
2999 ipstat.ips_fragdropped += fp->ipq_nfrags;
3000 frag_freef(head, fp);
3001 }
3002 m = NULL; /* nothing to return */
3003 goto done;
3004 }
3005
3006 /*
3007 * Reassembly is complete. Make sure the packet is a sane size.
3008 */
3009 q = fp->ipq_frags;
3010 ip = GETIP(q);
3011 if (next + (IP_VHL_HL(ip->ip_vhl) << 2) > IP_MAXPACKET) {
3012 ipstat.ips_toolong++;
3013 ipstat.ips_fragdropped += fp->ipq_nfrags;
3014 frag_freef(head, fp);
3015 m = NULL; /* nothing to return */
3016 goto done;
3017 }
3018
3019 /*
3020 * Concatenate fragments.
3021 */
3022 m = q;
3023 t = m->m_next;
3024 m->m_next = NULL;
3025 m_cat(m, t);
3026 nq = q->m_nextpkt;
3027 q->m_nextpkt = NULL;
3028 for (q = nq; q != NULL; q = nq) {
3029 nq = q->m_nextpkt;
3030 q->m_nextpkt = NULL;
3031 m_cat(m, q);
3032 }
3033
3034 /*
3035 * Store partial hardware checksum info from the fragment queue;
3036 * the receive start offset is set to 20 bytes (see code at the
3037 * top of this routine.)
3038 */
3039 if (fp->ipq_csum_flags != 0) {
3040 csum = fp->ipq_csum;
3041
3042 ADDCARRY(csum);
3043
3044 m->m_pkthdr.csum_rx_val = csum;
3045 m->m_pkthdr.csum_rx_start = sizeof(struct ip);
3046 m->m_pkthdr.csum_flags = fp->ipq_csum_flags;
3047 } else if ((m->m_pkthdr.rcvif->if_flags & IFF_LOOPBACK) ||
3048 (m->m_pkthdr.pkt_flags & PKTF_LOOP)) {
3049 /* loopback checksums are always OK */
3050 m->m_pkthdr.csum_data = 0xffff;
3051 m->m_pkthdr.csum_flags =
3052 CSUM_DATA_VALID | CSUM_PSEUDO_HDR |
3053 CSUM_IP_CHECKED | CSUM_IP_VALID;
3054 }
3055
3056 #if IPDIVERT
3057 /*
3058 * Extract firewall instructions from the fragment structure.
3059 */
3060 #ifdef IPDIVERT_44
3061 *divinfo = fp->ipq_div_info;
3062 #else
3063 *divinfo = fp->ipq_divert;
3064 #endif
3065 *divcookie = fp->ipq_div_cookie;
3066 #endif /* IPDIVERT */
3067
3068 #if CONFIG_MACF_NET
3069 mac_mbuf_label_associate_ipq(fp, m);
3070 mac_ipq_label_destroy(fp);
3071 #endif
3072 /*
3073 * Create header for new ip packet by modifying header of first
3074 * packet; dequeue and discard fragment reassembly header.
3075 * Make header visible.
3076 */
3077 ip->ip_len = (IP_VHL_HL(ip->ip_vhl) << 2) + next;
3078 ip->ip_src = fp->ipq_src;
3079 ip->ip_dst = fp->ipq_dst;
3080
3081 fp->ipq_frags = NULL; /* return to caller as 'm' */
3082 frag_freef(head, fp);
3083 fp = NULL;
3084
3085 m->m_len += (IP_VHL_HL(ip->ip_vhl) << 2);
3086 m->m_data -= (IP_VHL_HL(ip->ip_vhl) << 2);
3087 /* some debugging cruft by sklower, below, will go away soon */
3088 if (m->m_flags & M_PKTHDR) { /* XXX this should be done elsewhere */
3089 m_fixhdr(m);
3090 }
3091 ipstat.ips_reassembled++;
3092
3093 /* arm the purge timer if not already and if there's work to do */
3094 frag_sched_timeout();
3095 lck_mtx_unlock(&ipqlock);
3096 /* perform deferred free (if needed) now that lock is dropped */
3097 if (!MBUFQ_EMPTY(&dfq)) {
3098 MBUFQ_DRAIN(&dfq);
3099 }
3100 VERIFY(MBUFQ_EMPTY(&dfq));
3101 return m;
3102
3103 done:
3104 VERIFY(m == NULL);
3105 /* arm the purge timer if not already and if there's work to do */
3106 frag_sched_timeout();
3107 lck_mtx_unlock(&ipqlock);
3108 /* perform deferred free (if needed) */
3109 if (!MBUFQ_EMPTY(&dfq)) {
3110 MBUFQ_DRAIN(&dfq);
3111 }
3112 VERIFY(MBUFQ_EMPTY(&dfq));
3113 return NULL;
3114
3115 dropfrag:
3116 #if IPDIVERT
3117 *divinfo = 0;
3118 *divcookie = 0;
3119 #endif /* IPDIVERT */
3120 ipstat.ips_fragdropped++;
3121 if (fp != NULL) {
3122 fp->ipq_nfrags--;
3123 }
3124 /* arm the purge timer if not already and if there's work to do */
3125 frag_sched_timeout();
3126 lck_mtx_unlock(&ipqlock);
3127 m_freem(m);
3128 /* perform deferred free (if needed) */
3129 if (!MBUFQ_EMPTY(&dfq)) {
3130 MBUFQ_DRAIN(&dfq);
3131 }
3132 VERIFY(MBUFQ_EMPTY(&dfq));
3133 return NULL;
3134 #undef GETIP
3135 }
3136
3137 /*
3138 * Free a fragment reassembly header and all
3139 * associated datagrams.
3140 */
3141 static void
3142 frag_freef(struct ipqhead *fhp, struct ipq *fp)
3143 {
3144 LCK_MTX_ASSERT(&ipqlock, LCK_MTX_ASSERT_OWNED);
3145
3146 fp->ipq_nfrags = 0;
3147 if (fp->ipq_frags != NULL) {
3148 m_freem_list(fp->ipq_frags);
3149 fp->ipq_frags = NULL;
3150 }
3151 TAILQ_REMOVE(fhp, fp, ipq_list);
3152 nipq--;
3153 ipq_free(fp);
3154 }
3155
3156 /*
3157 * IP reassembly timer processing
3158 */
3159 static void
3160 frag_timeout(void *arg)
3161 {
3162 #pragma unused(arg)
3163 struct ipq *fp;
3164 int i;
3165
3166 /*
3167 * Update coarse-grained networking timestamp (in sec.); the idea
3168 * is to piggy-back on the timeout callout to update the counter
3169 * returnable via net_uptime().
3170 */
3171 net_update_uptime();
3172
3173 lck_mtx_lock(&ipqlock);
3174 for (i = 0; i < IPREASS_NHASH; i++) {
3175 for (fp = TAILQ_FIRST(&ipq[i]); fp;) {
3176 struct ipq *fpp;
3177
3178 fpp = fp;
3179 fp = TAILQ_NEXT(fp, ipq_list);
3180 if (--fpp->ipq_ttl == 0) {
3181 ipstat.ips_fragtimeout += fpp->ipq_nfrags;
3182 frag_freef(&ipq[i], fpp);
3183 }
3184 }
3185 }
3186 /*
3187 * If we are over the maximum number of fragments
3188 * (due to the limit being lowered), drain off
3189 * enough to get down to the new limit.
3190 */
3191 if (maxnipq >= 0 && nipq > (unsigned)maxnipq) {
3192 for (i = 0; i < IPREASS_NHASH; i++) {
3193 while (nipq > (unsigned)maxnipq &&
3194 !TAILQ_EMPTY(&ipq[i])) {
3195 ipstat.ips_fragdropped +=
3196 TAILQ_FIRST(&ipq[i])->ipq_nfrags;
3197 frag_freef(&ipq[i], TAILQ_FIRST(&ipq[i]));
3198 }
3199 }
3200 }
3201 /* re-arm the purge timer if there's work to do */
3202 frag_timeout_run = 0;
3203 frag_sched_timeout();
3204 lck_mtx_unlock(&ipqlock);
3205 }
3206
3207 static void
3208 frag_sched_timeout(void)
3209 {
3210 LCK_MTX_ASSERT(&ipqlock, LCK_MTX_ASSERT_OWNED);
3211
3212 if (!frag_timeout_run && nipq > 0) {
3213 frag_timeout_run = 1;
3214 timeout(frag_timeout, NULL, hz);
3215 }
3216 }
3217
3218 /*
3219 * Drain off all datagram fragments.
3220 */
3221 static void
3222 frag_drain(void)
3223 {
3224 int i;
3225
3226 lck_mtx_lock(&ipqlock);
3227 for (i = 0; i < IPREASS_NHASH; i++) {
3228 while (!TAILQ_EMPTY(&ipq[i])) {
3229 ipstat.ips_fragdropped +=
3230 TAILQ_FIRST(&ipq[i])->ipq_nfrags;
3231 frag_freef(&ipq[i], TAILQ_FIRST(&ipq[i]));
3232 }
3233 }
3234 lck_mtx_unlock(&ipqlock);
3235 }
3236
3237 static struct ipq *
3238 ipq_alloc(int how)
3239 {
3240 struct mbuf *t;
3241 struct ipq *fp;
3242
3243 /*
3244 * See comments in ipq_updateparams(). Keep the count separate
3245 * from nipq since the latter represents the elements already
3246 * in the reassembly queues.
3247 */
3248 if (ipq_limit > 0 && ipq_count > ipq_limit) {
3249 return NULL;
3250 }
3251
3252 t = m_get(how, MT_FTABLE);
3253 if (t != NULL) {
3254 atomic_add_32(&ipq_count, 1);
3255 fp = mtod(t, struct ipq *);
3256 bzero(fp, sizeof(*fp));
3257 } else {
3258 fp = NULL;
3259 }
3260 return fp;
3261 }
3262
3263 static void
3264 ipq_free(struct ipq *fp)
3265 {
3266 (void) m_free(dtom(fp));
3267 atomic_add_32(&ipq_count, -1);
3268 }
3269
3270 /*
3271 * Drain callback
3272 */
3273 void
3274 ip_drain(void)
3275 {
3276 frag_drain(); /* fragments */
3277 in_rtqdrain(); /* protocol cloned routes */
3278 in_arpdrain(NULL); /* cloned routes: ARP */
3279 }
3280
3281 /*
3282 * Do option processing on a datagram,
3283 * possibly discarding it if bad options are encountered,
3284 * or forwarding it if source-routed.
3285 * The pass argument is used when operating in the IPSTEALTH
3286 * mode to tell what options to process:
3287 * [LS]SRR (pass 0) or the others (pass 1).
3288 * The reason for as many as two passes is that when doing IPSTEALTH,
3289 * non-routing options should be processed only if the packet is for us.
3290 * Returns 1 if packet has been forwarded/freed,
3291 * 0 if the packet should be processed further.
3292 */
3293 static int
3294 ip_dooptions(struct mbuf *m, int pass, struct sockaddr_in *next_hop)
3295 {
3296 #pragma unused(pass)
3297 struct ip *ip = mtod(m, struct ip *);
3298 u_char *cp;
3299 struct ip_timestamp *ipt;
3300 struct in_ifaddr *ia;
3301 int opt, optlen, cnt, off, code, type = ICMP_PARAMPROB, forward = 0;
3302 struct in_addr *sin, dst;
3303 u_int32_t ntime;
3304 struct sockaddr_in ipaddr = {
3305 .sin_len = sizeof(ipaddr),
3306 .sin_family = AF_INET,
3307 .sin_port = 0,
3308 .sin_addr = { .s_addr = 0 },
3309 .sin_zero = { 0, }
3310 };
3311
3312 /* Expect 32-bit aligned data pointer on strict-align platforms */
3313 MBUF_STRICT_DATA_ALIGNMENT_CHECK_32(m);
3314
3315 dst = ip->ip_dst;
3316 cp = (u_char *)(ip + 1);
3317 cnt = (IP_VHL_HL(ip->ip_vhl) << 2) - sizeof(struct ip);
3318 for (; cnt > 0; cnt -= optlen, cp += optlen) {
3319 opt = cp[IPOPT_OPTVAL];
3320 if (opt == IPOPT_EOL) {
3321 break;
3322 }
3323 if (opt == IPOPT_NOP) {
3324 optlen = 1;
3325 } else {
3326 if (cnt < IPOPT_OLEN + sizeof(*cp)) {
3327 code = &cp[IPOPT_OLEN] - (u_char *)ip;
3328 goto bad;
3329 }
3330 optlen = cp[IPOPT_OLEN];
3331 if (optlen < IPOPT_OLEN + sizeof(*cp) ||
3332 optlen > cnt) {
3333 code = &cp[IPOPT_OLEN] - (u_char *)ip;
3334 goto bad;
3335 }
3336 }
3337 switch (opt) {
3338 default:
3339 break;
3340
3341 /*
3342 * Source routing with record.
3343 * Find interface with current destination address.
3344 * If none on this machine then drop if strictly routed,
3345 * or do nothing if loosely routed.
3346 * Record interface address and bring up next address
3347 * component. If strictly routed make sure next
3348 * address is on directly accessible net.
3349 */
3350 case IPOPT_LSRR:
3351 case IPOPT_SSRR:
3352 if (optlen < IPOPT_OFFSET + sizeof(*cp)) {
3353 code = &cp[IPOPT_OLEN] - (u_char *)ip;
3354 goto bad;
3355 }
3356 if ((off = cp[IPOPT_OFFSET]) < IPOPT_MINOFF) {
3357 code = &cp[IPOPT_OFFSET] - (u_char *)ip;
3358 goto bad;
3359 }
3360 ipaddr.sin_addr = ip->ip_dst;
3361 ia = (struct in_ifaddr *)ifa_ifwithaddr(SA(&ipaddr));
3362 if (ia == NULL) {
3363 if (opt == IPOPT_SSRR) {
3364 type = ICMP_UNREACH;
3365 code = ICMP_UNREACH_SRCFAIL;
3366 goto bad;
3367 }
3368 if (!ip_dosourceroute) {
3369 goto nosourcerouting;
3370 }
3371 /*
3372 * Loose routing, and not at next destination
3373 * yet; nothing to do except forward.
3374 */
3375 break;
3376 } else {
3377 IFA_REMREF(&ia->ia_ifa);
3378 ia = NULL;
3379 }
3380 off--; /* 0 origin */
3381 if (off > optlen - (int)sizeof(struct in_addr)) {
3382 /*
3383 * End of source route. Should be for us.
3384 */
3385 if (!ip_acceptsourceroute) {
3386 goto nosourcerouting;
3387 }
3388 save_rte(cp, ip->ip_src);
3389 break;
3390 }
3391
3392 if (!ip_dosourceroute) {
3393 if (ipforwarding) {
3394 char buf[MAX_IPv4_STR_LEN];
3395 char buf2[MAX_IPv4_STR_LEN];
3396 /*
3397 * Acting as a router, so generate ICMP
3398 */
3399 nosourcerouting:
3400 log(LOG_WARNING,
3401 "attempted source route from %s "
3402 "to %s\n",
3403 inet_ntop(AF_INET, &ip->ip_src,
3404 buf, sizeof(buf)),
3405 inet_ntop(AF_INET, &ip->ip_dst,
3406 buf2, sizeof(buf2)));
3407 type = ICMP_UNREACH;
3408 code = ICMP_UNREACH_SRCFAIL;
3409 goto bad;
3410 } else {
3411 /*
3412 * Not acting as a router,
3413 * so silently drop.
3414 */
3415 OSAddAtomic(1, &ipstat.ips_cantforward);
3416 m_freem(m);
3417 return 1;
3418 }
3419 }
3420
3421 /*
3422 * locate outgoing interface
3423 */
3424 (void) memcpy(&ipaddr.sin_addr, cp + off,
3425 sizeof(ipaddr.sin_addr));
3426
3427 if (opt == IPOPT_SSRR) {
3428 #define INA struct in_ifaddr *
3429 if ((ia = (INA)ifa_ifwithdstaddr(
3430 SA(&ipaddr))) == NULL) {
3431 ia = (INA)ifa_ifwithnet(SA(&ipaddr));
3432 }
3433 } else {
3434 ia = ip_rtaddr(ipaddr.sin_addr);
3435 }
3436 if (ia == NULL) {
3437 type = ICMP_UNREACH;
3438 code = ICMP_UNREACH_SRCFAIL;
3439 goto bad;
3440 }
3441 ip->ip_dst = ipaddr.sin_addr;
3442 IFA_LOCK(&ia->ia_ifa);
3443 (void) memcpy(cp + off, &(IA_SIN(ia)->sin_addr),
3444 sizeof(struct in_addr));
3445 IFA_UNLOCK(&ia->ia_ifa);
3446 IFA_REMREF(&ia->ia_ifa);
3447 ia = NULL;
3448 cp[IPOPT_OFFSET] += sizeof(struct in_addr);
3449 /*
3450 * Let ip_intr's mcast routing check handle mcast pkts
3451 */
3452 forward = !IN_MULTICAST(ntohl(ip->ip_dst.s_addr));
3453 break;
3454
3455 case IPOPT_RR:
3456 if (optlen < IPOPT_OFFSET + sizeof(*cp)) {
3457 code = &cp[IPOPT_OFFSET] - (u_char *)ip;
3458 goto bad;
3459 }
3460 if ((off = cp[IPOPT_OFFSET]) < IPOPT_MINOFF) {
3461 code = &cp[IPOPT_OFFSET] - (u_char *)ip;
3462 goto bad;
3463 }
3464 /*
3465 * If no space remains, ignore.
3466 */
3467 off--; /* 0 origin */
3468 if (off > optlen - (int)sizeof(struct in_addr)) {
3469 break;
3470 }
3471 (void) memcpy(&ipaddr.sin_addr, &ip->ip_dst,
3472 sizeof(ipaddr.sin_addr));
3473 /*
3474 * locate outgoing interface; if we're the destination,
3475 * use the incoming interface (should be same).
3476 */
3477 if ((ia = (INA)ifa_ifwithaddr(SA(&ipaddr))) == NULL) {
3478 if ((ia = ip_rtaddr(ipaddr.sin_addr)) == NULL) {
3479 type = ICMP_UNREACH;
3480 code = ICMP_UNREACH_HOST;
3481 goto bad;
3482 }
3483 }
3484 IFA_LOCK(&ia->ia_ifa);
3485 (void) memcpy(cp + off, &(IA_SIN(ia)->sin_addr),
3486 sizeof(struct in_addr));
3487 IFA_UNLOCK(&ia->ia_ifa);
3488 IFA_REMREF(&ia->ia_ifa);
3489 ia = NULL;
3490 cp[IPOPT_OFFSET] += sizeof(struct in_addr);
3491 break;
3492
3493 case IPOPT_TS:
3494 code = cp - (u_char *)ip;
3495 ipt = (struct ip_timestamp *)(void *)cp;
3496 if (ipt->ipt_len < 4 || ipt->ipt_len > 40) {
3497 code = (u_char *)&ipt->ipt_len - (u_char *)ip;
3498 goto bad;
3499 }
3500 if (ipt->ipt_ptr < 5) {
3501 code = (u_char *)&ipt->ipt_ptr - (u_char *)ip;
3502 goto bad;
3503 }
3504 if (ipt->ipt_ptr >
3505 ipt->ipt_len - (int)sizeof(int32_t)) {
3506 if (++ipt->ipt_oflw == 0) {
3507 code = (u_char *)&ipt->ipt_ptr -
3508 (u_char *)ip;
3509 goto bad;
3510 }
3511 break;
3512 }
3513 sin = (struct in_addr *)(void *)(cp + ipt->ipt_ptr - 1);
3514 switch (ipt->ipt_flg) {
3515 case IPOPT_TS_TSONLY:
3516 break;
3517
3518 case IPOPT_TS_TSANDADDR:
3519 if (ipt->ipt_ptr - 1 + sizeof(n_time) +
3520 sizeof(struct in_addr) > ipt->ipt_len) {
3521 code = (u_char *)&ipt->ipt_ptr -
3522 (u_char *)ip;
3523 goto bad;
3524 }
3525 ipaddr.sin_addr = dst;
3526 ia = (INA)ifaof_ifpforaddr(SA(&ipaddr),
3527 m->m_pkthdr.rcvif);
3528 if (ia == NULL) {
3529 continue;
3530 }
3531 IFA_LOCK(&ia->ia_ifa);
3532 (void) memcpy(sin, &IA_SIN(ia)->sin_addr,
3533 sizeof(struct in_addr));
3534 IFA_UNLOCK(&ia->ia_ifa);
3535 ipt->ipt_ptr += sizeof(struct in_addr);
3536 IFA_REMREF(&ia->ia_ifa);
3537 ia = NULL;
3538 break;
3539
3540 case IPOPT_TS_PRESPEC:
3541 if (ipt->ipt_ptr - 1 + sizeof(n_time) +
3542 sizeof(struct in_addr) > ipt->ipt_len) {
3543 code = (u_char *)&ipt->ipt_ptr -
3544 (u_char *)ip;
3545 goto bad;
3546 }
3547 (void) memcpy(&ipaddr.sin_addr, sin,
3548 sizeof(struct in_addr));
3549 if ((ia = (struct in_ifaddr *)ifa_ifwithaddr(
3550 SA(&ipaddr))) == NULL) {
3551 continue;
3552 }
3553 IFA_REMREF(&ia->ia_ifa);
3554 ia = NULL;
3555 ipt->ipt_ptr += sizeof(struct in_addr);
3556 break;
3557
3558 default:
3559 /* XXX can't take &ipt->ipt_flg */
3560 code = (u_char *)&ipt->ipt_ptr -
3561 (u_char *)ip + 1;
3562 goto bad;
3563 }
3564 ntime = iptime();
3565 (void) memcpy(cp + ipt->ipt_ptr - 1, &ntime,
3566 sizeof(n_time));
3567 ipt->ipt_ptr += sizeof(n_time);
3568 }
3569 }
3570 if (forward && ipforwarding) {
3571 ip_forward(m, 1, next_hop);
3572 return 1;
3573 }
3574 return 0;
3575 bad:
3576 icmp_error(m, type, code, 0, 0);
3577 OSAddAtomic(1, &ipstat.ips_badoptions);
3578 return 1;
3579 }
3580
3581 /*
3582 * Check for the presence of the IP Router Alert option [RFC2113]
3583 * in the header of an IPv4 datagram.
3584 *
3585 * This call is not intended for use from the forwarding path; it is here
3586 * so that protocol domains may check for the presence of the option.
3587 * Given how FreeBSD's IPv4 stack is currently structured, the Router Alert
3588 * option does not have much relevance to the implementation, though this
3589 * may change in future.
3590 * Router alert options SHOULD be passed if running in IPSTEALTH mode and
3591 * we are not the endpoint.
3592 * Length checks on individual options should already have been peformed
3593 * by ip_dooptions() therefore they are folded under DIAGNOSTIC here.
3594 *
3595 * Return zero if not present or options are invalid, non-zero if present.
3596 */
3597 int
3598 ip_checkrouteralert(struct mbuf *m)
3599 {
3600 struct ip *ip = mtod(m, struct ip *);
3601 u_char *cp;
3602 int opt, optlen, cnt, found_ra;
3603
3604 found_ra = 0;
3605 cp = (u_char *)(ip + 1);
3606 cnt = (IP_VHL_HL(ip->ip_vhl) << 2) - sizeof(struct ip);
3607 for (; cnt > 0; cnt -= optlen, cp += optlen) {
3608 opt = cp[IPOPT_OPTVAL];
3609 if (opt == IPOPT_EOL) {
3610 break;
3611 }
3612 if (opt == IPOPT_NOP) {
3613 optlen = 1;
3614 } else {
3615 #ifdef DIAGNOSTIC
3616 if (cnt < IPOPT_OLEN + sizeof(*cp)) {
3617 break;
3618 }
3619 #endif
3620 optlen = cp[IPOPT_OLEN];
3621 #ifdef DIAGNOSTIC
3622 if (optlen < IPOPT_OLEN + sizeof(*cp) || optlen > cnt) {
3623 break;
3624 }
3625 #endif
3626 }
3627 switch (opt) {
3628 case IPOPT_RA:
3629 #ifdef DIAGNOSTIC
3630 if (optlen != IPOPT_OFFSET + sizeof(uint16_t) ||
3631 (*((uint16_t *)(void *)&cp[IPOPT_OFFSET]) != 0)) {
3632 break;
3633 } else
3634 #endif
3635 found_ra = 1;
3636 break;
3637 default:
3638 break;
3639 }
3640 }
3641
3642 return found_ra;
3643 }
3644
3645 /*
3646 * Given address of next destination (final or next hop),
3647 * return internet address info of interface to be used to get there.
3648 */
3649 struct in_ifaddr *
3650 ip_rtaddr(struct in_addr dst)
3651 {
3652 struct sockaddr_in *sin;
3653 struct ifaddr *rt_ifa;
3654 struct route ro;
3655
3656 bzero(&ro, sizeof(ro));
3657 sin = SIN(&ro.ro_dst);
3658 sin->sin_family = AF_INET;
3659 sin->sin_len = sizeof(*sin);
3660 sin->sin_addr = dst;
3661
3662 rtalloc_ign(&ro, RTF_PRCLONING);
3663 if (ro.ro_rt == NULL) {
3664 ROUTE_RELEASE(&ro);
3665 return NULL;
3666 }
3667
3668 RT_LOCK(ro.ro_rt);
3669 if ((rt_ifa = ro.ro_rt->rt_ifa) != NULL) {
3670 IFA_ADDREF(rt_ifa);
3671 }
3672 RT_UNLOCK(ro.ro_rt);
3673 ROUTE_RELEASE(&ro);
3674
3675 return (struct in_ifaddr *)rt_ifa;
3676 }
3677
3678 /*
3679 * Save incoming source route for use in replies,
3680 * to be picked up later by ip_srcroute if the receiver is interested.
3681 */
3682 void
3683 save_rte(u_char *option, struct in_addr dst)
3684 {
3685 unsigned olen;
3686
3687 olen = option[IPOPT_OLEN];
3688 #if DIAGNOSTIC
3689 if (ipprintfs) {
3690 printf("save_rte: olen %d\n", olen);
3691 }
3692 #endif
3693 if (olen > sizeof(ip_srcrt) - (1 + sizeof(dst))) {
3694 return;
3695 }
3696 bcopy(option, ip_srcrt.srcopt, olen);
3697 ip_nhops = (olen - IPOPT_OFFSET - 1) / sizeof(struct in_addr);
3698 ip_srcrt.dst = dst;
3699 }
3700
3701 /*
3702 * Retrieve incoming source route for use in replies,
3703 * in the same form used by setsockopt.
3704 * The first hop is placed before the options, will be removed later.
3705 */
3706 struct mbuf *
3707 ip_srcroute(void)
3708 {
3709 struct in_addr *p, *q;
3710 struct mbuf *m;
3711
3712 if (ip_nhops == 0) {
3713 return NULL;
3714 }
3715
3716 m = m_get(M_DONTWAIT, MT_HEADER);
3717 if (m == NULL) {
3718 return NULL;
3719 }
3720
3721 #define OPTSIZ (sizeof (ip_srcrt.nop) + sizeof (ip_srcrt.srcopt))
3722
3723 /* length is (nhops+1)*sizeof(addr) + sizeof(nop + srcrt header) */
3724 m->m_len = ip_nhops * sizeof(struct in_addr) +
3725 sizeof(struct in_addr) + OPTSIZ;
3726 #if DIAGNOSTIC
3727 if (ipprintfs) {
3728 printf("ip_srcroute: nhops %d mlen %d", ip_nhops, m->m_len);
3729 }
3730 #endif
3731
3732 /*
3733 * First save first hop for return route
3734 */
3735 p = &ip_srcrt.route[ip_nhops - 1];
3736 *(mtod(m, struct in_addr *)) = *p--;
3737 #if DIAGNOSTIC
3738 if (ipprintfs) {
3739 printf(" hops %lx",
3740 (u_int32_t)ntohl(mtod(m, struct in_addr *)->s_addr));
3741 }
3742 #endif
3743
3744 /*
3745 * Copy option fields and padding (nop) to mbuf.
3746 */
3747 ip_srcrt.nop = IPOPT_NOP;
3748 ip_srcrt.srcopt[IPOPT_OFFSET] = IPOPT_MINOFF;
3749 (void) memcpy(mtod(m, caddr_t) + sizeof(struct in_addr),
3750 &ip_srcrt.nop, OPTSIZ);
3751 q = (struct in_addr *)(void *)(mtod(m, caddr_t) +
3752 sizeof(struct in_addr) + OPTSIZ);
3753 #undef OPTSIZ
3754 /*
3755 * Record return path as an IP source route,
3756 * reversing the path (pointers are now aligned).
3757 */
3758 while (p >= ip_srcrt.route) {
3759 #if DIAGNOSTIC
3760 if (ipprintfs) {
3761 printf(" %lx", (u_int32_t)ntohl(q->s_addr));
3762 }
3763 #endif
3764 *q++ = *p--;
3765 }
3766 /*
3767 * Last hop goes to final destination.
3768 */
3769 *q = ip_srcrt.dst;
3770 #if DIAGNOSTIC
3771 if (ipprintfs) {
3772 printf(" %lx\n", (u_int32_t)ntohl(q->s_addr));
3773 }
3774 #endif
3775 return m;
3776 }
3777
3778 /*
3779 * Strip out IP options, at higher level protocol in the kernel.
3780 */
3781 void
3782 ip_stripoptions(struct mbuf *m)
3783 {
3784 int i;
3785 struct ip *ip = mtod(m, struct ip *);
3786 caddr_t opts;
3787 int olen;
3788
3789 /* Expect 32-bit aligned data pointer on strict-align platforms */
3790 MBUF_STRICT_DATA_ALIGNMENT_CHECK_32(m);
3791
3792 /* use bcopy() since it supports overlapping range */
3793 olen = (IP_VHL_HL(ip->ip_vhl) << 2) - sizeof(struct ip);
3794 opts = (caddr_t)(ip + 1);
3795 i = m->m_len - (sizeof(struct ip) + olen);
3796 bcopy(opts + olen, opts, (unsigned)i);
3797 m->m_len -= olen;
3798 if (m->m_flags & M_PKTHDR) {
3799 m->m_pkthdr.len -= olen;
3800 }
3801 ip->ip_vhl = IP_MAKE_VHL(IPVERSION, sizeof(struct ip) >> 2);
3802
3803 /*
3804 * We expect ip_{off,len} to be in host order by now, and
3805 * that the original IP header length has been subtracted
3806 * out from ip_len. Temporarily adjust ip_len for checksum
3807 * recalculation, and restore it afterwards.
3808 */
3809 ip->ip_len += sizeof(struct ip);
3810
3811 /* recompute checksum now that IP header is smaller */
3812 #if BYTE_ORDER != BIG_ENDIAN
3813 HTONS(ip->ip_len);
3814 HTONS(ip->ip_off);
3815 #endif /* BYTE_ORDER != BIG_ENDIAN */
3816 ip->ip_sum = in_cksum_hdr(ip);
3817 #if BYTE_ORDER != BIG_ENDIAN
3818 NTOHS(ip->ip_off);
3819 NTOHS(ip->ip_len);
3820 #endif /* BYTE_ORDER != BIG_ENDIAN */
3821
3822 ip->ip_len -= sizeof(struct ip);
3823
3824 /*
3825 * Given that we've just stripped IP options from the header,
3826 * we need to adjust the start offset accordingly if this
3827 * packet had gone thru partial checksum offload.
3828 */
3829 if ((m->m_pkthdr.csum_flags & (CSUM_DATA_VALID | CSUM_PARTIAL)) ==
3830 (CSUM_DATA_VALID | CSUM_PARTIAL)) {
3831 if (m->m_pkthdr.csum_rx_start >= (sizeof(struct ip) + olen)) {
3832 /* most common case */
3833 m->m_pkthdr.csum_rx_start -= olen;
3834 } else {
3835 /* compute checksum in software instead */
3836 m->m_pkthdr.csum_flags &= ~CSUM_DATA_VALID;
3837 m->m_pkthdr.csum_data = 0;
3838 ipstat.ips_adj_hwcsum_clr++;
3839 }
3840 }
3841 }
3842
3843 u_char inetctlerrmap[PRC_NCMDS] = {
3844 0, 0, 0, 0,
3845 0, EMSGSIZE, EHOSTDOWN, EHOSTUNREACH,
3846 ENETUNREACH, EHOSTUNREACH, ECONNREFUSED, ECONNREFUSED,
3847 EMSGSIZE, EHOSTUNREACH, 0, 0,
3848 0, 0, EHOSTUNREACH, 0,
3849 ENOPROTOOPT, ECONNREFUSED
3850 };
3851
3852 static int
3853 sysctl_ipforwarding SYSCTL_HANDLER_ARGS
3854 {
3855 #pragma unused(arg1, arg2)
3856 int i, was_ipforwarding = ipforwarding;
3857
3858 i = sysctl_handle_int(oidp, oidp->oid_arg1, oidp->oid_arg2, req);
3859 if (i != 0 || req->newptr == USER_ADDR_NULL) {
3860 return i;
3861 }
3862
3863 if (was_ipforwarding && !ipforwarding) {
3864 /* clean up IPv4 forwarding cached routes */
3865 ifnet_head_lock_shared();
3866 for (i = 0; i <= if_index; i++) {
3867 struct ifnet *ifp = ifindex2ifnet[i];
3868 if (ifp != NULL) {
3869 lck_mtx_lock(&ifp->if_cached_route_lock);
3870 ROUTE_RELEASE(&ifp->if_fwd_route);
3871 bzero(&ifp->if_fwd_route,
3872 sizeof(ifp->if_fwd_route));
3873 lck_mtx_unlock(&ifp->if_cached_route_lock);
3874 }
3875 }
3876 ifnet_head_done();
3877 }
3878
3879 return 0;
3880 }
3881
3882 /*
3883 * Similar to inp_route_{copyout,copyin} routines except that these copy
3884 * out the cached IPv4 forwarding route from struct ifnet instead of the
3885 * inpcb. See comments for those routines for explanations.
3886 */
3887 static void
3888 ip_fwd_route_copyout(struct ifnet *ifp, struct route *dst)
3889 {
3890 struct route *src = &ifp->if_fwd_route;
3891
3892 lck_mtx_lock_spin(&ifp->if_cached_route_lock);
3893 lck_mtx_convert_spin(&ifp->if_cached_route_lock);
3894
3895 /* Minor sanity check */
3896 if (src->ro_rt != NULL && rt_key(src->ro_rt)->sa_family != AF_INET) {
3897 panic("%s: wrong or corrupted route: %p", __func__, src);
3898 }
3899
3900 route_copyout(dst, src, sizeof(*dst));
3901
3902 lck_mtx_unlock(&ifp->if_cached_route_lock);
3903 }
3904
3905 static void
3906 ip_fwd_route_copyin(struct ifnet *ifp, struct route *src)
3907 {
3908 struct route *dst = &ifp->if_fwd_route;
3909
3910 lck_mtx_lock_spin(&ifp->if_cached_route_lock);
3911 lck_mtx_convert_spin(&ifp->if_cached_route_lock);
3912
3913 /* Minor sanity check */
3914 if (src->ro_rt != NULL && rt_key(src->ro_rt)->sa_family != AF_INET) {
3915 panic("%s: wrong or corrupted route: %p", __func__, src);
3916 }
3917
3918 if (ifp->if_fwd_cacheok) {
3919 route_copyin(src, dst, sizeof(*src));
3920 }
3921
3922 lck_mtx_unlock(&ifp->if_cached_route_lock);
3923 }
3924
3925 /*
3926 * Forward a packet. If some error occurs return the sender
3927 * an icmp packet. Note we can't always generate a meaningful
3928 * icmp message because icmp doesn't have a large enough repertoire
3929 * of codes and types.
3930 *
3931 * If not forwarding, just drop the packet. This could be confusing
3932 * if ipforwarding was zero but some routing protocol was advancing
3933 * us as a gateway to somewhere. However, we must let the routing
3934 * protocol deal with that.
3935 *
3936 * The srcrt parameter indicates whether the packet is being forwarded
3937 * via a source route.
3938 */
3939 static void
3940 ip_forward(struct mbuf *m, int srcrt, struct sockaddr_in *next_hop)
3941 {
3942 #if !IPFIREWALL
3943 #pragma unused(next_hop)
3944 #endif
3945 struct ip *ip = mtod(m, struct ip *);
3946 struct sockaddr_in *sin;
3947 struct rtentry *rt;
3948 struct route fwd_rt;
3949 int error, type = 0, code = 0;
3950 struct mbuf *mcopy;
3951 n_long dest;
3952 struct in_addr pkt_dst;
3953 u_int32_t nextmtu = 0, len;
3954 struct ip_out_args ipoa;
3955 struct ifnet *rcvifp = m->m_pkthdr.rcvif;
3956
3957 bzero(&ipoa, sizeof(ipoa));
3958 ipoa.ipoa_boundif = IFSCOPE_NONE;
3959 ipoa.ipoa_sotc = SO_TC_UNSPEC;
3960 ipoa.ipoa_netsvctype = _NET_SERVICE_TYPE_UNSPEC;
3961
3962 #if IPSEC
3963 struct secpolicy *sp = NULL;
3964 int ipsecerror;
3965 #endif /* IPSEC */
3966 #if PF
3967 struct pf_mtag *pf_mtag;
3968 #endif /* PF */
3969
3970 dest = 0;
3971 #if IPFIREWALL
3972 /*
3973 * Cache the destination address of the packet; this may be
3974 * changed by use of 'ipfw fwd'.
3975 */
3976 pkt_dst = ((next_hop != NULL) ? next_hop->sin_addr : ip->ip_dst);
3977 #else /* !IPFIREWALL */
3978 pkt_dst = ip->ip_dst;
3979 #endif /* !IPFIREWALL */
3980
3981 #if DIAGNOSTIC
3982 if (ipprintfs) {
3983 printf("forward: src %lx dst %lx ttl %x\n",
3984 (u_int32_t)ip->ip_src.s_addr, (u_int32_t)pkt_dst.s_addr,
3985 ip->ip_ttl);
3986 }
3987 #endif
3988
3989 if (m->m_flags & (M_BCAST | M_MCAST) || !in_canforward(pkt_dst)) {
3990 OSAddAtomic(1, &ipstat.ips_cantforward);
3991 m_freem(m);
3992 return;
3993 }
3994 #if IPSTEALTH
3995 if (!ipstealth) {
3996 #endif /* IPSTEALTH */
3997 if (ip->ip_ttl <= IPTTLDEC) {
3998 icmp_error(m, ICMP_TIMXCEED, ICMP_TIMXCEED_INTRANS,
3999 dest, 0);
4000 return;
4001 }
4002 #if IPSTEALTH
4003 }
4004 #endif /* IPSTEALTH */
4005
4006 #if PF
4007 pf_mtag = pf_find_mtag(m);
4008 if (pf_mtag != NULL && pf_mtag->pftag_rtableid != IFSCOPE_NONE) {
4009 ipoa.ipoa_boundif = pf_mtag->pftag_rtableid;
4010 ipoa.ipoa_flags |= IPOAF_BOUND_IF;
4011 }
4012 #endif /* PF */
4013
4014 ip_fwd_route_copyout(rcvifp, &fwd_rt);
4015
4016 sin = SIN(&fwd_rt.ro_dst);
4017 if (ROUTE_UNUSABLE(&fwd_rt) || pkt_dst.s_addr != sin->sin_addr.s_addr) {
4018 ROUTE_RELEASE(&fwd_rt);
4019
4020 sin->sin_family = AF_INET;
4021 sin->sin_len = sizeof(*sin);
4022 sin->sin_addr = pkt_dst;
4023
4024 rtalloc_scoped_ign(&fwd_rt, RTF_PRCLONING, ipoa.ipoa_boundif);
4025 if (fwd_rt.ro_rt == NULL) {
4026 icmp_error(m, ICMP_UNREACH, ICMP_UNREACH_HOST, dest, 0);
4027 goto done;
4028 }
4029 }
4030 rt = fwd_rt.ro_rt;
4031
4032 /*
4033 * Save the IP header and at most 8 bytes of the payload,
4034 * in case we need to generate an ICMP message to the src.
4035 *
4036 * We don't use m_copy() because it might return a reference
4037 * to a shared cluster. Both this function and ip_output()
4038 * assume exclusive access to the IP header in `m', so any
4039 * data in a cluster may change before we reach icmp_error().
4040 */
4041 MGET(mcopy, M_DONTWAIT, m->m_type);
4042 if (mcopy != NULL) {
4043 M_COPY_PKTHDR(mcopy, m);
4044 mcopy->m_len = imin((IP_VHL_HL(ip->ip_vhl) << 2) + 8,
4045 (int)ip->ip_len);
4046 m_copydata(m, 0, mcopy->m_len, mtod(mcopy, caddr_t));
4047 }
4048
4049 #if IPSTEALTH
4050 if (!ipstealth) {
4051 #endif /* IPSTEALTH */
4052 ip->ip_ttl -= IPTTLDEC;
4053 #if IPSTEALTH
4054 }
4055 #endif /* IPSTEALTH */
4056
4057 /*
4058 * If forwarding packet using same interface that it came in on,
4059 * perhaps should send a redirect to sender to shortcut a hop.
4060 * Only send redirect if source is sending directly to us,
4061 * and if packet was not source routed (or has any options).
4062 * Also, don't send redirect if forwarding using a default route
4063 * or a route modified by a redirect.
4064 */
4065 RT_LOCK_SPIN(rt);
4066 if (rt->rt_ifp == m->m_pkthdr.rcvif &&
4067 !(rt->rt_flags & (RTF_DYNAMIC | RTF_MODIFIED)) &&
4068 satosin(rt_key(rt))->sin_addr.s_addr != INADDR_ANY &&
4069 ipsendredirects && !srcrt && rt->rt_ifa != NULL) {
4070 struct in_ifaddr *ia = (struct in_ifaddr *)rt->rt_ifa;
4071 u_int32_t src = ntohl(ip->ip_src.s_addr);
4072
4073 /* Become a regular mutex */
4074 RT_CONVERT_LOCK(rt);
4075 IFA_LOCK_SPIN(&ia->ia_ifa);
4076 if ((src & ia->ia_subnetmask) == ia->ia_subnet) {
4077 if (rt->rt_flags & RTF_GATEWAY) {
4078 dest = satosin(rt->rt_gateway)->sin_addr.s_addr;
4079 } else {
4080 dest = pkt_dst.s_addr;
4081 }
4082 /*
4083 * Router requirements says to only send
4084 * host redirects.
4085 */
4086 type = ICMP_REDIRECT;
4087 code = ICMP_REDIRECT_HOST;
4088 #if DIAGNOSTIC
4089 if (ipprintfs) {
4090 printf("redirect (%d) to %lx\n", code,
4091 (u_int32_t)dest);
4092 }
4093 #endif
4094 }
4095 IFA_UNLOCK(&ia->ia_ifa);
4096 }
4097 RT_UNLOCK(rt);
4098
4099 #if IPFIREWALL
4100 if (next_hop != NULL) {
4101 /* Pass IPFORWARD info if available */
4102 struct m_tag *tag;
4103 struct ip_fwd_tag *ipfwd_tag;
4104
4105 tag = m_tag_create(KERNEL_MODULE_TAG_ID,
4106 KERNEL_TAG_TYPE_IPFORWARD,
4107 sizeof(*ipfwd_tag), M_NOWAIT, m);
4108 if (tag == NULL) {
4109 error = ENOBUFS;
4110 m_freem(m);
4111 goto done;
4112 }
4113
4114 ipfwd_tag = (struct ip_fwd_tag *)(tag + 1);
4115 ipfwd_tag->next_hop = next_hop;
4116
4117 m_tag_prepend(m, tag);
4118 }
4119 #endif /* IPFIREWALL */
4120
4121 /* Mark this packet as being forwarded from another interface */
4122 m->m_pkthdr.pkt_flags |= PKTF_FORWARDED;
4123 len = m_pktlen(m);
4124
4125 error = ip_output(m, NULL, &fwd_rt, IP_FORWARDING | IP_OUTARGS,
4126 NULL, &ipoa);
4127
4128 /* Refresh rt since the route could have changed while in IP */
4129 rt = fwd_rt.ro_rt;
4130
4131 if (error != 0) {
4132 OSAddAtomic(1, &ipstat.ips_cantforward);
4133 } else {
4134 /*
4135 * Increment stats on the source interface; the ones
4136 * for destination interface has been taken care of
4137 * during output above by virtue of PKTF_FORWARDED.
4138 */
4139 rcvifp->if_fpackets++;
4140 rcvifp->if_fbytes += len;
4141
4142 OSAddAtomic(1, &ipstat.ips_forward);
4143 if (type != 0) {
4144 OSAddAtomic(1, &ipstat.ips_redirectsent);
4145 } else {
4146 if (mcopy != NULL) {
4147 /*
4148 * If we didn't have to go thru ipflow and
4149 * the packet was successfully consumed by
4150 * ip_output, the mcopy is rather a waste;
4151 * this could be further optimized.
4152 */
4153 m_freem(mcopy);
4154 }
4155 goto done;
4156 }
4157 }
4158 if (mcopy == NULL) {
4159 goto done;
4160 }
4161
4162 switch (error) {
4163 case 0: /* forwarded, but need redirect */
4164 /* type, code set above */
4165 break;
4166
4167 case ENETUNREACH: /* shouldn't happen, checked above */
4168 case EHOSTUNREACH:
4169 case ENETDOWN:
4170 case EHOSTDOWN:
4171 default:
4172 type = ICMP_UNREACH;
4173 code = ICMP_UNREACH_HOST;
4174 break;
4175
4176 case EMSGSIZE:
4177 type = ICMP_UNREACH;
4178 code = ICMP_UNREACH_NEEDFRAG;
4179
4180 if (rt == NULL) {
4181 break;
4182 } else {
4183 RT_LOCK_SPIN(rt);
4184 if (rt->rt_ifp != NULL) {
4185 nextmtu = rt->rt_ifp->if_mtu;
4186 }
4187 RT_UNLOCK(rt);
4188 }
4189 #ifdef IPSEC
4190 if (ipsec_bypass) {
4191 break;
4192 }
4193
4194 /*
4195 * If the packet is routed over IPsec tunnel, tell the
4196 * originator the tunnel MTU.
4197 * tunnel MTU = if MTU - sizeof(IP) - ESP/AH hdrsiz
4198 * XXX quickhack!!!
4199 */
4200 sp = ipsec4_getpolicybyaddr(mcopy, IPSEC_DIR_OUTBOUND,
4201 IP_FORWARDING, &ipsecerror);
4202
4203 if (sp == NULL) {
4204 break;
4205 }
4206
4207 /*
4208 * find the correct route for outer IPv4
4209 * header, compute tunnel MTU.
4210 */
4211 nextmtu = 0;
4212
4213 if (sp->req != NULL &&
4214 sp->req->saidx.mode == IPSEC_MODE_TUNNEL) {
4215 struct secasindex saidx;
4216 struct secasvar *sav;
4217 struct route *ro;
4218 struct ip *ipm;
4219 int ipsechdr;
4220
4221 /* count IPsec header size */
4222 ipsechdr = ipsec_hdrsiz(sp);
4223
4224 ipm = mtod(mcopy, struct ip *);
4225 bcopy(&sp->req->saidx, &saidx, sizeof(saidx));
4226 saidx.mode = sp->req->saidx.mode;
4227 saidx.reqid = sp->req->saidx.reqid;
4228 sin = SIN(&saidx.src);
4229 if (sin->sin_len == 0) {
4230 sin->sin_len = sizeof(*sin);
4231 sin->sin_family = AF_INET;
4232 sin->sin_port = IPSEC_PORT_ANY;
4233 bcopy(&ipm->ip_src, &sin->sin_addr,
4234 sizeof(sin->sin_addr));
4235 }
4236 sin = SIN(&saidx.dst);
4237 if (sin->sin_len == 0) {
4238 sin->sin_len = sizeof(*sin);
4239 sin->sin_family = AF_INET;
4240 sin->sin_port = IPSEC_PORT_ANY;
4241 bcopy(&ipm->ip_dst, &sin->sin_addr,
4242 sizeof(sin->sin_addr));
4243 }
4244 sav = key_allocsa_policy(&saidx);
4245 if (sav != NULL) {
4246 lck_mtx_lock(sadb_mutex);
4247 if (sav->sah != NULL) {
4248 ro = (struct route *)&sav->sah->sa_route;
4249 if (ro->ro_rt != NULL) {
4250 RT_LOCK(ro->ro_rt);
4251 if (ro->ro_rt->rt_ifp != NULL) {
4252 nextmtu = ro->ro_rt->
4253 rt_ifp->if_mtu;
4254 nextmtu -= ipsechdr;
4255 }
4256 RT_UNLOCK(ro->ro_rt);
4257 }
4258 }
4259 key_freesav(sav, KEY_SADB_LOCKED);
4260 lck_mtx_unlock(sadb_mutex);
4261 }
4262 }
4263 key_freesp(sp, KEY_SADB_UNLOCKED);
4264 #endif /* IPSEC */
4265 break;
4266
4267 case ENOBUFS:
4268 /*
4269 * A router should not generate ICMP_SOURCEQUENCH as
4270 * required in RFC1812 Requirements for IP Version 4 Routers.
4271 * Source quench could be a big problem under DoS attacks,
4272 * or if the underlying interface is rate-limited.
4273 * Those who need source quench packets may re-enable them
4274 * via the net.inet.ip.sendsourcequench sysctl.
4275 */
4276 if (ip_sendsourcequench == 0) {
4277 m_freem(mcopy);
4278 goto done;
4279 } else {
4280 type = ICMP_SOURCEQUENCH;
4281 code = 0;
4282 }
4283 break;
4284
4285 case EACCES: /* ipfw denied packet */
4286 m_freem(mcopy);
4287 goto done;
4288 }
4289
4290 if (type == ICMP_UNREACH && code == ICMP_UNREACH_NEEDFRAG) {
4291 OSAddAtomic(1, &ipstat.ips_cantfrag);
4292 }
4293
4294 icmp_error(mcopy, type, code, dest, nextmtu);
4295 done:
4296 ip_fwd_route_copyin(rcvifp, &fwd_rt);
4297 }
4298
4299 int
4300 ip_savecontrol(struct inpcb *inp, struct mbuf **mp, struct ip *ip,
4301 struct mbuf *m)
4302 {
4303 *mp = NULL;
4304 if (inp->inp_socket->so_options & SO_TIMESTAMP) {
4305 struct timeval tv;
4306
4307 getmicrotime(&tv);
4308 mp = sbcreatecontrol_mbuf((caddr_t)&tv, sizeof(tv),
4309 SCM_TIMESTAMP, SOL_SOCKET, mp);
4310 if (*mp == NULL) {
4311 goto no_mbufs;
4312 }
4313 }
4314 if (inp->inp_socket->so_options & SO_TIMESTAMP_MONOTONIC) {
4315 uint64_t time;
4316
4317 time = mach_absolute_time();
4318 mp = sbcreatecontrol_mbuf((caddr_t)&time, sizeof(time),
4319 SCM_TIMESTAMP_MONOTONIC, SOL_SOCKET, mp);
4320 if (*mp == NULL) {
4321 goto no_mbufs;
4322 }
4323 }
4324 if (inp->inp_socket->so_options & SO_TIMESTAMP_CONTINUOUS) {
4325 uint64_t time;
4326
4327 time = mach_continuous_time();
4328 mp = sbcreatecontrol_mbuf((caddr_t)&time, sizeof(time),
4329 SCM_TIMESTAMP_CONTINUOUS, SOL_SOCKET, mp);
4330 if (*mp == NULL) {
4331 goto no_mbufs;
4332 }
4333 }
4334 if (inp->inp_flags & INP_RECVDSTADDR) {
4335 mp = sbcreatecontrol_mbuf((caddr_t)&ip->ip_dst,
4336 sizeof(struct in_addr), IP_RECVDSTADDR, IPPROTO_IP, mp);
4337 if (*mp == NULL) {
4338 goto no_mbufs;
4339 }
4340 }
4341 #ifdef notyet
4342 /*
4343 * XXX
4344 * Moving these out of udp_input() made them even more broken
4345 * than they already were.
4346 */
4347 /* options were tossed already */
4348 if (inp->inp_flags & INP_RECVOPTS) {
4349 mp = sbcreatecontrol_mbuf((caddr_t)opts_deleted_above,
4350 sizeof(struct in_addr), IP_RECVOPTS, IPPROTO_IP, mp);
4351 if (*mp == NULL) {
4352 goto no_mbufs;
4353 }
4354 }
4355 /* ip_srcroute doesn't do what we want here, need to fix */
4356 if (inp->inp_flags & INP_RECVRETOPTS) {
4357 mp = sbcreatecontrol_mbuf((caddr_t)ip_srcroute(),
4358 sizeof(struct in_addr), IP_RECVRETOPTS, IPPROTO_IP, mp);
4359 if (*mp == NULL) {
4360 goto no_mbufs;
4361 }
4362 }
4363 #endif /* notyet */
4364 if (inp->inp_flags & INP_RECVIF) {
4365 struct ifnet *ifp;
4366 uint8_t sdlbuf[SOCK_MAXADDRLEN + 1];
4367 struct sockaddr_dl *sdl2 = SDL(&sdlbuf);
4368
4369 /*
4370 * Make sure to accomodate the largest possible
4371 * size of SA(if_lladdr)->sa_len.
4372 */
4373 _CASSERT(sizeof(sdlbuf) == (SOCK_MAXADDRLEN + 1));
4374
4375 ifnet_head_lock_shared();
4376 if ((ifp = m->m_pkthdr.rcvif) != NULL &&
4377 ifp->if_index && (ifp->if_index <= if_index)) {
4378 struct ifaddr *ifa = ifnet_addrs[ifp->if_index - 1];
4379 struct sockaddr_dl *sdp;
4380
4381 if (!ifa || !ifa->ifa_addr) {
4382 goto makedummy;
4383 }
4384
4385 IFA_LOCK_SPIN(ifa);
4386 sdp = SDL(ifa->ifa_addr);
4387 /*
4388 * Change our mind and don't try copy.
4389 */
4390 if (sdp->sdl_family != AF_LINK) {
4391 IFA_UNLOCK(ifa);
4392 goto makedummy;
4393 }
4394 /* the above _CASSERT ensures sdl_len fits in sdlbuf */
4395 bcopy(sdp, sdl2, sdp->sdl_len);
4396 IFA_UNLOCK(ifa);
4397 } else {
4398 makedummy:
4399 sdl2->sdl_len =
4400 offsetof(struct sockaddr_dl, sdl_data[0]);
4401 sdl2->sdl_family = AF_LINK;
4402 sdl2->sdl_index = 0;
4403 sdl2->sdl_nlen = sdl2->sdl_alen = sdl2->sdl_slen = 0;
4404 }
4405 ifnet_head_done();
4406 mp = sbcreatecontrol_mbuf((caddr_t)sdl2, sdl2->sdl_len,
4407 IP_RECVIF, IPPROTO_IP, mp);
4408 if (*mp == NULL) {
4409 goto no_mbufs;
4410 }
4411 }
4412 if (inp->inp_flags & INP_RECVTTL) {
4413 mp = sbcreatecontrol_mbuf((caddr_t)&ip->ip_ttl,
4414 sizeof(ip->ip_ttl), IP_RECVTTL, IPPROTO_IP, mp);
4415 if (*mp == NULL) {
4416 goto no_mbufs;
4417 }
4418 }
4419 if (inp->inp_socket->so_flags & SOF_RECV_TRAFFIC_CLASS) {
4420 int tc = m_get_traffic_class(m);
4421
4422 mp = sbcreatecontrol_mbuf((caddr_t)&tc, sizeof(tc),
4423 SO_TRAFFIC_CLASS, SOL_SOCKET, mp);
4424 if (*mp == NULL) {
4425 goto no_mbufs;
4426 }
4427 }
4428 if (inp->inp_flags & INP_PKTINFO) {
4429 struct in_pktinfo pi;
4430
4431 bzero(&pi, sizeof(struct in_pktinfo));
4432 bcopy(&ip->ip_dst, &pi.ipi_addr, sizeof(struct in_addr));
4433 pi.ipi_ifindex = (m != NULL && m->m_pkthdr.rcvif != NULL) ?
4434 m->m_pkthdr.rcvif->if_index : 0;
4435
4436 mp = sbcreatecontrol_mbuf((caddr_t)&pi,
4437 sizeof(struct in_pktinfo), IP_RECVPKTINFO, IPPROTO_IP, mp);
4438 if (*mp == NULL) {
4439 goto no_mbufs;
4440 }
4441 }
4442 if (inp->inp_flags & INP_RECVTOS) {
4443 mp = sbcreatecontrol_mbuf((caddr_t)&ip->ip_tos,
4444 sizeof(u_char), IP_RECVTOS, IPPROTO_IP, mp);
4445 if (*mp == NULL) {
4446 goto no_mbufs;
4447 }
4448 }
4449 return 0;
4450
4451 no_mbufs:
4452 ipstat.ips_pktdropcntrl++;
4453 return ENOBUFS;
4454 }
4455
4456 static inline u_short
4457 ip_cksum(struct mbuf *m, int hlen)
4458 {
4459 u_short sum;
4460
4461 if (m->m_pkthdr.csum_flags & CSUM_IP_CHECKED) {
4462 sum = !(m->m_pkthdr.csum_flags & CSUM_IP_VALID);
4463 } else if (!(m->m_pkthdr.rcvif->if_flags & IFF_LOOPBACK) &&
4464 !(m->m_pkthdr.pkt_flags & PKTF_LOOP)) {
4465 /*
4466 * The packet arrived on an interface which isn't capable
4467 * of performing IP header checksum; compute it now.
4468 */
4469 sum = ip_cksum_hdr_in(m, hlen);
4470 } else {
4471 sum = 0;
4472 m->m_pkthdr.csum_flags |= (CSUM_DATA_VALID | CSUM_PSEUDO_HDR |
4473 CSUM_IP_CHECKED | CSUM_IP_VALID);
4474 m->m_pkthdr.csum_data = 0xffff;
4475 }
4476
4477 if (sum != 0) {
4478 OSAddAtomic(1, &ipstat.ips_badsum);
4479 }
4480
4481 return sum;
4482 }
4483
4484 static int
4485 ip_getstat SYSCTL_HANDLER_ARGS
4486 {
4487 #pragma unused(oidp, arg1, arg2)
4488 if (req->oldptr == USER_ADDR_NULL) {
4489 req->oldlen = (size_t)sizeof(struct ipstat);
4490 }
4491
4492 return SYSCTL_OUT(req, &ipstat, MIN(sizeof(ipstat), req->oldlen));
4493 }
4494
4495 void
4496 ip_setsrcifaddr_info(struct mbuf *m, uint32_t src_idx, struct in_ifaddr *ia)
4497 {
4498 VERIFY(m->m_flags & M_PKTHDR);
4499
4500 /*
4501 * If the source ifaddr is specified, pick up the information
4502 * from there; otherwise just grab the passed-in ifindex as the
4503 * caller may not have the ifaddr available.
4504 */
4505 if (ia != NULL) {
4506 m->m_pkthdr.pkt_flags |= PKTF_IFAINFO;
4507 m->m_pkthdr.src_ifindex = ia->ia_ifp->if_index;
4508 } else {
4509 m->m_pkthdr.src_ifindex = src_idx;
4510 if (src_idx != 0) {
4511 m->m_pkthdr.pkt_flags |= PKTF_IFAINFO;
4512 }
4513 }
4514 }
4515
4516 void
4517 ip_setdstifaddr_info(struct mbuf *m, uint32_t dst_idx, struct in_ifaddr *ia)
4518 {
4519 VERIFY(m->m_flags & M_PKTHDR);
4520
4521 /*
4522 * If the destination ifaddr is specified, pick up the information
4523 * from there; otherwise just grab the passed-in ifindex as the
4524 * caller may not have the ifaddr available.
4525 */
4526 if (ia != NULL) {
4527 m->m_pkthdr.pkt_flags |= PKTF_IFAINFO;
4528 m->m_pkthdr.dst_ifindex = ia->ia_ifp->if_index;
4529 } else {
4530 m->m_pkthdr.dst_ifindex = dst_idx;
4531 if (dst_idx != 0) {
4532 m->m_pkthdr.pkt_flags |= PKTF_IFAINFO;
4533 }
4534 }
4535 }
4536
4537 int
4538 ip_getsrcifaddr_info(struct mbuf *m, uint32_t *src_idx, uint32_t *iaf)
4539 {
4540 VERIFY(m->m_flags & M_PKTHDR);
4541
4542 if (!(m->m_pkthdr.pkt_flags & PKTF_IFAINFO)) {
4543 return -1;
4544 }
4545
4546 if (src_idx != NULL) {
4547 *src_idx = m->m_pkthdr.src_ifindex;
4548 }
4549
4550 if (iaf != NULL) {
4551 *iaf = 0;
4552 }
4553
4554 return 0;
4555 }
4556
4557 int
4558 ip_getdstifaddr_info(struct mbuf *m, uint32_t *dst_idx, uint32_t *iaf)
4559 {
4560 VERIFY(m->m_flags & M_PKTHDR);
4561
4562 if (!(m->m_pkthdr.pkt_flags & PKTF_IFAINFO)) {
4563 return -1;
4564 }
4565
4566 if (dst_idx != NULL) {
4567 *dst_idx = m->m_pkthdr.dst_ifindex;
4568 }
4569
4570 if (iaf != NULL) {
4571 *iaf = 0;
4572 }
4573
4574 return 0;
4575 }
4576
4577 /*
4578 * Protocol input handler for IPPROTO_GRE.
4579 */
4580 void
4581 gre_input(struct mbuf *m, int off)
4582 {
4583 gre_input_func_t fn = gre_input_func;
4584
4585 /*
4586 * If there is a registered GRE input handler, pass mbuf to it.
4587 */
4588 if (fn != NULL) {
4589 lck_mtx_unlock(inet_domain_mutex);
4590 m = fn(m, off, (mtod(m, struct ip *))->ip_p);
4591 lck_mtx_lock(inet_domain_mutex);
4592 }
4593
4594 /*
4595 * If no matching tunnel that is up is found, we inject
4596 * the mbuf to raw ip socket to see if anyone picks it up.
4597 */
4598 if (m != NULL) {
4599 rip_input(m, off);
4600 }
4601 }
4602
4603 /*
4604 * Private KPI for PPP/PPTP.
4605 */
4606 int
4607 ip_gre_register_input(gre_input_func_t fn)
4608 {
4609 lck_mtx_lock(inet_domain_mutex);
4610 gre_input_func = fn;
4611 lck_mtx_unlock(inet_domain_mutex);
4612
4613 return 0;
4614 }
4615
4616 #if (DEBUG || DEVELOPMENT)
4617 static int
4618 sysctl_reset_ip_input_stats SYSCTL_HANDLER_ARGS
4619 {
4620 #pragma unused(arg1, arg2)
4621 int error, i;
4622
4623 i = ip_input_measure;
4624 error = sysctl_handle_int(oidp, &i, 0, req);
4625 if (error || req->newptr == USER_ADDR_NULL) {
4626 goto done;
4627 }
4628 /* impose bounds */
4629 if (i < 0 || i > 1) {
4630 error = EINVAL;
4631 goto done;
4632 }
4633 if (ip_input_measure != i && i == 1) {
4634 net_perf_initialize(&net_perf, ip_input_measure_bins);
4635 }
4636 ip_input_measure = i;
4637 done:
4638 return error;
4639 }
4640
4641 static int
4642 sysctl_ip_input_measure_bins SYSCTL_HANDLER_ARGS
4643 {
4644 #pragma unused(arg1, arg2)
4645 int error;
4646 uint64_t i;
4647
4648 i = ip_input_measure_bins;
4649 error = sysctl_handle_quad(oidp, &i, 0, req);
4650 if (error || req->newptr == USER_ADDR_NULL) {
4651 goto done;
4652 }
4653 /* validate data */
4654 if (!net_perf_validate_bins(i)) {
4655 error = EINVAL;
4656 goto done;
4657 }
4658 ip_input_measure_bins = i;
4659 done:
4660 return error;
4661 }
4662
4663 static int
4664 sysctl_ip_input_getperf SYSCTL_HANDLER_ARGS
4665 {
4666 #pragma unused(oidp, arg1, arg2)
4667 if (req->oldptr == USER_ADDR_NULL) {
4668 req->oldlen = (size_t)sizeof(struct ipstat);
4669 }
4670
4671 return SYSCTL_OUT(req, &net_perf, MIN(sizeof(net_perf), req->oldlen));
4672 }
4673 #endif /* (DEBUG || DEVELOPMENT) */