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