]> git.saurik.com Git - apple/xnu.git/blob - bsd/netinet/ip_input.c
a6c47e084706df255c37e380f49920b0472b214d
[apple/xnu.git] / bsd / netinet / ip_input.c
1 /*
2 * Copyright (c) 2000-2008 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 * $FreeBSD: src/sys/netinet/ip_input.c,v 1.130.2.25 2001/08/29 21:41:37 jesper Exp $
62 */
63 /*
64 * NOTICE: This file was modified by SPARTA, Inc. in 2007 to introduce
65 * support for mandatory and extensible security protections. This notice
66 * is included in support of clause 2.2 (b) of the Apple Public License,
67 * Version 2.0.
68 */
69
70 #define _IP_VHL
71
72 #include <sys/param.h>
73 #include <sys/systm.h>
74 #include <sys/mbuf.h>
75 #include <sys/malloc.h>
76 #include <sys/domain.h>
77 #include <sys/protosw.h>
78 #include <sys/socket.h>
79 #include <sys/time.h>
80 #include <sys/kernel.h>
81 #include <sys/syslog.h>
82 #include <sys/sysctl.h>
83
84 #include <machine/endian.h>
85
86 #include <kern/queue.h>
87 #include <kern/locks.h>
88
89 #include <pexpert/pexpert.h>
90
91 #include <net/if.h>
92 #include <net/if_var.h>
93 #include <net/if_dl.h>
94 #include <net/route.h>
95 #include <net/kpi_protocol.h>
96
97 #include <netinet/in.h>
98 #include <netinet/in_systm.h>
99 #include <netinet/in_var.h>
100 #include <netinet/in_arp.h>
101 #include <netinet/ip.h>
102 #include <netinet/in_pcb.h>
103 #include <netinet/ip_var.h>
104 #include <netinet/ip_icmp.h>
105 #include <sys/socketvar.h>
106
107 #include <netinet/ip_fw.h>
108 #include <netinet/ip_divert.h>
109
110 #include <netinet/kpi_ipfilter_var.h>
111
112 /* needed for AUTOCONFIGURING: */
113 #include <netinet/udp.h>
114 #include <netinet/udp_var.h>
115 #include <netinet/bootp.h>
116
117 #if CONFIG_MACF_NET
118 #include <security/mac_framework.h>
119 #endif
120
121 #include <sys/kdebug.h>
122 #include <libkern/OSAtomic.h>
123
124 #define DBG_LAYER_BEG NETDBG_CODE(DBG_NETIP, 0)
125 #define DBG_LAYER_END NETDBG_CODE(DBG_NETIP, 2)
126 #define DBG_FNC_IP_INPUT NETDBG_CODE(DBG_NETIP, (2 << 8))
127
128
129 #if IPSEC
130 #include <netinet6/ipsec.h>
131 #include <netkey/key.h>
132 #endif
133
134 #include "faith.h"
135 #if defined(NFAITH) && NFAITH > 0
136 #include <net/if_types.h>
137 #endif
138
139 #if DUMMYNET
140 #include <netinet/ip_dummynet.h>
141 #endif
142
143 #if PF
144 #include <net/pfvar.h>
145 #endif /* PF */
146
147 #if IPSEC
148 extern int ipsec_bypass;
149 extern lck_mtx_t *sadb_mutex;
150
151 lck_grp_t *sadb_stat_mutex_grp;
152 lck_grp_attr_t *sadb_stat_mutex_grp_attr;
153 lck_attr_t *sadb_stat_mutex_attr;
154 lck_mtx_t *sadb_stat_mutex;
155
156 #endif
157
158 int rsvp_on = 0;
159 static int ip_rsvp_on;
160 struct socket *ip_rsvpd;
161
162 static int sysctl_ipforwarding SYSCTL_HANDLER_ARGS;
163
164 int ipforwarding = 0;
165 SYSCTL_PROC(_net_inet_ip, IPCTL_FORWARDING, forwarding,
166 CTLTYPE_INT | CTLFLAG_RW | CTLFLAG_LOCKED, &ipforwarding, 0,
167 sysctl_ipforwarding, "I", "Enable IP forwarding between interfaces");
168
169 static int ipsendredirects = 1; /* XXX */
170 SYSCTL_INT(_net_inet_ip, IPCTL_SENDREDIRECTS, redirect, CTLFLAG_RW,
171 &ipsendredirects, 0, "Enable sending IP redirects");
172
173 int ip_defttl = IPDEFTTL;
174 SYSCTL_INT(_net_inet_ip, IPCTL_DEFTTL, ttl, CTLFLAG_RW,
175 &ip_defttl, 0, "Maximum TTL on IP packets");
176
177 static int ip_dosourceroute = 0;
178 SYSCTL_INT(_net_inet_ip, IPCTL_SOURCEROUTE, sourceroute, CTLFLAG_RW,
179 &ip_dosourceroute, 0, "Enable forwarding source routed IP packets");
180
181 static int ip_acceptsourceroute = 0;
182 SYSCTL_INT(_net_inet_ip, IPCTL_ACCEPTSOURCEROUTE, accept_sourceroute,
183 CTLFLAG_RW, &ip_acceptsourceroute, 0,
184 "Enable accepting source routed IP packets");
185
186 static int ip_keepfaith = 0;
187 SYSCTL_INT(_net_inet_ip, IPCTL_KEEPFAITH, keepfaith, CTLFLAG_RW,
188 &ip_keepfaith, 0,
189 "Enable packet capture for FAITH IPv4->IPv6 translater daemon");
190
191 static int nipq = 0; /* total # of reass queues */
192 static int maxnipq;
193 SYSCTL_INT(_net_inet_ip, OID_AUTO, maxfragpackets, CTLFLAG_RW,
194 &maxnipq, 0,
195 "Maximum number of IPv4 fragment reassembly queue entries");
196
197 static int maxfragsperpacket;
198 SYSCTL_INT(_net_inet_ip, OID_AUTO, maxfragsperpacket, CTLFLAG_RW,
199 &maxfragsperpacket, 0,
200 "Maximum number of IPv4 fragments allowed per packet");
201
202 static int maxfrags;
203 SYSCTL_INT(_net_inet_ip, OID_AUTO, maxfrags, CTLFLAG_RW,
204 &maxfrags, 0, "Maximum number of IPv4 fragments allowed");
205
206 static int currentfrags = 0;
207
208 int ip_doscopedroute = 1;
209 SYSCTL_INT(_net_inet_ip, OID_AUTO, scopedroute, CTLFLAG_RW,
210 &ip_doscopedroute, 0, "Enable IPv4 scoped routing");
211
212 /*
213 * XXX - Setting ip_checkinterface mostly implements the receive side of
214 * the Strong ES model described in RFC 1122, but since the routing table
215 * and transmit implementation do not implement the Strong ES model,
216 * setting this to 1 results in an odd hybrid.
217 *
218 * XXX - ip_checkinterface currently must be disabled if you use ipnat
219 * to translate the destination address to another local interface.
220 *
221 * XXX - ip_checkinterface must be disabled if you add IP aliases
222 * to the loopback interface instead of the interface where the
223 * packets for those addresses are received.
224 */
225 static int ip_checkinterface = 0;
226 SYSCTL_INT(_net_inet_ip, OID_AUTO, check_interface, CTLFLAG_RW,
227 &ip_checkinterface, 0, "Verify packet arrives on correct interface");
228
229
230 #if DIAGNOSTIC
231 static int ipprintfs = 0;
232 #endif
233
234 extern int in_proto_count;
235 extern struct domain inetdomain;
236 extern struct protosw inetsw[];
237 struct protosw *ip_protox[IPPROTO_MAX];
238 static int ipqmaxlen = IFQ_MAXLEN;
239
240 static lck_grp_attr_t *in_ifaddr_rwlock_grp_attr;
241 static lck_grp_t *in_ifaddr_rwlock_grp;
242 static lck_attr_t *in_ifaddr_rwlock_attr;
243 lck_rw_t *in_ifaddr_rwlock;
244
245 /* Protected by in_ifaddr_rwlock */
246 struct in_ifaddrhead in_ifaddrhead; /* first inet address */
247 struct in_ifaddrhashhead *in_ifaddrhashtbl; /* inet addr hash table */
248
249 #define INADDR_NHASH 61
250 static u_int32_t inaddr_nhash; /* hash table size */
251 static u_int32_t inaddr_hashp; /* next largest prime */
252
253 struct ifqueue ipintrq;
254 SYSCTL_INT(_net_inet_ip, IPCTL_INTRQMAXLEN, intr_queue_maxlen, CTLFLAG_RW,
255 &ipintrq.ifq_maxlen, 0, "Maximum size of the IP input queue");
256 SYSCTL_INT(_net_inet_ip, IPCTL_INTRQDROPS, intr_queue_drops, CTLFLAG_RD,
257 &ipintrq.ifq_drops, 0, "Number of packets dropped from the IP input queue");
258
259 struct ipstat ipstat;
260 SYSCTL_STRUCT(_net_inet_ip, IPCTL_STATS, stats, CTLFLAG_RD,
261 &ipstat, ipstat, "IP statistics (struct ipstat, netinet/ip_var.h)");
262
263 /* Packet reassembly stuff */
264 #define IPREASS_NHASH_LOG2 6
265 #define IPREASS_NHASH (1 << IPREASS_NHASH_LOG2)
266 #define IPREASS_HMASK (IPREASS_NHASH - 1)
267 #define IPREASS_HASH(x,y) \
268 (((((x) & 0xF) | ((((x) >> 8) & 0xF) << 4)) ^ (y)) & IPREASS_HMASK)
269
270 static struct ipq ipq[IPREASS_NHASH];
271 static TAILQ_HEAD(ipq_list, ipq) ipq_list =
272 TAILQ_HEAD_INITIALIZER(ipq_list);
273 const int ipintrq_present = 1;
274 lck_mtx_t *ip_mutex;
275 lck_attr_t *ip_mutex_attr;
276 lck_grp_t *ip_mutex_grp;
277 lck_grp_attr_t *ip_mutex_grp_attr;
278 lck_mtx_t *inet_domain_mutex;
279 extern lck_mtx_t *domain_proto_mtx;
280
281 #if IPCTL_DEFMTU
282 SYSCTL_INT(_net_inet_ip, IPCTL_DEFMTU, mtu, CTLFLAG_RW,
283 &ip_mtu, 0, "Default MTU");
284 #endif
285
286 #if IPSTEALTH
287 static int ipstealth = 0;
288 SYSCTL_INT(_net_inet_ip, OID_AUTO, stealth, CTLFLAG_RW,
289 &ipstealth, 0, "");
290 #endif
291
292
293 /* Firewall hooks */
294 #if IPFIREWALL
295 ip_fw_chk_t *ip_fw_chk_ptr;
296 int fw_enable = 1;
297 int fw_bypass = 1;
298 int fw_one_pass = 0;
299
300 #if DUMMYNET
301 ip_dn_io_t *ip_dn_io_ptr;
302 #endif
303
304 int (*fr_checkp)(struct ip *, int, struct ifnet *, int, struct mbuf **) = NULL;
305 #endif /* IPFIREWALL */
306
307 SYSCTL_NODE(_net_inet_ip, OID_AUTO, linklocal, CTLFLAG_RW|CTLFLAG_LOCKED, 0, "link local");
308
309 struct ip_linklocal_stat ip_linklocal_stat;
310 SYSCTL_STRUCT(_net_inet_ip_linklocal, OID_AUTO, stat, CTLFLAG_RD,
311 &ip_linklocal_stat, ip_linklocal_stat,
312 "Number of link local packets with TTL less than 255");
313
314 SYSCTL_NODE(_net_inet_ip_linklocal, OID_AUTO, in, CTLFLAG_RW|CTLFLAG_LOCKED, 0, "link local input");
315
316 int ip_linklocal_in_allowbadttl = 1;
317 SYSCTL_INT(_net_inet_ip_linklocal_in, OID_AUTO, allowbadttl, CTLFLAG_RW,
318 &ip_linklocal_in_allowbadttl, 0,
319 "Allow incoming link local packets with TTL less than 255");
320
321
322 /*
323 * We need to save the IP options in case a protocol wants to respond
324 * to an incoming packet over the same route if the packet got here
325 * using IP source routing. This allows connection establishment and
326 * maintenance when the remote end is on a network that is not known
327 * to us.
328 */
329 static int ip_nhops = 0;
330 static struct ip_srcrt {
331 struct in_addr dst; /* final destination */
332 char nop; /* one NOP to align */
333 char srcopt[IPOPT_OFFSET + 1]; /* OPTVAL, OLEN and OFFSET */
334 struct in_addr route[MAX_IPOPTLEN/sizeof(struct in_addr)];
335 } ip_srcrt;
336
337 static void in_ifaddrhashtbl_init(void);
338 static void save_rte(u_char *, struct in_addr);
339 static int ip_dooptions(struct mbuf *, int, struct sockaddr_in *);
340 static void ip_forward(struct mbuf *, int, struct sockaddr_in *);
341 static void ip_freef(struct ipq *);
342 #if IPDIVERT
343 #ifdef IPDIVERT_44
344 static struct mbuf *ip_reass(struct mbuf *,
345 struct ipq *, struct ipq *, u_int32_t *, u_int16_t *);
346 #else
347 static struct mbuf *ip_reass(struct mbuf *,
348 struct ipq *, struct ipq *, u_int16_t *, u_int16_t *);
349 #endif
350 #else
351 static struct mbuf *ip_reass(struct mbuf *, struct ipq *, struct ipq *);
352 #endif
353 static void ip_fwd_route_copyout(struct ifnet *, struct route *);
354 static void ip_fwd_route_copyin(struct ifnet *, struct route *);
355 void ipintr(void);
356 void in_dinit(void);
357
358 #if RANDOM_IP_ID
359 extern u_short ip_id;
360
361 int ip_use_randomid = 1;
362 SYSCTL_INT(_net_inet_ip, OID_AUTO, random_id, CTLFLAG_RW,
363 &ip_use_randomid, 0, "Randomize IP packets IDs");
364 #endif
365
366 #define satosin(sa) ((struct sockaddr_in *)(sa))
367 #define ifatoia(ifa) ((struct in_ifaddr *)(ifa))
368
369 /*
370 * IP initialization: fill in IP protocol switch table.
371 * All protocols not implemented in kernel go to raw IP protocol handler.
372 */
373 void
374 ip_init(void)
375 {
376 struct protosw *pr;
377 int i;
378 static int ip_initialized = 0;
379
380 if (!ip_initialized)
381 {
382 in_ifaddr_init();
383
384 in_ifaddr_rwlock_grp_attr = lck_grp_attr_alloc_init();
385 in_ifaddr_rwlock_grp = lck_grp_alloc_init("in_ifaddr_rwlock",
386 in_ifaddr_rwlock_grp_attr);
387 in_ifaddr_rwlock_attr = lck_attr_alloc_init();
388 in_ifaddr_rwlock = lck_rw_alloc_init(in_ifaddr_rwlock_grp,
389 in_ifaddr_rwlock_attr);
390
391 TAILQ_INIT(&in_ifaddrhead);
392 in_ifaddrhashtbl_init();
393
394 pr = pffindproto_locked(PF_INET, IPPROTO_RAW, SOCK_RAW);
395 if (pr == 0)
396 panic("ip_init");
397 for (i = 0; i < IPPROTO_MAX; i++)
398 ip_protox[i] = pr;
399 for (pr = inetdomain.dom_protosw; pr; pr = pr->pr_next) {
400 if (pr->pr_domain == NULL)
401 continue; /* If uninitialized, skip */
402 if (pr->pr_domain->dom_family == PF_INET &&
403 pr->pr_protocol && pr->pr_protocol != IPPROTO_RAW)
404 ip_protox[pr->pr_protocol] = pr;
405 }
406 for (i = 0; i < IPREASS_NHASH; i++)
407 ipq[i].next = ipq[i].prev = &ipq[i];
408
409 maxnipq = nmbclusters / 32;
410 maxfrags = maxnipq * 2;
411 maxfragsperpacket = 128; /* enough for 64k in 512 byte fragments */
412
413 #if RANDOM_IP_ID
414 {
415 struct timeval timenow;
416 getmicrotime(&timenow);
417 ip_id = timenow.tv_sec & 0xffff;
418 }
419 #endif
420 ipintrq.ifq_maxlen = ipqmaxlen;
421
422 ipf_init();
423
424 ip_mutex_grp_attr = lck_grp_attr_alloc_init();
425
426 ip_mutex_grp = lck_grp_alloc_init("ip", ip_mutex_grp_attr);
427
428 ip_mutex_attr = lck_attr_alloc_init();
429
430 if ((ip_mutex = lck_mtx_alloc_init(ip_mutex_grp, ip_mutex_attr)) == NULL) {
431 printf("ip_init: can't alloc ip_mutex\n");
432 return;
433 }
434
435 #if IPSEC
436
437 sadb_stat_mutex_grp_attr = lck_grp_attr_alloc_init();
438 sadb_stat_mutex_grp = lck_grp_alloc_init("sadb_stat", sadb_stat_mutex_grp_attr);
439 sadb_stat_mutex_attr = lck_attr_alloc_init();
440
441 if ((sadb_stat_mutex = lck_mtx_alloc_init(sadb_stat_mutex_grp, sadb_stat_mutex_attr)) == NULL) {
442 printf("ip_init: can't alloc sadb_stat_mutex\n");
443 return;
444 }
445
446 #endif
447 arp_init();
448
449 ip_initialized = 1;
450 }
451 }
452
453 /*
454 * Initialize IPv4 source address hash table.
455 */
456 static void
457 in_ifaddrhashtbl_init(void)
458 {
459 int i, k, p;
460
461 if (in_ifaddrhashtbl != NULL)
462 return;
463
464 PE_parse_boot_argn("inaddr_nhash", &inaddr_nhash, sizeof (inaddr_nhash));
465 if (inaddr_nhash == 0)
466 inaddr_nhash = INADDR_NHASH;
467
468 MALLOC(in_ifaddrhashtbl, struct in_ifaddrhashhead *,
469 inaddr_nhash * sizeof (*in_ifaddrhashtbl),
470 M_IFADDR, M_WAITOK | M_ZERO);
471 if (in_ifaddrhashtbl == NULL)
472 panic("in_ifaddrhashtbl_init allocation failed");
473
474 /*
475 * Generate the next largest prime greater than inaddr_nhash.
476 */
477 k = (inaddr_nhash % 2 == 0) ? inaddr_nhash + 1 : inaddr_nhash + 2;
478 for (;;) {
479 p = 1;
480 for (i = 3; i * i <= k; i += 2) {
481 if (k % i == 0)
482 p = 0;
483 }
484 if (p == 1)
485 break;
486 k += 2;
487 }
488 inaddr_hashp = k;
489 }
490
491 u_int32_t
492 inaddr_hashval(u_int32_t key)
493 {
494 /*
495 * The hash index is the computed prime times the key modulo
496 * the hash size, as documented in "Introduction to Algorithms"
497 * (Cormen, Leiserson, Rivest).
498 */
499 if (inaddr_nhash > 1)
500 return ((key * inaddr_hashp) % inaddr_nhash);
501 else
502 return (0);
503 }
504
505 static void
506 ip_proto_input(
507 protocol_family_t __unused protocol,
508 mbuf_t packet_list)
509 {
510 mbuf_t packet;
511 int how_many = 0 ;
512
513 /* ip_input should handle a list of packets but does not yet */
514
515 for (packet = packet_list; packet; packet = packet_list) {
516 how_many++;
517 packet_list = mbuf_nextpkt(packet);
518 mbuf_setnextpkt(packet, NULL);
519 ip_input(packet);
520 }
521 }
522
523 /* Initialize the PF_INET domain, and add in the pre-defined protos */
524 void
525 in_dinit(void)
526 {
527 int i;
528 struct protosw *pr;
529 struct domain *dp;
530 static int inetdomain_initted = 0;
531
532 if (!inetdomain_initted)
533 {
534 #if 0
535 kprintf("Initing %d protosw entries\n", in_proto_count);
536 #endif
537 dp = &inetdomain;
538 dp->dom_flags = DOM_REENTRANT;
539
540 for (i=0, pr = &inetsw[0]; i<in_proto_count; i++, pr++)
541 net_add_proto(pr, dp);
542 inet_domain_mutex = dp->dom_mtx;
543 inetdomain_initted = 1;
544
545 lck_mtx_unlock(domain_proto_mtx);
546 proto_register_input(PF_INET, ip_proto_input, NULL, 1);
547 lck_mtx_lock(domain_proto_mtx);
548 }
549 }
550
551 __private_extern__ void
552 ip_proto_dispatch_in(
553 struct mbuf *m,
554 int hlen,
555 u_int8_t proto,
556 ipfilter_t inject_ipfref)
557 {
558 struct ipfilter *filter;
559 int seen = (inject_ipfref == 0);
560 int changed_header = 0;
561 struct ip *ip;
562
563 if (!TAILQ_EMPTY(&ipv4_filters)) {
564 ipf_ref();
565 TAILQ_FOREACH(filter, &ipv4_filters, ipf_link) {
566 if (seen == 0) {
567 if ((struct ipfilter *)inject_ipfref == filter)
568 seen = 1;
569 } else if (filter->ipf_filter.ipf_input) {
570 errno_t result;
571
572 if (changed_header == 0) {
573 changed_header = 1;
574 ip = mtod(m, struct ip *);
575 ip->ip_len = htons(ip->ip_len + hlen);
576 ip->ip_off = htons(ip->ip_off);
577 ip->ip_sum = 0;
578 ip->ip_sum = in_cksum(m, hlen);
579 }
580 result = filter->ipf_filter.ipf_input(
581 filter->ipf_filter.cookie, (mbuf_t*)&m, hlen, proto);
582 if (result == EJUSTRETURN) {
583 ipf_unref();
584 return;
585 }
586 if (result != 0) {
587 ipf_unref();
588 m_freem(m);
589 return;
590 }
591 }
592 }
593 ipf_unref();
594 }
595 /*
596 * If there isn't a specific lock for the protocol
597 * we're about to call, use the generic lock for AF_INET.
598 * otherwise let the protocol deal with its own locking
599 */
600 ip = mtod(m, struct ip *);
601
602 if (changed_header) {
603 ip->ip_len = ntohs(ip->ip_len) - hlen;
604 ip->ip_off = ntohs(ip->ip_off);
605 }
606
607 if (!(ip_protox[ip->ip_p]->pr_flags & PR_PROTOLOCK)) {
608 lck_mtx_lock(inet_domain_mutex);
609 (*ip_protox[ip->ip_p]->pr_input)(m, hlen);
610 lck_mtx_unlock(inet_domain_mutex);
611 }
612 else
613 (*ip_protox[ip->ip_p]->pr_input)(m, hlen);
614
615 }
616
617 /*
618 * Ip input routine. Checksum and byte swap header. If fragmented
619 * try to reassemble. Process options. Pass to next level.
620 */
621 void
622 ip_input(struct mbuf *m)
623 {
624 struct ip *ip;
625 struct ipq *fp;
626 struct in_ifaddr *ia = NULL;
627 int i, hlen, checkif;
628 u_short sum;
629 struct in_addr pkt_dst;
630 u_int32_t div_info = 0; /* packet divert/tee info */
631 #if IPFIREWALL
632 struct ip_fw_args args;
633 #endif
634 ipfilter_t inject_filter_ref = 0;
635 struct m_tag *tag;
636
637 #if IPFIREWALL
638 args.eh = NULL;
639 args.oif = NULL;
640 args.rule = NULL;
641 args.divert_rule = 0; /* divert cookie */
642 args.next_hop = NULL;
643
644 /*
645 * Don't bother searching for tag(s) if there's none.
646 */
647 if (SLIST_EMPTY(&m->m_pkthdr.tags))
648 goto ipfw_tags_done;
649
650 /* Grab info from mtags prepended to the chain */
651 #if DUMMYNET
652 if ((tag = m_tag_locate(m, KERNEL_MODULE_TAG_ID,
653 KERNEL_TAG_TYPE_DUMMYNET, NULL)) != NULL) {
654 struct dn_pkt_tag *dn_tag;
655
656 dn_tag = (struct dn_pkt_tag *)(tag+1);
657 args.rule = dn_tag->rule;
658
659 m_tag_delete(m, tag);
660 }
661 #endif /* DUMMYNET */
662
663 #if IPDIVERT
664 if ((tag = m_tag_locate(m, KERNEL_MODULE_TAG_ID,
665 KERNEL_TAG_TYPE_DIVERT, NULL)) != NULL) {
666 struct divert_tag *div_tag;
667
668 div_tag = (struct divert_tag *)(tag+1);
669 args.divert_rule = div_tag->cookie;
670
671 m_tag_delete(m, tag);
672 }
673 #endif
674
675 if ((tag = m_tag_locate(m, KERNEL_MODULE_TAG_ID,
676 KERNEL_TAG_TYPE_IPFORWARD, NULL)) != NULL) {
677 struct ip_fwd_tag *ipfwd_tag;
678
679 ipfwd_tag = (struct ip_fwd_tag *)(tag+1);
680 args.next_hop = ipfwd_tag->next_hop;
681
682 m_tag_delete(m, tag);
683 }
684
685 #if DIAGNOSTIC
686 if (m == NULL || (m->m_flags & M_PKTHDR) == 0)
687 panic("ip_input no HDR");
688 #endif
689
690 if (args.rule) { /* dummynet already filtered us */
691 ip = mtod(m, struct ip *);
692 hlen = IP_VHL_HL(ip->ip_vhl) << 2;
693 inject_filter_ref = ipf_get_inject_filter(m);
694 goto iphack ;
695 }
696 ipfw_tags_done:
697 #endif /* IPFIREWALL */
698
699 /*
700 * No need to proccess packet twice if we've already seen it.
701 */
702 if (!SLIST_EMPTY(&m->m_pkthdr.tags))
703 inject_filter_ref = ipf_get_inject_filter(m);
704 if (inject_filter_ref != 0) {
705 ip = mtod(m, struct ip *);
706 hlen = IP_VHL_HL(ip->ip_vhl) << 2;
707 ip->ip_len = ntohs(ip->ip_len) - hlen;
708 ip->ip_off = ntohs(ip->ip_off);
709 ip_proto_dispatch_in(m, hlen, ip->ip_p, inject_filter_ref);
710 return;
711 }
712
713 OSAddAtomic(1, &ipstat.ips_total);
714
715 if (m->m_pkthdr.len < sizeof(struct ip))
716 goto tooshort;
717
718 if (m->m_len < sizeof (struct ip) &&
719 (m = m_pullup(m, sizeof (struct ip))) == 0) {
720 OSAddAtomic(1, &ipstat.ips_toosmall);
721 return;
722 }
723 ip = mtod(m, struct ip *);
724
725 KERNEL_DEBUG(DBG_LAYER_BEG, ip->ip_dst.s_addr,
726 ip->ip_src.s_addr, ip->ip_p, ip->ip_off, ip->ip_len);
727
728 if (IP_VHL_V(ip->ip_vhl) != IPVERSION) {
729 OSAddAtomic(1, &ipstat.ips_badvers);
730 goto bad;
731 }
732
733 hlen = IP_VHL_HL(ip->ip_vhl) << 2;
734 if (hlen < sizeof(struct ip)) { /* minimum header length */
735 OSAddAtomic(1, &ipstat.ips_badhlen);
736 goto bad;
737 }
738 if (hlen > m->m_len) {
739 if ((m = m_pullup(m, hlen)) == 0) {
740 OSAddAtomic(1, &ipstat.ips_badhlen);
741 return;
742 }
743 ip = mtod(m, struct ip *);
744 }
745
746 /* 127/8 must not appear on wire - RFC1122 */
747 if ((ntohl(ip->ip_dst.s_addr) >> IN_CLASSA_NSHIFT) == IN_LOOPBACKNET ||
748 (ntohl(ip->ip_src.s_addr) >> IN_CLASSA_NSHIFT) == IN_LOOPBACKNET) {
749 if ((m->m_pkthdr.rcvif->if_flags & IFF_LOOPBACK) == 0) {
750 OSAddAtomic(1, &ipstat.ips_badaddr);
751 goto bad;
752 }
753 }
754
755 /* IPv4 Link-Local Addresses as defined in <draft-ietf-zeroconf-ipv4-linklocal-05.txt> */
756 if ((IN_LINKLOCAL(ntohl(ip->ip_dst.s_addr)) ||
757 IN_LINKLOCAL(ntohl(ip->ip_src.s_addr)))) {
758 ip_linklocal_stat.iplls_in_total++;
759 if (ip->ip_ttl != MAXTTL) {
760 OSAddAtomic(1, &ip_linklocal_stat.iplls_in_badttl);
761 /* Silently drop link local traffic with bad TTL */
762 if (!ip_linklocal_in_allowbadttl)
763 goto bad;
764 }
765 }
766 if ((IF_HWASSIST_CSUM_FLAGS(m->m_pkthdr.rcvif->if_hwassist) == 0)
767 || (apple_hwcksum_rx == 0) ||
768 ((m->m_pkthdr.csum_flags & CSUM_TCP_SUM16) && ip->ip_p != IPPROTO_TCP)) {
769 m->m_pkthdr.csum_flags = 0; /* invalidate HW generated checksum flags */
770 }
771
772 if (m->m_pkthdr.csum_flags & CSUM_IP_CHECKED) {
773 sum = !(m->m_pkthdr.csum_flags & CSUM_IP_VALID);
774 } else if (!(m->m_pkthdr.rcvif->if_flags & IFF_LOOPBACK) ||
775 apple_hwcksum_tx == 0) {
776 /*
777 * Either this is not loopback packet coming from an interface
778 * that does not support checksum offloading, or it is loopback
779 * packet that has undergone software checksumming at the send
780 * side because apple_hwcksum_tx was set to 0. In this case,
781 * calculate the checksum in software to validate the packet.
782 */
783 sum = in_cksum(m, hlen);
784 } else {
785 /*
786 * This is a loopback packet without any valid checksum since
787 * the send side has bypassed it (apple_hwcksum_tx set to 1).
788 * We get here because apple_hwcksum_rx was set to 0, and so
789 * we pretend that all is well.
790 */
791 sum = 0;
792 m->m_pkthdr.csum_flags |= CSUM_DATA_VALID | CSUM_PSEUDO_HDR |
793 CSUM_IP_CHECKED | CSUM_IP_VALID;
794 m->m_pkthdr.csum_data = 0xffff;
795 }
796 if (sum) {
797 OSAddAtomic(1, &ipstat.ips_badsum);
798 goto bad;
799 }
800
801 /*
802 * Convert fields to host representation.
803 */
804 #if BYTE_ORDER != BIG_ENDIAN
805 NTOHS(ip->ip_len);
806 #endif
807
808 if (ip->ip_len < hlen) {
809 OSAddAtomic(1, &ipstat.ips_badlen);
810 goto bad;
811 }
812
813 #if BYTE_ORDER != BIG_ENDIAN
814 NTOHS(ip->ip_off);
815 #endif
816 /*
817 * Check that the amount of data in the buffers
818 * is as at least much as the IP header would have us expect.
819 * Trim mbufs if longer than we expect.
820 * Drop packet if shorter than we expect.
821 */
822 if (m->m_pkthdr.len < ip->ip_len) {
823 tooshort:
824 OSAddAtomic(1, &ipstat.ips_tooshort);
825 goto bad;
826 }
827 if (m->m_pkthdr.len > ip->ip_len) {
828 /* Invalidate hwcksuming */
829 m->m_pkthdr.csum_flags = 0;
830 m->m_pkthdr.csum_data = 0;
831
832 if (m->m_len == m->m_pkthdr.len) {
833 m->m_len = ip->ip_len;
834 m->m_pkthdr.len = ip->ip_len;
835 } else
836 m_adj(m, ip->ip_len - m->m_pkthdr.len);
837 }
838
839 #if IPSEC
840 if (ipsec_bypass == 0 && ipsec_gethist(m, NULL))
841 goto pass;
842 #endif
843
844 /*
845 * IpHack's section.
846 * Right now when no processing on packet has done
847 * and it is still fresh out of network we do our black
848 * deals with it.
849 * - Firewall: deny/allow/divert
850 * - Xlate: translate packet's addr/port (NAT).
851 * - Pipe: pass pkt through dummynet.
852 * - Wrap: fake packet's addr/port <unimpl.>
853 * - Encapsulate: put it in another IP and send out. <unimp.>
854 */
855 #if PF
856 /* Invoke inbound packet filter */
857 if (pf_af_hook(m->m_pkthdr.rcvif, NULL, &m, AF_INET, TRUE) != 0) {
858 if (m != NULL) {
859 panic("%s: unexpected packet %p\n", __func__, m);
860 /* NOTREACHED */
861 }
862 /* Already freed by callee */
863 return;
864 }
865 ip = mtod(m, struct ip *);
866 hlen = IP_VHL_HL(ip->ip_vhl) << 2;
867 #endif /* PF */
868
869 #if IPFIREWALL
870 #if DUMMYNET
871 iphack:
872 #endif /* DUMMYNET */
873 /*
874 * Check if we want to allow this packet to be processed.
875 * Consider it to be bad if not.
876 */
877 if (fr_checkp) {
878 struct mbuf *m1 = m;
879
880 if (fr_checkp(ip, hlen, m->m_pkthdr.rcvif, 0, &m1) || !m1) {
881 return;
882 }
883 ip = mtod(m = m1, struct ip *);
884 }
885 if (fw_enable && IPFW_LOADED) {
886 #if IPFIREWALL_FORWARD
887 /*
888 * If we've been forwarded from the output side, then
889 * skip the firewall a second time
890 */
891 if (args.next_hop)
892 goto ours;
893 #endif /* IPFIREWALL_FORWARD */
894
895 args.m = m;
896
897 i = ip_fw_chk_ptr(&args);
898 m = args.m;
899
900 if ( (i & IP_FW_PORT_DENY_FLAG) || m == NULL) { /* drop */
901 if (m)
902 m_freem(m);
903 return;
904 }
905 ip = mtod(m, struct ip *); /* just in case m changed */
906
907 if (i == 0 && args.next_hop == NULL) { /* common case */
908 goto pass;
909 }
910 #if DUMMYNET
911 if (DUMMYNET_LOADED && (i & IP_FW_PORT_DYNT_FLAG) != 0) {
912 /* Send packet to the appropriate pipe */
913 ip_dn_io_ptr(m, i&0xffff, DN_TO_IP_IN, &args);
914 return;
915 }
916 #endif /* DUMMYNET */
917 #if IPDIVERT
918 if (i != 0 && (i & IP_FW_PORT_DYNT_FLAG) == 0) {
919 /* Divert or tee packet */
920 div_info = i;
921 goto ours;
922 }
923 #endif
924 #if IPFIREWALL_FORWARD
925 if (i == 0 && args.next_hop != NULL) {
926 goto pass;
927 }
928 #endif
929 /*
930 * if we get here, the packet must be dropped
931 */
932 m_freem(m);
933 return;
934 }
935 #endif /* IPFIREWALL */
936 pass:
937
938 /*
939 * Process options and, if not destined for us,
940 * ship it on. ip_dooptions returns 1 when an
941 * error was detected (causing an icmp message
942 * to be sent and the original packet to be freed).
943 */
944 ip_nhops = 0; /* for source routed packets */
945 #if IPFIREWALL
946 if (hlen > sizeof (struct ip) && ip_dooptions(m, 0, args.next_hop)) {
947 #else
948 if (hlen > sizeof (struct ip) && ip_dooptions(m, 0, NULL)) {
949 #endif
950 return;
951 }
952
953 /* greedy RSVP, snatches any PATH packet of the RSVP protocol and no
954 * matter if it is destined to another node, or whether it is
955 * a multicast one, RSVP wants it! and prevents it from being forwarded
956 * anywhere else. Also checks if the rsvp daemon is running before
957 * grabbing the packet.
958 */
959 if (rsvp_on && ip->ip_p==IPPROTO_RSVP)
960 goto ours;
961
962 /*
963 * Check our list of addresses, to see if the packet is for us.
964 * If we don't have any addresses, assume any unicast packet
965 * we receive might be for us (and let the upper layers deal
966 * with it).
967 */
968 if (TAILQ_EMPTY(&in_ifaddrhead) &&
969 (m->m_flags & (M_MCAST|M_BCAST)) == 0)
970 goto ours;
971
972 /*
973 * Cache the destination address of the packet; this may be
974 * changed by use of 'ipfw fwd'.
975 */
976 #if IPFIREWALL
977 pkt_dst = args.next_hop == NULL ?
978 ip->ip_dst : args.next_hop->sin_addr;
979 #else
980 pkt_dst = ip->ip_dst;
981 #endif
982
983 /*
984 * Enable a consistency check between the destination address
985 * and the arrival interface for a unicast packet (the RFC 1122
986 * strong ES model) if IP forwarding is disabled and the packet
987 * is not locally generated and the packet is not subject to
988 * 'ipfw fwd'.
989 *
990 * XXX - Checking also should be disabled if the destination
991 * address is ipnat'ed to a different interface.
992 *
993 * XXX - Checking is incompatible with IP aliases added
994 * to the loopback interface instead of the interface where
995 * the packets are received.
996 */
997 checkif = ip_checkinterface && (ipforwarding == 0) &&
998 ((m->m_pkthdr.rcvif->if_flags & IFF_LOOPBACK) == 0)
999 #if IPFIREWALL
1000 && (args.next_hop == NULL);
1001 #else
1002 ;
1003 #endif
1004
1005 /*
1006 * Check for exact addresses in the hash bucket.
1007 */
1008 lck_rw_lock_shared(in_ifaddr_rwlock);
1009 TAILQ_FOREACH(ia, INADDR_HASH(pkt_dst.s_addr), ia_hash) {
1010 /*
1011 * If the address matches, verify that the packet
1012 * arrived via the correct interface if checking is
1013 * enabled.
1014 */
1015 if (IA_SIN(ia)->sin_addr.s_addr == pkt_dst.s_addr &&
1016 (!checkif || ia->ia_ifp == m->m_pkthdr.rcvif)) {
1017 lck_rw_done(in_ifaddr_rwlock);
1018 goto ours;
1019 }
1020 }
1021 lck_rw_done(in_ifaddr_rwlock);
1022
1023 /*
1024 * Check for broadcast addresses.
1025 *
1026 * Only accept broadcast packets that arrive via the matching
1027 * interface. Reception of forwarded directed broadcasts would be
1028 * handled via ip_forward() and ether_frameout() with the loopback
1029 * into the stack for SIMPLEX interfaces handled by ether_frameout().
1030 */
1031 if (m->m_pkthdr.rcvif->if_flags & IFF_BROADCAST) {
1032 struct ifaddr *ifa;
1033 struct ifnet *ifp = m->m_pkthdr.rcvif;
1034
1035 ifnet_lock_shared(ifp);
1036 TAILQ_FOREACH(ifa, &ifp->if_addrhead, ifa_link) {
1037 if (ifa->ifa_addr->sa_family != AF_INET)
1038 continue;
1039 ia = ifatoia(ifa);
1040 if (satosin(&ia->ia_broadaddr)->sin_addr.s_addr ==
1041 pkt_dst.s_addr || ia->ia_netbroadcast.s_addr ==
1042 pkt_dst.s_addr) {
1043 ifnet_lock_done(ifp);
1044 goto ours;
1045 }
1046 }
1047 ifnet_lock_done(ifp);
1048 }
1049
1050 if (IN_MULTICAST(ntohl(ip->ip_dst.s_addr))) {
1051 struct in_multi *inm;
1052 struct ifnet *ifp = m->m_pkthdr.rcvif;
1053 #if MROUTING
1054 if (ip_mrouter) {
1055 /*
1056 * If we are acting as a multicast router, all
1057 * incoming multicast packets are passed to the
1058 * kernel-level multicast forwarding function.
1059 * The packet is returned (relatively) intact; if
1060 * ip_mforward() returns a non-zero value, the packet
1061 * must be discarded, else it may be accepted below.
1062 */
1063 lck_mtx_lock(ip_mutex);
1064 if (ip_mforward && ip_mforward(ip, ifp, m, 0) != 0) {
1065 OSAddAtomic(1, &ipstat.ips_cantforward);
1066 m_freem(m);
1067 lck_mtx_unlock(ip_mutex);
1068 return;
1069 }
1070
1071 /*
1072 * The process-level routing daemon needs to receive
1073 * all multicast IGMP packets, whether or not this
1074 * host belongs to their destination groups.
1075 */
1076 if (ip->ip_p == IPPROTO_IGMP)
1077 goto ours;
1078 OSAddAtomic(1, &ipstat.ips_forward);
1079 }
1080 #endif /* MROUTING */
1081 /*
1082 * See if we belong to the destination multicast group on the
1083 * arrival interface.
1084 */
1085 ifnet_lock_shared(ifp);
1086 IN_LOOKUP_MULTI(ip->ip_dst, ifp, inm);
1087 ifnet_lock_done(ifp);
1088 if (inm == NULL) {
1089 OSAddAtomic(1, &ipstat.ips_notmember);
1090 m_freem(m);
1091 return;
1092 }
1093 goto ours;
1094 }
1095 if (ip->ip_dst.s_addr == (u_int32_t)INADDR_BROADCAST)
1096 goto ours;
1097 if (ip->ip_dst.s_addr == INADDR_ANY)
1098 goto ours;
1099
1100 /* Allow DHCP/BootP responses through */
1101 if (m->m_pkthdr.rcvif != NULL
1102 && (m->m_pkthdr.rcvif->if_eflags & IFEF_AUTOCONFIGURING)
1103 && hlen == sizeof(struct ip)
1104 && ip->ip_p == IPPROTO_UDP) {
1105 struct udpiphdr *ui;
1106 if (m->m_len < sizeof(struct udpiphdr)
1107 && (m = m_pullup(m, sizeof(struct udpiphdr))) == 0) {
1108 OSAddAtomic(1, &udpstat.udps_hdrops);
1109 return;
1110 }
1111 ui = mtod(m, struct udpiphdr *);
1112 if (ntohs(ui->ui_dport) == IPPORT_BOOTPC) {
1113 goto ours;
1114 }
1115 ip = mtod(m, struct ip *); /* in case it changed */
1116 }
1117
1118 #if defined(NFAITH) && 0 < NFAITH
1119 /*
1120 * FAITH(Firewall Aided Internet Translator)
1121 */
1122 if (m->m_pkthdr.rcvif && m->m_pkthdr.rcvif->if_type == IFT_FAITH) {
1123 if (ip_keepfaith) {
1124 if (ip->ip_p == IPPROTO_TCP || ip->ip_p == IPPROTO_ICMP)
1125 goto ours;
1126 }
1127 m_freem(m);
1128 return;
1129 }
1130 #endif
1131 /*
1132 * Not for us; forward if possible and desirable.
1133 */
1134 if (ipforwarding == 0) {
1135 OSAddAtomic(1, &ipstat.ips_cantforward);
1136 m_freem(m);
1137 } else {
1138 #if IPFIREWALL
1139 ip_forward(m, 0, args.next_hop);
1140 #else
1141 ip_forward(m, 0, NULL);
1142 #endif
1143 }
1144 return;
1145
1146 ours:
1147 /*
1148 * If offset or IP_MF are set, must reassemble.
1149 * Otherwise, nothing need be done.
1150 * (We could look in the reassembly queue to see
1151 * if the packet was previously fragmented,
1152 * but it's not worth the time; just let them time out.)
1153 */
1154 if (ip->ip_off & (IP_MF | IP_OFFMASK | IP_RF)) {
1155
1156 /* If maxnipq is 0, never accept fragments. */
1157 if (maxnipq == 0) {
1158
1159 OSAddAtomic(1, &ipstat.ips_fragments);
1160 OSAddAtomic(1, &ipstat.ips_fragdropped);
1161 goto bad;
1162 }
1163
1164 /*
1165 * If we will exceed the number of fragments in queues, timeout the
1166 * oldest fragemented packet to make space.
1167 */
1168 lck_mtx_lock(ip_mutex);
1169 if (currentfrags >= maxfrags) {
1170 fp = TAILQ_LAST(&ipq_list, ipq_list);
1171 OSAddAtomic(fp->ipq_nfrags, &ipstat.ips_fragtimeout);
1172
1173 if (ip->ip_id == fp->ipq_id &&
1174 ip->ip_src.s_addr == fp->ipq_src.s_addr &&
1175 ip->ip_dst.s_addr == fp->ipq_dst.s_addr &&
1176 ip->ip_p == fp->ipq_p) {
1177 /*
1178 * If we match the fragment queue we were going to
1179 * discard, drop this packet too.
1180 */
1181 OSAddAtomic(1, &ipstat.ips_fragdropped);
1182 ip_freef(fp);
1183 lck_mtx_unlock(ip_mutex);
1184 goto bad;
1185 }
1186
1187 ip_freef(fp);
1188 }
1189
1190 sum = IPREASS_HASH(ip->ip_src.s_addr, ip->ip_id);
1191 /*
1192 * Look for queue of fragments
1193 * of this datagram.
1194 */
1195 for (fp = ipq[sum].next; fp != &ipq[sum]; fp = fp->next)
1196 if (ip->ip_id == fp->ipq_id &&
1197 ip->ip_src.s_addr == fp->ipq_src.s_addr &&
1198 ip->ip_dst.s_addr == fp->ipq_dst.s_addr &&
1199 #if CONFIG_MACF_NET
1200 mac_ipq_label_compare(m, fp) &&
1201 #endif
1202 ip->ip_p == fp->ipq_p)
1203 goto found;
1204
1205 /*
1206 * Enforce upper bound on number of fragmented packets
1207 * for which we attempt reassembly;
1208 * If maxnipq is -1, accept all fragments without limitation.
1209 */
1210 if ((nipq > maxnipq) && (maxnipq > 0)) {
1211 /*
1212 * drop the oldest fragment before proceeding further
1213 */
1214 fp = TAILQ_LAST(&ipq_list, ipq_list);
1215 OSAddAtomic(fp->ipq_nfrags, &ipstat.ips_fragtimeout);
1216 ip_freef(fp);
1217 }
1218
1219 fp = NULL;
1220
1221 found:
1222 /*
1223 * Adjust ip_len to not reflect header,
1224 * convert offset of this to bytes.
1225 */
1226 ip->ip_len -= hlen;
1227 if (ip->ip_off & IP_MF) {
1228 /*
1229 * Make sure that fragments have a data length
1230 * that's a non-zero multiple of 8 bytes.
1231 */
1232 if (ip->ip_len == 0 || (ip->ip_len & 0x7) != 0) {
1233 OSAddAtomic(1, &ipstat.ips_toosmall);
1234 lck_mtx_unlock(ip_mutex);
1235 goto bad;
1236 }
1237 m->m_flags |= M_FRAG;
1238 } else {
1239 /* Clear the flag in case packet comes from loopback */
1240 m->m_flags &= ~M_FRAG;
1241 }
1242 ip->ip_off <<= 3;
1243
1244 /*
1245 * Attempt reassembly; if it succeeds, proceed.
1246 * ip_reass() will return a different mbuf, and update
1247 * the divert info in div_info and args.divert_rule.
1248 */
1249 OSAddAtomic(1, &ipstat.ips_fragments);
1250 m->m_pkthdr.header = ip;
1251 #if IPDIVERT
1252 m = ip_reass(m, fp, &ipq[sum],
1253 (u_int16_t *)&div_info, &args.divert_rule);
1254 #else
1255 m = ip_reass(m, fp, &ipq[sum]);
1256 #endif
1257 if (m == 0) {
1258 lck_mtx_unlock(ip_mutex);
1259 return;
1260 }
1261 OSAddAtomic(1, &ipstat.ips_reassembled);
1262 ip = mtod(m, struct ip *);
1263 /* Get the header length of the reassembled packet */
1264 hlen = IP_VHL_HL(ip->ip_vhl) << 2;
1265
1266 #if IPDIVERT
1267 /* Restore original checksum before diverting packet */
1268 if (div_info != 0) {
1269 ip->ip_len += hlen;
1270
1271 #if BYTE_ORDER != BIG_ENDIAN
1272 HTONS(ip->ip_len);
1273 HTONS(ip->ip_off);
1274 #endif
1275
1276 ip->ip_sum = 0;
1277 ip->ip_sum = in_cksum(m, hlen);
1278
1279 #if BYTE_ORDER != BIG_ENDIAN
1280 NTOHS(ip->ip_off);
1281 NTOHS(ip->ip_len);
1282 #endif
1283
1284 ip->ip_len -= hlen;
1285 }
1286 #endif
1287 lck_mtx_unlock(ip_mutex);
1288 } else
1289 ip->ip_len -= hlen;
1290
1291 #if IPDIVERT
1292 /*
1293 * Divert or tee packet to the divert protocol if required.
1294 *
1295 * If div_info is zero then cookie should be too, so we shouldn't
1296 * need to clear them here. Assume divert_packet() does so also.
1297 */
1298 if (div_info != 0) {
1299 struct mbuf *clone = NULL;
1300
1301 /* Clone packet if we're doing a 'tee' */
1302 if ((div_info & IP_FW_PORT_TEE_FLAG) != 0)
1303 clone = m_dup(m, M_DONTWAIT);
1304
1305 /* Restore packet header fields to original values */
1306 ip->ip_len += hlen;
1307
1308 #if BYTE_ORDER != BIG_ENDIAN
1309 HTONS(ip->ip_len);
1310 HTONS(ip->ip_off);
1311 #endif
1312 /* Deliver packet to divert input routine */
1313 OSAddAtomic(1, &ipstat.ips_delivered);
1314 divert_packet(m, 1, div_info & 0xffff, args.divert_rule);
1315
1316 /* If 'tee', continue with original packet */
1317 if (clone == NULL) {
1318 return;
1319 }
1320 m = clone;
1321 ip = mtod(m, struct ip *);
1322 }
1323 #endif
1324
1325 #if IPSEC
1326 /*
1327 * enforce IPsec policy checking if we are seeing last header.
1328 * note that we do not visit this with protocols with pcb layer
1329 * code - like udp/tcp/raw ip.
1330 */
1331 if (ipsec_bypass == 0 && (ip_protox[ip->ip_p]->pr_flags & PR_LASTHDR) != 0) {
1332 if (ipsec4_in_reject(m, NULL)) {
1333 IPSEC_STAT_INCREMENT(ipsecstat.in_polvio);
1334 goto bad;
1335 }
1336 }
1337 #endif
1338
1339 /*
1340 * Switch out to protocol's input routine.
1341 */
1342 OSAddAtomic(1, &ipstat.ips_delivered);
1343 {
1344 #if IPFIREWALL
1345 if (args.next_hop && ip->ip_p == IPPROTO_TCP) {
1346 /* TCP needs IPFORWARD info if available */
1347 struct m_tag *fwd_tag;
1348 struct ip_fwd_tag *ipfwd_tag;
1349
1350 fwd_tag = m_tag_alloc(KERNEL_MODULE_TAG_ID,
1351 KERNEL_TAG_TYPE_IPFORWARD, sizeof (*ipfwd_tag),
1352 M_NOWAIT);
1353 if (fwd_tag == NULL) {
1354 goto bad;
1355 }
1356
1357 ipfwd_tag = (struct ip_fwd_tag *)(fwd_tag+1);
1358 ipfwd_tag->next_hop = args.next_hop;
1359
1360 m_tag_prepend(m, fwd_tag);
1361
1362 KERNEL_DEBUG(DBG_LAYER_END, ip->ip_dst.s_addr,
1363 ip->ip_src.s_addr, ip->ip_p, ip->ip_off, ip->ip_len);
1364
1365
1366 /* TCP deals with its own locking */
1367 ip_proto_dispatch_in(m, hlen, ip->ip_p, 0);
1368 } else {
1369 KERNEL_DEBUG(DBG_LAYER_END, ip->ip_dst.s_addr,
1370 ip->ip_src.s_addr, ip->ip_p, ip->ip_off, ip->ip_len);
1371
1372 ip_proto_dispatch_in(m, hlen, ip->ip_p, 0);
1373 }
1374 #else
1375 ip_proto_dispatch_in(m, hlen, ip->ip_p, 0);
1376 #endif
1377
1378 return;
1379 }
1380 bad:
1381 KERNEL_DEBUG(DBG_LAYER_END, 0,0,0,0,0);
1382 m_freem(m);
1383 }
1384
1385 /*
1386 * Take incoming datagram fragment and try to reassemble it into
1387 * whole datagram. If a chain for reassembly of this datagram already
1388 * exists, then it is given as fp; otherwise have to make a chain.
1389 *
1390 * When IPDIVERT enabled, keep additional state with each packet that
1391 * tells us if we need to divert or tee the packet we're building.
1392 */
1393
1394 static struct mbuf *
1395 #if IPDIVERT
1396 ip_reass(struct mbuf *m, struct ipq *fp, struct ipq *where,
1397 #ifdef IPDIVERT_44
1398 u_int32_t *divinfo,
1399 #else /* IPDIVERT_44 */
1400 u_int16_t *divinfo,
1401 #endif /* IPDIVERT_44 */
1402 u_int16_t *divcookie)
1403 #else /* IPDIVERT */
1404 ip_reass(struct mbuf *m, struct ipq *fp, struct ipq *where)
1405 #endif /* IPDIVERT */
1406 {
1407 struct ip *ip = mtod(m, struct ip *);
1408 struct mbuf *p = 0, *q, *nq;
1409 struct mbuf *t;
1410 int hlen = IP_VHL_HL(ip->ip_vhl) << 2;
1411 int i, next;
1412 u_int8_t ecn, ecn0;
1413
1414 lck_mtx_assert(ip_mutex, LCK_MTX_ASSERT_OWNED);
1415 /*
1416 * Presence of header sizes in mbufs
1417 * would confuse code below.
1418 */
1419 m->m_data += hlen;
1420 m->m_len -= hlen;
1421
1422 if (m->m_pkthdr.csum_flags & CSUM_TCP_SUM16)
1423 m->m_pkthdr.csum_flags = 0;
1424 /*
1425 * If first fragment to arrive, create a reassembly queue.
1426 */
1427 if (fp == 0) {
1428 if ((t = m_get(M_DONTWAIT, MT_FTABLE)) == NULL)
1429 goto dropfrag;
1430 fp = mtod(t, struct ipq *);
1431 #if CONFIG_MACF_NET
1432 if (mac_ipq_label_init(fp, M_NOWAIT) != 0) {
1433 m_free(t);
1434 fp = NULL;
1435 goto dropfrag;
1436 }
1437 mac_ipq_label_associate(m, fp);
1438 #endif
1439 insque((void*)fp, (void*)where);
1440 nipq++;
1441 fp->ipq_nfrags = 1;
1442 fp->ipq_ttl = IPFRAGTTL;
1443 fp->ipq_p = ip->ip_p;
1444 fp->ipq_id = ip->ip_id;
1445 fp->ipq_src = ip->ip_src;
1446 fp->ipq_dst = ip->ip_dst;
1447 fp->ipq_frags = m;
1448 m->m_nextpkt = NULL;
1449 #if IPDIVERT
1450 #ifdef IPDIVERT_44
1451 fp->ipq_div_info = 0;
1452 #else
1453 fp->ipq_divert = 0;
1454 #endif
1455 fp->ipq_div_cookie = 0;
1456 #endif
1457 TAILQ_INSERT_HEAD(&ipq_list, fp, ipq_list);
1458 goto inserted;
1459 } else {
1460 fp->ipq_nfrags++;
1461 #if CONFIG_MACF_NET
1462 mac_ipq_label_update(m, fp);
1463 #endif
1464 }
1465
1466 #define GETIP(m) ((struct ip*)((m)->m_pkthdr.header))
1467
1468 /*
1469 * Handle ECN by comparing this segment with the first one;
1470 * if CE is set, do not lose CE.
1471 * drop if CE and not-ECT are mixed for the same packet.
1472 */
1473 ecn = ip->ip_tos & IPTOS_ECN_MASK;
1474 ecn0 = GETIP(fp->ipq_frags)->ip_tos & IPTOS_ECN_MASK;
1475 if (ecn == IPTOS_ECN_CE) {
1476 if (ecn0 == IPTOS_ECN_NOTECT)
1477 goto dropfrag;
1478 if (ecn0 != IPTOS_ECN_CE)
1479 GETIP(fp->ipq_frags)->ip_tos |= IPTOS_ECN_CE;
1480 }
1481 if (ecn == IPTOS_ECN_NOTECT && ecn0 != IPTOS_ECN_NOTECT)
1482 goto dropfrag;
1483
1484 /*
1485 * Find a segment which begins after this one does.
1486 */
1487 for (p = NULL, q = fp->ipq_frags; q; p = q, q = q->m_nextpkt)
1488 if (GETIP(q)->ip_off > ip->ip_off)
1489 break;
1490
1491 /*
1492 * If there is a preceding segment, it may provide some of
1493 * our data already. If so, drop the data from the incoming
1494 * segment. If it provides all of our data, drop us, otherwise
1495 * stick new segment in the proper place.
1496 *
1497 * If some of the data is dropped from the the preceding
1498 * segment, then it's checksum is invalidated.
1499 */
1500 if (p) {
1501 i = GETIP(p)->ip_off + GETIP(p)->ip_len - ip->ip_off;
1502 if (i > 0) {
1503 if (i >= ip->ip_len)
1504 goto dropfrag;
1505 m_adj(m, i);
1506 m->m_pkthdr.csum_flags = 0;
1507 ip->ip_off += i;
1508 ip->ip_len -= i;
1509 }
1510 m->m_nextpkt = p->m_nextpkt;
1511 p->m_nextpkt = m;
1512 } else {
1513 m->m_nextpkt = fp->ipq_frags;
1514 fp->ipq_frags = m;
1515 }
1516
1517 /*
1518 * While we overlap succeeding segments trim them or,
1519 * if they are completely covered, dequeue them.
1520 */
1521 for (; q != NULL && ip->ip_off + ip->ip_len > GETIP(q)->ip_off;
1522 q = nq) {
1523 i = (ip->ip_off + ip->ip_len) -
1524 GETIP(q)->ip_off;
1525 if (i < GETIP(q)->ip_len) {
1526 GETIP(q)->ip_len -= i;
1527 GETIP(q)->ip_off += i;
1528 m_adj(q, i);
1529 q->m_pkthdr.csum_flags = 0;
1530 break;
1531 }
1532 nq = q->m_nextpkt;
1533 m->m_nextpkt = nq;
1534 OSAddAtomic(1, &ipstat.ips_fragdropped);
1535 fp->ipq_nfrags--;
1536 m_freem(q);
1537 }
1538
1539 inserted:
1540 currentfrags++;
1541
1542 #if IPDIVERT
1543 /*
1544 * Transfer firewall instructions to the fragment structure.
1545 * Only trust info in the fragment at offset 0.
1546 */
1547 if (ip->ip_off == 0) {
1548 #ifdef IPDIVERT_44
1549 fp->ipq_div_info = *divinfo;
1550 #else
1551 fp->ipq_divert = *divinfo;
1552 #endif
1553 fp->ipq_div_cookie = *divcookie;
1554 }
1555 *divinfo = 0;
1556 *divcookie = 0;
1557 #endif
1558
1559 /*
1560 * Check for complete reassembly and perform frag per packet
1561 * limiting.
1562 *
1563 * Frag limiting is performed here so that the nth frag has
1564 * a chance to complete the packet before we drop the packet.
1565 * As a result, n+1 frags are actually allowed per packet, but
1566 * only n will ever be stored. (n = maxfragsperpacket.)
1567 *
1568 */
1569 next = 0;
1570 for (p = NULL, q = fp->ipq_frags; q; p = q, q = q->m_nextpkt) {
1571 if (GETIP(q)->ip_off != next) {
1572 if (fp->ipq_nfrags > maxfragsperpacket) {
1573 OSAddAtomic(fp->ipq_nfrags, &ipstat.ips_fragdropped);
1574 ip_freef(fp);
1575 }
1576 return (0);
1577 }
1578 next += GETIP(q)->ip_len;
1579 }
1580 /* Make sure the last packet didn't have the IP_MF flag */
1581 if (p->m_flags & M_FRAG) {
1582 if (fp->ipq_nfrags > maxfragsperpacket) {
1583 OSAddAtomic(fp->ipq_nfrags, &ipstat.ips_fragdropped);
1584 ip_freef(fp);
1585 }
1586 return (0);
1587 }
1588
1589 /*
1590 * Reassembly is complete. Make sure the packet is a sane size.
1591 */
1592 q = fp->ipq_frags;
1593 ip = GETIP(q);
1594 if (next + (IP_VHL_HL(ip->ip_vhl) << 2) > IP_MAXPACKET) {
1595 OSAddAtomic(1, &ipstat.ips_toolong);
1596 OSAddAtomic(fp->ipq_nfrags, &ipstat.ips_fragdropped);
1597 ip_freef(fp);
1598 return (0);
1599 }
1600
1601 /*
1602 * Concatenate fragments.
1603 */
1604 m = q;
1605 t = m->m_next;
1606 m->m_next = 0;
1607 m_cat(m, t);
1608 nq = q->m_nextpkt;
1609 q->m_nextpkt = 0;
1610 for (q = nq; q != NULL; q = nq) {
1611 nq = q->m_nextpkt;
1612 q->m_nextpkt = NULL;
1613 if (q->m_pkthdr.csum_flags & CSUM_TCP_SUM16)
1614 m->m_pkthdr.csum_flags = 0;
1615 else {
1616 m->m_pkthdr.csum_flags &= q->m_pkthdr.csum_flags;
1617 m->m_pkthdr.csum_data += q->m_pkthdr.csum_data;
1618 }
1619 m_cat(m, q);
1620 }
1621
1622 #if IPDIVERT
1623 /*
1624 * Extract firewall instructions from the fragment structure.
1625 */
1626 #ifdef IPDIVERT_44
1627 *divinfo = fp->ipq_div_info;
1628 #else
1629 *divinfo = fp->ipq_divert;
1630 #endif
1631 *divcookie = fp->ipq_div_cookie;
1632 #endif
1633
1634 #if CONFIG_MACF_NET
1635 mac_mbuf_label_associate_ipq(fp, m);
1636 mac_ipq_label_destroy(fp);
1637 #endif
1638 /*
1639 * Create header for new ip packet by
1640 * modifying header of first packet;
1641 * dequeue and discard fragment reassembly header.
1642 * Make header visible.
1643 */
1644 ip->ip_len = next;
1645 ip->ip_src = fp->ipq_src;
1646 ip->ip_dst = fp->ipq_dst;
1647 remque((void*)fp);
1648 TAILQ_REMOVE(&ipq_list, fp, ipq_list);
1649 currentfrags -= fp->ipq_nfrags;
1650 nipq--;
1651 (void) m_free(dtom(fp));
1652 m->m_len += (IP_VHL_HL(ip->ip_vhl) << 2);
1653 m->m_data -= (IP_VHL_HL(ip->ip_vhl) << 2);
1654 /* some debugging cruft by sklower, below, will go away soon */
1655 if (m->m_flags & M_PKTHDR) { /* XXX this should be done elsewhere */
1656 int plen = 0;
1657 for (t = m; t; t = t->m_next)
1658 plen += t->m_len;
1659 m->m_pkthdr.len = plen;
1660 }
1661 return (m);
1662
1663 dropfrag:
1664 #if IPDIVERT
1665 *divinfo = 0;
1666 *divcookie = 0;
1667 #endif
1668 OSAddAtomic(1, &ipstat.ips_fragdropped);
1669 if (fp != 0)
1670 fp->ipq_nfrags--;
1671 m_freem(m);
1672 return (0);
1673
1674 #undef GETIP
1675 }
1676
1677 /*
1678 * Free a fragment reassembly header and all
1679 * associated datagrams.
1680 */
1681 static void
1682 ip_freef(struct ipq *fp)
1683 {
1684 lck_mtx_assert(ip_mutex, LCK_MTX_ASSERT_OWNED);
1685 currentfrags -= fp->ipq_nfrags;
1686 m_freem_list(fp->ipq_frags);
1687 remque((void*)fp);
1688 TAILQ_REMOVE(&ipq_list, fp, ipq_list);
1689 (void) m_free(dtom(fp));
1690 nipq--;
1691 }
1692
1693 /*
1694 * IP timer processing;
1695 * if a timer expires on a reassembly
1696 * queue, discard it.
1697 */
1698 void
1699 ip_slowtimo(void)
1700 {
1701 struct ipq *fp;
1702 int i;
1703 lck_mtx_lock(ip_mutex);
1704 for (i = 0; i < IPREASS_NHASH; i++) {
1705 fp = ipq[i].next;
1706 if (fp == 0)
1707 continue;
1708 while (fp != &ipq[i]) {
1709 --fp->ipq_ttl;
1710 fp = fp->next;
1711 if (fp->prev->ipq_ttl == 0) {
1712 OSAddAtomic(fp->ipq_nfrags, &ipstat.ips_fragtimeout);
1713 ip_freef(fp->prev);
1714 }
1715 }
1716 }
1717 /*
1718 * If we are over the maximum number of fragments
1719 * (due to the limit being lowered), drain off
1720 * enough to get down to the new limit.
1721 */
1722 if (maxnipq >= 0 && nipq > maxnipq) {
1723 for (i = 0; i < IPREASS_NHASH; i++) {
1724 while (nipq > maxnipq &&
1725 (ipq[i].next != &ipq[i])) {
1726 OSAddAtomic(ipq[i].next->ipq_nfrags, &ipstat.ips_fragdropped);
1727 ip_freef(ipq[i].next);
1728 }
1729 }
1730 }
1731 #if IPFLOW
1732 ipflow_slowtimo();
1733 #endif
1734 lck_mtx_unlock(ip_mutex);
1735 }
1736
1737 /*
1738 * Drain off all datagram fragments.
1739 */
1740 void
1741 ip_drain(void)
1742 {
1743 int i;
1744
1745 lck_mtx_lock(ip_mutex);
1746 for (i = 0; i < IPREASS_NHASH; i++) {
1747 while (ipq[i].next != &ipq[i]) {
1748 OSAddAtomic(ipq[i].next->ipq_nfrags, &ipstat.ips_fragdropped);
1749 ip_freef(ipq[i].next);
1750 }
1751 }
1752 lck_mtx_unlock(ip_mutex);
1753 in_rtqdrain();
1754 }
1755
1756 /*
1757 * Do option processing on a datagram,
1758 * possibly discarding it if bad options are encountered,
1759 * or forwarding it if source-routed.
1760 * The pass argument is used when operating in the IPSTEALTH
1761 * mode to tell what options to process:
1762 * [LS]SRR (pass 0) or the others (pass 1).
1763 * The reason for as many as two passes is that when doing IPSTEALTH,
1764 * non-routing options should be processed only if the packet is for us.
1765 * Returns 1 if packet has been forwarded/freed,
1766 * 0 if the packet should be processed further.
1767 */
1768 static int
1769 ip_dooptions(struct mbuf *m, __unused int pass, struct sockaddr_in *next_hop)
1770 {
1771 struct ip *ip = mtod(m, struct ip *);
1772 u_char *cp;
1773 struct ip_timestamp *ipt;
1774 struct in_ifaddr *ia;
1775 int opt, optlen, cnt, off, code, type = ICMP_PARAMPROB, forward = 0;
1776 struct in_addr *sin, dst;
1777 n_time ntime;
1778 struct sockaddr_in ipaddr = {
1779 sizeof (ipaddr), AF_INET , 0 , { 0 }, { 0, } };
1780
1781 dst = ip->ip_dst;
1782 cp = (u_char *)(ip + 1);
1783 cnt = (IP_VHL_HL(ip->ip_vhl) << 2) - sizeof (struct ip);
1784 for (; cnt > 0; cnt -= optlen, cp += optlen) {
1785 opt = cp[IPOPT_OPTVAL];
1786 if (opt == IPOPT_EOL)
1787 break;
1788 if (opt == IPOPT_NOP)
1789 optlen = 1;
1790 else {
1791 if (cnt < IPOPT_OLEN + sizeof(*cp)) {
1792 code = &cp[IPOPT_OLEN] - (u_char *)ip;
1793 goto bad;
1794 }
1795 optlen = cp[IPOPT_OLEN];
1796 if (optlen < IPOPT_OLEN + sizeof(*cp) || optlen > cnt) {
1797 code = &cp[IPOPT_OLEN] - (u_char *)ip;
1798 goto bad;
1799 }
1800 }
1801 switch (opt) {
1802
1803 default:
1804 break;
1805
1806 /*
1807 * Source routing with record.
1808 * Find interface with current destination address.
1809 * If none on this machine then drop if strictly routed,
1810 * or do nothing if loosely routed.
1811 * Record interface address and bring up next address
1812 * component. If strictly routed make sure next
1813 * address is on directly accessible net.
1814 */
1815 case IPOPT_LSRR:
1816 case IPOPT_SSRR:
1817 if (optlen < IPOPT_OFFSET + sizeof(*cp)) {
1818 code = &cp[IPOPT_OLEN] - (u_char *)ip;
1819 goto bad;
1820 }
1821 if ((off = cp[IPOPT_OFFSET]) < IPOPT_MINOFF) {
1822 code = &cp[IPOPT_OFFSET] - (u_char *)ip;
1823 goto bad;
1824 }
1825 ipaddr.sin_addr = ip->ip_dst;
1826 ia = (struct in_ifaddr *)
1827 ifa_ifwithaddr((struct sockaddr *)&ipaddr);
1828 if (ia == 0) {
1829 if (opt == IPOPT_SSRR) {
1830 type = ICMP_UNREACH;
1831 code = ICMP_UNREACH_SRCFAIL;
1832 goto bad;
1833 }
1834 if (!ip_dosourceroute)
1835 goto nosourcerouting;
1836 /*
1837 * Loose routing, and not at next destination
1838 * yet; nothing to do except forward.
1839 */
1840 break;
1841 }
1842 else {
1843 ifafree(&ia->ia_ifa);
1844 ia = NULL;
1845 }
1846 off--; /* 0 origin */
1847 if (off > optlen - (int)sizeof(struct in_addr)) {
1848 /*
1849 * End of source route. Should be for us.
1850 */
1851 if (!ip_acceptsourceroute)
1852 goto nosourcerouting;
1853 save_rte(cp, ip->ip_src);
1854 break;
1855 }
1856
1857 if (!ip_dosourceroute) {
1858 if (ipforwarding) {
1859 char buf[MAX_IPv4_STR_LEN];
1860 char buf2[MAX_IPv4_STR_LEN];
1861 /*
1862 * Acting as a router, so generate ICMP
1863 */
1864 nosourcerouting:
1865 log(LOG_WARNING,
1866 "attempted source route from %s to %s\n",
1867 inet_ntop(AF_INET, &ip->ip_src, buf, sizeof(buf)),
1868 inet_ntop(AF_INET, &ip->ip_dst, buf2, sizeof(buf2)));
1869 type = ICMP_UNREACH;
1870 code = ICMP_UNREACH_SRCFAIL;
1871 goto bad;
1872 } else {
1873 /*
1874 * Not acting as a router, so silently drop.
1875 */
1876 OSAddAtomic(1, &ipstat.ips_cantforward);
1877 m_freem(m);
1878 return (1);
1879 }
1880 }
1881
1882 /*
1883 * locate outgoing interface
1884 */
1885 (void)memcpy(&ipaddr.sin_addr, cp + off,
1886 sizeof(ipaddr.sin_addr));
1887
1888 if (opt == IPOPT_SSRR) {
1889 #define INA struct in_ifaddr *
1890 #define SA struct sockaddr *
1891 if ((ia = (INA)ifa_ifwithdstaddr((SA)&ipaddr)) == 0) {
1892 ia = (INA)ifa_ifwithnet((SA)&ipaddr);
1893 }
1894 } else {
1895 ia = ip_rtaddr(ipaddr.sin_addr);
1896 }
1897 if (ia == 0) {
1898 type = ICMP_UNREACH;
1899 code = ICMP_UNREACH_SRCFAIL;
1900 goto bad;
1901 }
1902 ip->ip_dst = ipaddr.sin_addr;
1903 (void)memcpy(cp + off, &(IA_SIN(ia)->sin_addr),
1904 sizeof(struct in_addr));
1905 ifafree(&ia->ia_ifa);
1906 ia = NULL;
1907 cp[IPOPT_OFFSET] += sizeof(struct in_addr);
1908 /*
1909 * Let ip_intr's mcast routing check handle mcast pkts
1910 */
1911 forward = !IN_MULTICAST(ntohl(ip->ip_dst.s_addr));
1912 break;
1913
1914 case IPOPT_RR:
1915 if (optlen < IPOPT_OFFSET + sizeof(*cp)) {
1916 code = &cp[IPOPT_OFFSET] - (u_char *)ip;
1917 goto bad;
1918 }
1919 if ((off = cp[IPOPT_OFFSET]) < IPOPT_MINOFF) {
1920 code = &cp[IPOPT_OFFSET] - (u_char *)ip;
1921 goto bad;
1922 }
1923 /*
1924 * If no space remains, ignore.
1925 */
1926 off--; /* 0 origin */
1927 if (off > optlen - (int)sizeof(struct in_addr))
1928 break;
1929 (void)memcpy(&ipaddr.sin_addr, &ip->ip_dst,
1930 sizeof(ipaddr.sin_addr));
1931 /*
1932 * locate outgoing interface; if we're the destination,
1933 * use the incoming interface (should be same).
1934 */
1935 if ((ia = (INA)ifa_ifwithaddr((SA)&ipaddr)) == 0) {
1936 if ((ia = ip_rtaddr(ipaddr.sin_addr)) == 0) {
1937 type = ICMP_UNREACH;
1938 code = ICMP_UNREACH_HOST;
1939 goto bad;
1940 }
1941 }
1942 (void)memcpy(cp + off, &(IA_SIN(ia)->sin_addr),
1943 sizeof(struct in_addr));
1944 ifafree(&ia->ia_ifa);
1945 ia = NULL;
1946 cp[IPOPT_OFFSET] += sizeof(struct in_addr);
1947 break;
1948
1949 case IPOPT_TS:
1950 code = cp - (u_char *)ip;
1951 ipt = (struct ip_timestamp *)cp;
1952 if (ipt->ipt_len < 4 || ipt->ipt_len > 40) {
1953 code = (u_char *)&ipt->ipt_len - (u_char *)ip;
1954 goto bad;
1955 }
1956 if (ipt->ipt_ptr < 5) {
1957 code = (u_char *)&ipt->ipt_ptr - (u_char *)ip;
1958 goto bad;
1959 }
1960 if (ipt->ipt_ptr >
1961 ipt->ipt_len - (int)sizeof(int32_t)) {
1962 if (++ipt->ipt_oflw == 0) {
1963 code = (u_char *)&ipt->ipt_ptr -
1964 (u_char *)ip;
1965 goto bad;
1966 }
1967 break;
1968 }
1969 sin = (struct in_addr *)(cp + ipt->ipt_ptr - 1);
1970 switch (ipt->ipt_flg) {
1971
1972 case IPOPT_TS_TSONLY:
1973 break;
1974
1975 case IPOPT_TS_TSANDADDR:
1976 if (ipt->ipt_ptr - 1 + sizeof(n_time) +
1977 sizeof(struct in_addr) > ipt->ipt_len) {
1978 code = (u_char *)&ipt->ipt_ptr -
1979 (u_char *)ip;
1980 goto bad;
1981 }
1982 ipaddr.sin_addr = dst;
1983 ia = (INA)ifaof_ifpforaddr((SA)&ipaddr,
1984 m->m_pkthdr.rcvif);
1985 if (ia == 0)
1986 continue;
1987 (void)memcpy(sin, &IA_SIN(ia)->sin_addr,
1988 sizeof(struct in_addr));
1989 ipt->ipt_ptr += sizeof(struct in_addr);
1990 ifafree(&ia->ia_ifa);
1991 ia = NULL;
1992 break;
1993
1994 case IPOPT_TS_PRESPEC:
1995 if (ipt->ipt_ptr - 1 + sizeof(n_time) +
1996 sizeof(struct in_addr) > ipt->ipt_len) {
1997 code = (u_char *)&ipt->ipt_ptr -
1998 (u_char *)ip;
1999 goto bad;
2000 }
2001 (void)memcpy(&ipaddr.sin_addr, sin,
2002 sizeof(struct in_addr));
2003 if ((ia = (struct in_ifaddr*)ifa_ifwithaddr((SA)&ipaddr)) == 0)
2004 continue;
2005 ifafree(&ia->ia_ifa);
2006 ia = NULL;
2007 ipt->ipt_ptr += sizeof(struct in_addr);
2008 break;
2009
2010 default:
2011 /* XXX can't take &ipt->ipt_flg */
2012 code = (u_char *)&ipt->ipt_ptr -
2013 (u_char *)ip + 1;
2014 goto bad;
2015 }
2016 ntime = iptime();
2017 (void)memcpy(cp + ipt->ipt_ptr - 1, &ntime,
2018 sizeof(n_time));
2019 ipt->ipt_ptr += sizeof(n_time);
2020 }
2021 }
2022 if (forward && ipforwarding) {
2023 ip_forward(m, 1, next_hop);
2024 return (1);
2025 }
2026 return (0);
2027 bad:
2028 ip->ip_len -= IP_VHL_HL(ip->ip_vhl) << 2; /* XXX icmp_error adds in hdr length */
2029 icmp_error(m, type, code, 0, 0);
2030 OSAddAtomic(1, &ipstat.ips_badoptions);
2031 return (1);
2032 }
2033
2034 /*
2035 * Given address of next destination (final or next hop),
2036 * return internet address info of interface to be used to get there.
2037 */
2038 struct in_ifaddr *
2039 ip_rtaddr(struct in_addr dst)
2040 {
2041 struct sockaddr_in *sin;
2042 struct ifaddr *rt_ifa;
2043 struct route ro;
2044
2045 bzero(&ro, sizeof (ro));
2046 sin = (struct sockaddr_in *)&ro.ro_dst;
2047 sin->sin_family = AF_INET;
2048 sin->sin_len = sizeof (*sin);
2049 sin->sin_addr = dst;
2050
2051 rtalloc_ign(&ro, RTF_PRCLONING);
2052 if (ro.ro_rt == NULL)
2053 return (NULL);
2054
2055 RT_LOCK(ro.ro_rt);
2056 if ((rt_ifa = ro.ro_rt->rt_ifa) != NULL)
2057 ifaref(rt_ifa);
2058 RT_UNLOCK(ro.ro_rt);
2059 rtfree(ro.ro_rt);
2060
2061 return ((struct in_ifaddr *)rt_ifa);
2062 }
2063
2064 /*
2065 * Save incoming source route for use in replies,
2066 * to be picked up later by ip_srcroute if the receiver is interested.
2067 */
2068 void
2069 save_rte(u_char *option, struct in_addr dst)
2070 {
2071 unsigned olen;
2072
2073 olen = option[IPOPT_OLEN];
2074 #if DIAGNOSTIC
2075 if (ipprintfs)
2076 printf("save_rte: olen %d\n", olen);
2077 #endif
2078 if (olen > sizeof(ip_srcrt) - (1 + sizeof(dst)))
2079 return;
2080 bcopy(option, ip_srcrt.srcopt, olen);
2081 ip_nhops = (olen - IPOPT_OFFSET - 1) / sizeof(struct in_addr);
2082 ip_srcrt.dst = dst;
2083 }
2084
2085 /*
2086 * Retrieve incoming source route for use in replies,
2087 * in the same form used by setsockopt.
2088 * The first hop is placed before the options, will be removed later.
2089 */
2090 struct mbuf *
2091 ip_srcroute(void)
2092 {
2093 struct in_addr *p, *q;
2094 struct mbuf *m;
2095
2096 if (ip_nhops == 0)
2097 return ((struct mbuf *)0);
2098 m = m_get(M_DONTWAIT, MT_HEADER);
2099 if (m == 0)
2100 return ((struct mbuf *)0);
2101
2102 #define OPTSIZ (sizeof(ip_srcrt.nop) + sizeof(ip_srcrt.srcopt))
2103
2104 /* length is (nhops+1)*sizeof(addr) + sizeof(nop + srcrt header) */
2105 m->m_len = ip_nhops * sizeof(struct in_addr) + sizeof(struct in_addr) +
2106 OPTSIZ;
2107 #if DIAGNOSTIC
2108 if (ipprintfs)
2109 printf("ip_srcroute: nhops %d mlen %d", ip_nhops, m->m_len);
2110 #endif
2111
2112 /*
2113 * First save first hop for return route
2114 */
2115 p = &ip_srcrt.route[ip_nhops - 1];
2116 *(mtod(m, struct in_addr *)) = *p--;
2117 #if DIAGNOSTIC
2118 if (ipprintfs)
2119 printf(" hops %lx", (u_int32_t)ntohl(mtod(m, struct in_addr *)->s_addr));
2120 #endif
2121
2122 /*
2123 * Copy option fields and padding (nop) to mbuf.
2124 */
2125 ip_srcrt.nop = IPOPT_NOP;
2126 ip_srcrt.srcopt[IPOPT_OFFSET] = IPOPT_MINOFF;
2127 (void)memcpy(mtod(m, caddr_t) + sizeof(struct in_addr),
2128 &ip_srcrt.nop, OPTSIZ);
2129 q = (struct in_addr *)(mtod(m, caddr_t) +
2130 sizeof(struct in_addr) + OPTSIZ);
2131 #undef OPTSIZ
2132 /*
2133 * Record return path as an IP source route,
2134 * reversing the path (pointers are now aligned).
2135 */
2136 while (p >= ip_srcrt.route) {
2137 #if DIAGNOSTIC
2138 if (ipprintfs)
2139 printf(" %lx", (u_int32_t)ntohl(q->s_addr));
2140 #endif
2141 *q++ = *p--;
2142 }
2143 /*
2144 * Last hop goes to final destination.
2145 */
2146 *q = ip_srcrt.dst;
2147 #if DIAGNOSTIC
2148 if (ipprintfs)
2149 printf(" %lx\n", (u_int32_t)ntohl(q->s_addr));
2150 #endif
2151 return (m);
2152 }
2153
2154 /*
2155 * Strip out IP options, at higher
2156 * level protocol in the kernel.
2157 * Second argument is buffer to which options
2158 * will be moved, and return value is their length.
2159 * XXX should be deleted; last arg currently ignored.
2160 */
2161 void
2162 ip_stripoptions(struct mbuf *m, __unused struct mbuf *mopt)
2163 {
2164 int i;
2165 struct ip *ip = mtod(m, struct ip *);
2166 caddr_t opts;
2167 int olen;
2168
2169 olen = (IP_VHL_HL(ip->ip_vhl) << 2) - sizeof (struct ip);
2170 opts = (caddr_t)(ip + 1);
2171 i = m->m_len - (sizeof (struct ip) + olen);
2172 bcopy(opts + olen, opts, (unsigned)i);
2173 m->m_len -= olen;
2174 if (m->m_flags & M_PKTHDR)
2175 m->m_pkthdr.len -= olen;
2176 ip->ip_vhl = IP_MAKE_VHL(IPVERSION, sizeof(struct ip) >> 2);
2177 }
2178
2179 u_char inetctlerrmap[PRC_NCMDS] = {
2180 0, 0, 0, 0,
2181 0, EMSGSIZE, EHOSTDOWN, EHOSTUNREACH,
2182 ENETUNREACH, EHOSTUNREACH, ECONNREFUSED, ECONNREFUSED,
2183 EMSGSIZE, EHOSTUNREACH, 0, 0,
2184 0, 0, 0, 0,
2185 ENOPROTOOPT, ECONNREFUSED
2186 };
2187
2188 static int
2189 sysctl_ipforwarding SYSCTL_HANDLER_ARGS
2190 {
2191 #pragma unused(arg1, arg2)
2192 int i, was_ipforwarding = ipforwarding;
2193
2194 i = sysctl_handle_int(oidp, oidp->oid_arg1, oidp->oid_arg2, req);
2195 if (i != 0 || req->newptr == USER_ADDR_NULL)
2196 return (i);
2197
2198 if (was_ipforwarding && !ipforwarding) {
2199 /* clean up IPv4 forwarding cached routes */
2200 ifnet_head_lock_shared();
2201 for (i = 0; i <= if_index; i++) {
2202 struct ifnet *ifp = ifindex2ifnet[i];
2203 if (ifp != NULL) {
2204 lck_mtx_lock(ifp->if_fwd_route_lock);
2205 if (ifp->if_fwd_route.ro_rt != NULL) {
2206 rtfree(ifp->if_fwd_route.ro_rt);
2207 ifp->if_fwd_route.ro_rt = NULL;
2208 }
2209 lck_mtx_unlock(ifp->if_fwd_route_lock);
2210 }
2211 }
2212 ifnet_head_done();
2213 }
2214
2215 return (0);
2216 }
2217
2218 /*
2219 * Similar to inp_route_{copyout,copyin} routines except that these copy
2220 * out the cached IPv4 forwarding route from struct ifnet instead of the
2221 * inpcb. See comments for those routines for explanations.
2222 */
2223 static void
2224 ip_fwd_route_copyout(struct ifnet *ifp, struct route *dst)
2225 {
2226 struct route *src = &ifp->if_fwd_route;
2227
2228 lck_mtx_lock(ifp->if_fwd_route_lock);
2229
2230 /* Minor sanity check */
2231 if (src->ro_rt != NULL && rt_key(src->ro_rt)->sa_family != AF_INET)
2232 panic("%s: wrong or corrupted route: %p", __func__, src);
2233
2234 /* Copy everything (rt, dst, flags) from ifnet */
2235 bcopy(src, dst, sizeof (*dst));
2236
2237 /* Hold one reference for the local copy of struct route */
2238 if (dst->ro_rt != NULL)
2239 RT_ADDREF(dst->ro_rt);
2240
2241 lck_mtx_unlock(ifp->if_fwd_route_lock);
2242 }
2243
2244 static void
2245 ip_fwd_route_copyin(struct ifnet *ifp, struct route *src)
2246 {
2247 struct route *dst = &ifp->if_fwd_route;
2248
2249 lck_mtx_lock(ifp->if_fwd_route_lock);
2250
2251 /* Minor sanity check */
2252 if (src->ro_rt != NULL && rt_key(src->ro_rt)->sa_family != AF_INET)
2253 panic("%s: wrong or corrupted route: %p", __func__, src);
2254
2255 /* No cached route in the ifnet? */
2256 if (dst->ro_rt == NULL) {
2257 /*
2258 * Copy everything (rt, dst, flags) from ip_forward();
2259 * the reference to the route was held at the time
2260 * it was allocated and is kept intact.
2261 */
2262 bcopy(src, dst, sizeof (*dst));
2263 } else if (src->ro_rt != NULL) {
2264 /*
2265 * If the same, update just the ro_flags and ditch the one
2266 * in the local copy. Else ditch the one that is currently
2267 * cached, and cache what we got back from ip_output().
2268 */
2269 if (dst->ro_rt == src->ro_rt) {
2270 dst->ro_flags = src->ro_flags;
2271 rtfree(src->ro_rt);
2272 src->ro_rt = NULL;
2273 } else {
2274 rtfree(dst->ro_rt);
2275 bcopy(src, dst, sizeof (*dst));
2276 }
2277 }
2278
2279 lck_mtx_unlock(ifp->if_fwd_route_lock);
2280 }
2281
2282 /*
2283 * Forward a packet. If some error occurs return the sender
2284 * an icmp packet. Note we can't always generate a meaningful
2285 * icmp message because icmp doesn't have a large enough repertoire
2286 * of codes and types.
2287 *
2288 * If not forwarding, just drop the packet. This could be confusing
2289 * if ipforwarding was zero but some routing protocol was advancing
2290 * us as a gateway to somewhere. However, we must let the routing
2291 * protocol deal with that.
2292 *
2293 * The srcrt parameter indicates whether the packet is being forwarded
2294 * via a source route.
2295 */
2296 static void
2297 ip_forward(struct mbuf *m, int srcrt, struct sockaddr_in *next_hop)
2298 {
2299 #if !IPFIREWALL
2300 #pragma unused(next_hop)
2301 #endif
2302 struct ip *ip = mtod(m, struct ip *);
2303 struct sockaddr_in *sin;
2304 struct rtentry *rt;
2305 struct route fwd_rt;
2306 int error, type = 0, code = 0;
2307 struct mbuf *mcopy;
2308 n_long dest;
2309 struct in_addr pkt_dst;
2310 u_int32_t nextmtu = 0;
2311 struct ip_out_args ipoa = { IFSCOPE_NONE };
2312 struct ifnet *ifp = m->m_pkthdr.rcvif;
2313 #if PF
2314 struct pf_mtag *pf_mtag;
2315 #endif /* PF */
2316
2317 dest = 0;
2318 #if IPFIREWALL
2319 /*
2320 * Cache the destination address of the packet; this may be
2321 * changed by use of 'ipfw fwd'.
2322 */
2323 pkt_dst = next_hop ? next_hop->sin_addr : ip->ip_dst;
2324 #else
2325 pkt_dst = ip->ip_dst;
2326 #endif
2327
2328 #if DIAGNOSTIC
2329 if (ipprintfs)
2330 printf("forward: src %lx dst %lx ttl %x\n",
2331 (u_int32_t)ip->ip_src.s_addr, (u_int32_t)pkt_dst.s_addr,
2332 ip->ip_ttl);
2333 #endif
2334
2335 if (m->m_flags & (M_BCAST|M_MCAST) || in_canforward(pkt_dst) == 0) {
2336 OSAddAtomic(1, &ipstat.ips_cantforward);
2337 m_freem(m);
2338 return;
2339 }
2340 #if IPSTEALTH
2341 if (!ipstealth) {
2342 #endif
2343 if (ip->ip_ttl <= IPTTLDEC) {
2344 icmp_error(m, ICMP_TIMXCEED, ICMP_TIMXCEED_INTRANS,
2345 dest, 0);
2346 return;
2347 }
2348 #if IPSTEALTH
2349 }
2350 #endif
2351
2352 #if PF
2353 pf_mtag = pf_find_mtag(m);
2354 if (pf_mtag != NULL && pf_mtag->rtableid != IFSCOPE_NONE)
2355 ipoa.ipoa_ifscope = pf_mtag->rtableid;
2356 #endif /* PF */
2357
2358 ip_fwd_route_copyout(ifp, &fwd_rt);
2359
2360 sin = (struct sockaddr_in *)&fwd_rt.ro_dst;
2361 if (fwd_rt.ro_rt == NULL ||
2362 fwd_rt.ro_rt->generation_id != route_generation ||
2363 pkt_dst.s_addr != sin->sin_addr.s_addr) {
2364 if (fwd_rt.ro_rt != NULL) {
2365 rtfree(fwd_rt.ro_rt);
2366 fwd_rt.ro_rt = NULL;
2367 }
2368 sin->sin_family = AF_INET;
2369 sin->sin_len = sizeof (*sin);
2370 sin->sin_addr = pkt_dst;
2371
2372 rtalloc_scoped_ign(&fwd_rt, RTF_PRCLONING, ipoa.ipoa_ifscope);
2373 if (fwd_rt.ro_rt == NULL) {
2374 icmp_error(m, ICMP_UNREACH, ICMP_UNREACH_HOST, dest, 0);
2375 goto done;
2376 }
2377 }
2378 rt = fwd_rt.ro_rt;
2379
2380 /*
2381 * Save the IP header and at most 8 bytes of the payload,
2382 * in case we need to generate an ICMP message to the src.
2383 *
2384 * We don't use m_copy() because it might return a reference
2385 * to a shared cluster. Both this function and ip_output()
2386 * assume exclusive access to the IP header in `m', so any
2387 * data in a cluster may change before we reach icmp_error().
2388 */
2389 MGET(mcopy, M_DONTWAIT, m->m_type);
2390 if (mcopy != NULL) {
2391 M_COPY_PKTHDR(mcopy, m);
2392 mcopy->m_len = imin((IP_VHL_HL(ip->ip_vhl) << 2) + 8,
2393 (int)ip->ip_len);
2394 m_copydata(m, 0, mcopy->m_len, mtod(mcopy, caddr_t));
2395 }
2396
2397 #if IPSTEALTH
2398 if (!ipstealth) {
2399 #endif
2400 ip->ip_ttl -= IPTTLDEC;
2401 #if IPSTEALTH
2402 }
2403 #endif
2404
2405 /*
2406 * If forwarding packet using same interface that it came in on,
2407 * perhaps should send a redirect to sender to shortcut a hop.
2408 * Only send redirect if source is sending directly to us,
2409 * and if packet was not source routed (or has any options).
2410 * Also, don't send redirect if forwarding using a default route
2411 * or a route modified by a redirect.
2412 */
2413 RT_LOCK_SPIN(rt);
2414 if (rt->rt_ifp == m->m_pkthdr.rcvif &&
2415 (rt->rt_flags & (RTF_DYNAMIC|RTF_MODIFIED)) == 0 &&
2416 satosin(rt_key(rt))->sin_addr.s_addr != 0 &&
2417 ipsendredirects && !srcrt) {
2418 #define RTA(rt) ((struct in_ifaddr *)(rt->rt_ifa))
2419 u_int32_t src = ntohl(ip->ip_src.s_addr);
2420
2421 if (RTA(rt) &&
2422 (src & RTA(rt)->ia_subnetmask) == RTA(rt)->ia_subnet) {
2423 if (rt->rt_flags & RTF_GATEWAY)
2424 dest = satosin(rt->rt_gateway)->sin_addr.s_addr;
2425 else
2426 dest = pkt_dst.s_addr;
2427 /* Router requirements says to only send host redirects */
2428 type = ICMP_REDIRECT;
2429 code = ICMP_REDIRECT_HOST;
2430 #if DIAGNOSTIC
2431 if (ipprintfs)
2432 printf("redirect (%d) to %lx\n", code, (u_int32_t)dest);
2433 #endif
2434 }
2435 }
2436 RT_UNLOCK(rt);
2437
2438 #if IPFIREWALL
2439 if (next_hop) {
2440 /* Pass IPFORWARD info if available */
2441 struct m_tag *tag;
2442 struct ip_fwd_tag *ipfwd_tag;
2443
2444 tag = m_tag_alloc(KERNEL_MODULE_TAG_ID,
2445 KERNEL_TAG_TYPE_IPFORWARD,
2446 sizeof (*ipfwd_tag), M_NOWAIT);
2447 if (tag == NULL) {
2448 error = ENOBUFS;
2449 m_freem(m);
2450 goto done;
2451 }
2452
2453 ipfwd_tag = (struct ip_fwd_tag *)(tag+1);
2454 ipfwd_tag->next_hop = next_hop;
2455
2456 m_tag_prepend(m, tag);
2457 }
2458 #endif
2459 error = ip_output_list(m, 0, NULL, &fwd_rt,
2460 IP_FORWARDING | IP_OUTARGS, 0, &ipoa);
2461
2462 /* Refresh rt since the route could have changed while in IP */
2463 rt = fwd_rt.ro_rt;
2464
2465 if (error) {
2466 OSAddAtomic(1, &ipstat.ips_cantforward);
2467 } else {
2468 OSAddAtomic(1, &ipstat.ips_forward);
2469 if (type)
2470 OSAddAtomic(1, &ipstat.ips_redirectsent);
2471 else {
2472 if (mcopy) {
2473 #if IPFLOW
2474 ipflow_create(&fwd_rt, mcopy);
2475 #endif
2476 /*
2477 * If we didn't have to go thru ipflow and
2478 * the packet was successfully consumed by
2479 * ip_output, the mcopy is rather a waste;
2480 * this could be further optimized.
2481 */
2482 m_freem(mcopy);
2483 }
2484 goto done;
2485 }
2486 }
2487 if (mcopy == NULL)
2488 goto done;
2489
2490 switch (error) {
2491
2492 case 0: /* forwarded, but need redirect */
2493 /* type, code set above */
2494 break;
2495
2496 case ENETUNREACH: /* shouldn't happen, checked above */
2497 case EHOSTUNREACH:
2498 case ENETDOWN:
2499 case EHOSTDOWN:
2500 default:
2501 type = ICMP_UNREACH;
2502 code = ICMP_UNREACH_HOST;
2503 break;
2504
2505 case EMSGSIZE:
2506 type = ICMP_UNREACH;
2507 code = ICMP_UNREACH_NEEDFRAG;
2508 #ifndef IPSEC
2509 if (rt != NULL) {
2510 RT_LOCK_SPIN(rt);
2511 if (rt->rt_ifp != NULL)
2512 nextmtu = rt->rt_ifp->if_mtu;
2513 RT_UNLOCK(rt);
2514 }
2515 #else
2516 /*
2517 * If the packet is routed over IPsec tunnel, tell the
2518 * originator the tunnel MTU.
2519 * tunnel MTU = if MTU - sizeof(IP) - ESP/AH hdrsiz
2520 * XXX quickhack!!!
2521 */
2522 if (rt != NULL) {
2523 struct secpolicy *sp = NULL;
2524 int ipsecerror;
2525 int ipsechdr;
2526 struct route *ro;
2527
2528 RT_LOCK_SPIN(rt);
2529 if (rt->rt_ifp != NULL)
2530 nextmtu = rt->rt_ifp->if_mtu;
2531 RT_UNLOCK(rt);
2532
2533 if (ipsec_bypass) {
2534 OSAddAtomic(1, &ipstat.ips_cantfrag);
2535 break;
2536 }
2537 sp = ipsec4_getpolicybyaddr(mcopy,
2538 IPSEC_DIR_OUTBOUND,
2539 IP_FORWARDING,
2540 &ipsecerror);
2541
2542 if (sp != NULL) {
2543 /* count IPsec header size */
2544 ipsechdr = ipsec_hdrsiz(sp);
2545
2546 /*
2547 * find the correct route for outer IPv4
2548 * header, compute tunnel MTU.
2549 */
2550 nextmtu = 0;
2551
2552 if (sp->req != NULL) {
2553 if (sp->req->saidx.mode == IPSEC_MODE_TUNNEL) {
2554 struct secasindex saidx;
2555 struct ip *ipm;
2556 struct secasvar *sav;
2557
2558 ipm = mtod(mcopy, struct ip *);
2559 bcopy(&sp->req->saidx, &saidx, sizeof(saidx));
2560 saidx.mode = sp->req->saidx.mode;
2561 saidx.reqid = sp->req->saidx.reqid;
2562 sin = (struct sockaddr_in *)&saidx.src;
2563 if (sin->sin_len == 0) {
2564 sin->sin_len = sizeof(*sin);
2565 sin->sin_family = AF_INET;
2566 sin->sin_port = IPSEC_PORT_ANY;
2567 bcopy(&ipm->ip_src, &sin->sin_addr,
2568 sizeof(sin->sin_addr));
2569 }
2570 sin = (struct sockaddr_in *)&saidx.dst;
2571 if (sin->sin_len == 0) {
2572 sin->sin_len = sizeof(*sin);
2573 sin->sin_family = AF_INET;
2574 sin->sin_port = IPSEC_PORT_ANY;
2575 bcopy(&ipm->ip_dst, &sin->sin_addr,
2576 sizeof(sin->sin_addr));
2577 }
2578 sav = key_allocsa_policy(&saidx);
2579 if (sav != NULL) {
2580 if (sav->sah != NULL) {
2581 ro = &sav->sah->sa_route;
2582 if (ro->ro_rt != NULL) {
2583 RT_LOCK(ro->ro_rt);
2584 if (ro->ro_rt->rt_ifp != NULL) {
2585 nextmtu = ro->ro_rt->rt_ifp->if_mtu;
2586 nextmtu -= ipsechdr;
2587 }
2588 RT_UNLOCK(ro->ro_rt);
2589 }
2590 }
2591 key_freesav(sav, KEY_SADB_UNLOCKED);
2592 }
2593 }
2594 }
2595 key_freesp(sp, KEY_SADB_UNLOCKED);
2596 }
2597 }
2598 #endif /*IPSEC*/
2599 OSAddAtomic(1, &ipstat.ips_cantfrag);
2600 break;
2601
2602 case ENOBUFS:
2603 type = ICMP_SOURCEQUENCH;
2604 code = 0;
2605 break;
2606
2607 case EACCES: /* ipfw denied packet */
2608 m_freem(mcopy);
2609 goto done;
2610 }
2611
2612 icmp_error(mcopy, type, code, dest, nextmtu);
2613 done:
2614 ip_fwd_route_copyin(ifp, &fwd_rt);
2615 }
2616
2617 void
2618 ip_savecontrol(
2619 struct inpcb *inp,
2620 struct mbuf **mp,
2621 struct ip *ip,
2622 struct mbuf *m)
2623 {
2624 if (inp->inp_socket->so_options & SO_TIMESTAMP) {
2625 struct timeval tv;
2626
2627 microtime(&tv);
2628 *mp = sbcreatecontrol((caddr_t) &tv, sizeof(tv),
2629 SCM_TIMESTAMP, SOL_SOCKET);
2630 if (*mp)
2631 mp = &(*mp)->m_next;
2632 }
2633 if (inp->inp_flags & INP_RECVDSTADDR) {
2634 *mp = sbcreatecontrol((caddr_t) &ip->ip_dst,
2635 sizeof(struct in_addr), IP_RECVDSTADDR, IPPROTO_IP);
2636 if (*mp)
2637 mp = &(*mp)->m_next;
2638 }
2639 #ifdef notyet
2640 /* XXX
2641 * Moving these out of udp_input() made them even more broken
2642 * than they already were.
2643 */
2644 /* options were tossed already */
2645 if (inp->inp_flags & INP_RECVOPTS) {
2646 *mp = sbcreatecontrol((caddr_t) opts_deleted_above,
2647 sizeof(struct in_addr), IP_RECVOPTS, IPPROTO_IP);
2648 if (*mp)
2649 mp = &(*mp)->m_next;
2650 }
2651 /* ip_srcroute doesn't do what we want here, need to fix */
2652 if (inp->inp_flags & INP_RECVRETOPTS) {
2653 *mp = sbcreatecontrol((caddr_t) ip_srcroute(),
2654 sizeof(struct in_addr), IP_RECVRETOPTS, IPPROTO_IP);
2655 if (*mp)
2656 mp = &(*mp)->m_next;
2657 }
2658 #endif
2659 if (inp->inp_flags & INP_RECVIF) {
2660 struct ifnet *ifp;
2661 struct sdlbuf {
2662 struct sockaddr_dl sdl;
2663 u_char pad[32];
2664 } sdlbuf;
2665 struct sockaddr_dl *sdp;
2666 struct sockaddr_dl *sdl2 = &sdlbuf.sdl;
2667
2668 ifnet_head_lock_shared();
2669 if (((ifp = m->m_pkthdr.rcvif))
2670 && ( ifp->if_index && (ifp->if_index <= if_index))) {
2671 struct ifaddr *ifa = ifnet_addrs[ifp->if_index - 1];
2672
2673 if (!ifa || !ifa->ifa_addr)
2674 goto makedummy;
2675
2676 sdp = (struct sockaddr_dl *)ifa->ifa_addr;
2677 /*
2678 * Change our mind and don't try copy.
2679 */
2680 if ((sdp->sdl_family != AF_LINK)
2681 || (sdp->sdl_len > sizeof(sdlbuf))) {
2682 goto makedummy;
2683 }
2684 bcopy(sdp, sdl2, sdp->sdl_len);
2685 } else {
2686 makedummy:
2687 sdl2->sdl_len
2688 = offsetof(struct sockaddr_dl, sdl_data[0]);
2689 sdl2->sdl_family = AF_LINK;
2690 sdl2->sdl_index = 0;
2691 sdl2->sdl_nlen = sdl2->sdl_alen = sdl2->sdl_slen = 0;
2692 }
2693 ifnet_head_done();
2694 *mp = sbcreatecontrol((caddr_t) sdl2, sdl2->sdl_len,
2695 IP_RECVIF, IPPROTO_IP);
2696 if (*mp)
2697 mp = &(*mp)->m_next;
2698 }
2699 if (inp->inp_flags & INP_RECVTTL) {
2700 *mp = sbcreatecontrol((caddr_t)&ip->ip_ttl, sizeof(ip->ip_ttl), IP_RECVTTL, IPPROTO_IP);
2701 if (*mp) mp = &(*mp)->m_next;
2702 }
2703 }
2704
2705 int
2706 ip_rsvp_init(struct socket *so)
2707 {
2708 if (so->so_type != SOCK_RAW ||
2709 so->so_proto->pr_protocol != IPPROTO_RSVP)
2710 return EOPNOTSUPP;
2711
2712 if (ip_rsvpd != NULL)
2713 return EADDRINUSE;
2714
2715 ip_rsvpd = so;
2716 /*
2717 * This may seem silly, but we need to be sure we don't over-increment
2718 * the RSVP counter, in case something slips up.
2719 */
2720 if (!ip_rsvp_on) {
2721 ip_rsvp_on = 1;
2722 rsvp_on++;
2723 }
2724
2725 return 0;
2726 }
2727
2728 int
2729 ip_rsvp_done(void)
2730 {
2731 ip_rsvpd = NULL;
2732 /*
2733 * This may seem silly, but we need to be sure we don't over-decrement
2734 * the RSVP counter, in case something slips up.
2735 */
2736 if (ip_rsvp_on) {
2737 ip_rsvp_on = 0;
2738 rsvp_on--;
2739 }
2740 return 0;
2741 }