2 * Copyright (c) 2003, 2004 Jeffrey M. Hsu. All rights reserved.
3 * Copyright (c) 2003, 2004 The DragonFly Project. All rights reserved.
5 * This code is derived from software contributed to The DragonFly Project
8 * Redistribution and use in source and binary forms, with or without
9 * modification, are permitted provided that the following conditions
11 * 1. Redistributions of source code must retain the above copyright
12 * notice, this list of conditions and the following disclaimer.
13 * 2. Redistributions in binary form must reproduce the above copyright
14 * notice, this list of conditions and the following disclaimer in the
15 * documentation and/or other materials provided with the distribution.
16 * 3. Neither the name of The DragonFly Project nor the names of its
17 * contributors may be used to endorse or promote products derived
18 * from this software without specific, prior written permission.
20 * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS
21 * ``AS IS'' AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT
22 * LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS
23 * FOR A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE
24 * COPYRIGHT HOLDERS OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT,
25 * INCIDENTAL, SPECIAL, EXEMPLARY OR CONSEQUENTIAL DAMAGES (INCLUDING,
26 * BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES;
27 * LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED
28 * AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY,
29 * OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT
30 * OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF
35 * Copyright (c) 1982, 1986, 1988, 1993
36 * The Regents of the University of California. All rights reserved.
38 * Redistribution and use in source and binary forms, with or without
39 * modification, are permitted provided that the following conditions
41 * 1. Redistributions of source code must retain the above copyright
42 * notice, this list of conditions and the following disclaimer.
43 * 2. Redistributions in binary form must reproduce the above copyright
44 * notice, this list of conditions and the following disclaimer in the
45 * documentation and/or other materials provided with the distribution.
46 * 3. Neither the name of the University nor the names of its contributors
47 * may be used to endorse or promote products derived from this software
48 * without specific prior written permission.
50 * THIS SOFTWARE IS PROVIDED BY THE REGENTS AND CONTRIBUTORS ``AS IS'' AND
51 * ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
52 * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE
53 * ARE DISCLAIMED. IN NO EVENT SHALL THE REGENTS OR CONTRIBUTORS BE LIABLE
54 * FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL
55 * DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS
56 * OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION)
57 * HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT
58 * LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY
59 * OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF
62 * @(#)ip_input.c 8.2 (Berkeley) 1/4/94
63 * $FreeBSD: src/sys/netinet/ip_input.c,v 1.130.2.52 2003/03/07 07:01:28 silby Exp $
68 #include "opt_bootp.h"
70 #include "opt_ipdivert.h"
71 #include "opt_ipstealth.h"
74 #include <sys/param.h>
75 #include <sys/systm.h>
77 #include <sys/malloc.h>
78 #include <sys/mpipe.h>
79 #include <sys/domain.h>
80 #include <sys/protosw.h>
81 #include <sys/socket.h>
83 #include <sys/globaldata.h>
84 #include <sys/thread.h>
85 #include <sys/kernel.h>
86 #include <sys/syslog.h>
87 #include <sys/sysctl.h>
88 #include <sys/in_cksum.h>
91 #include <sys/mplock2.h>
93 #include <machine/stdarg.h>
96 #include <net/if_types.h>
97 #include <net/if_var.h>
98 #include <net/if_dl.h>
100 #include <net/route.h>
101 #include <net/netisr2.h>
103 #include <netinet/in.h>
104 #include <netinet/in_systm.h>
105 #include <netinet/in_var.h>
106 #include <netinet/ip.h>
107 #include <netinet/in_pcb.h>
108 #include <netinet/ip_var.h>
109 #include <netinet/ip_icmp.h>
110 #include <netinet/ip_divert.h>
111 #include <netinet/ip_flow.h>
113 #include <sys/thread2.h>
114 #include <sys/msgport2.h>
115 #include <net/netmsg2.h>
117 #include <sys/socketvar.h>
119 #include <net/ipfw/ip_fw.h>
120 #include <net/dummynet/ip_dummynet.h>
123 static int ip_rsvp_on;
124 struct socket *ip_rsvpd;
126 int ipforwarding = 0;
127 SYSCTL_INT(_net_inet_ip, IPCTL_FORWARDING, forwarding, CTLFLAG_RW,
128 &ipforwarding, 0, "Enable IP forwarding between interfaces");
130 static int ipsendredirects = 1; /* XXX */
131 SYSCTL_INT(_net_inet_ip, IPCTL_SENDREDIRECTS, redirect, CTLFLAG_RW,
132 &ipsendredirects, 0, "Enable sending IP redirects");
134 int ip_defttl = IPDEFTTL;
135 SYSCTL_INT(_net_inet_ip, IPCTL_DEFTTL, ttl, CTLFLAG_RW,
136 &ip_defttl, 0, "Maximum TTL on IP packets");
138 static int ip_dosourceroute = 0;
139 SYSCTL_INT(_net_inet_ip, IPCTL_SOURCEROUTE, sourceroute, CTLFLAG_RW,
140 &ip_dosourceroute, 0, "Enable forwarding source routed IP packets");
142 static int ip_acceptsourceroute = 0;
143 SYSCTL_INT(_net_inet_ip, IPCTL_ACCEPTSOURCEROUTE, accept_sourceroute,
144 CTLFLAG_RW, &ip_acceptsourceroute, 0,
145 "Enable accepting source routed IP packets");
148 SYSCTL_INT(_net_inet_ip, OID_AUTO, maxfragpackets, CTLFLAG_RW,
150 "Maximum number of IPv4 fragment reassembly queue entries");
152 static int maxfragsperpacket;
153 SYSCTL_INT(_net_inet_ip, OID_AUTO, maxfragsperpacket, CTLFLAG_RW,
154 &maxfragsperpacket, 0,
155 "Maximum number of IPv4 fragments allowed per packet");
157 static int ip_sendsourcequench = 0;
158 SYSCTL_INT(_net_inet_ip, OID_AUTO, sendsourcequench, CTLFLAG_RW,
159 &ip_sendsourcequench, 0,
160 "Enable the transmission of source quench packets");
162 int ip_do_randomid = 1;
163 SYSCTL_INT(_net_inet_ip, OID_AUTO, random_id, CTLFLAG_RW,
165 "Assign random ip_id values");
167 * XXX - Setting ip_checkinterface mostly implements the receive side of
168 * the Strong ES model described in RFC 1122, but since the routing table
169 * and transmit implementation do not implement the Strong ES model,
170 * setting this to 1 results in an odd hybrid.
172 * XXX - ip_checkinterface currently must be disabled if you use ipnat
173 * to translate the destination address to another local interface.
175 * XXX - ip_checkinterface must be disabled if you add IP aliases
176 * to the loopback interface instead of the interface where the
177 * packets for those addresses are received.
179 static int ip_checkinterface = 0;
180 SYSCTL_INT(_net_inet_ip, OID_AUTO, check_interface, CTLFLAG_RW,
181 &ip_checkinterface, 0, "Verify packet arrives on correct interface");
183 static u_long ip_hash_count = 0;
184 SYSCTL_ULONG(_net_inet_ip, OID_AUTO, hash_count, CTLFLAG_RD,
185 &ip_hash_count, 0, "Number of packets hashed by IP");
188 static u_long ip_rehash_count = 0;
189 SYSCTL_ULONG(_net_inet_ip, OID_AUTO, rehash_count, CTLFLAG_RD,
190 &ip_rehash_count, 0, "Number of packets rehashed by IP");
192 static u_long ip_dispatch_fast = 0;
193 SYSCTL_ULONG(_net_inet_ip, OID_AUTO, dispatch_fast_count, CTLFLAG_RD,
194 &ip_dispatch_fast, 0, "Number of packets handled on current CPU");
196 static u_long ip_dispatch_slow = 0;
197 SYSCTL_ULONG(_net_inet_ip, OID_AUTO, dispatch_slow_count, CTLFLAG_RD,
198 &ip_dispatch_slow, 0, "Number of packets messaged to another CPU");
202 static int ipprintfs = 0;
205 extern struct domain inetdomain;
206 extern struct protosw inetsw[];
207 u_char ip_protox[IPPROTO_MAX];
208 struct in_ifaddrhead in_ifaddrheads[MAXCPU]; /* first inet address */
209 struct in_ifaddrhashhead *in_ifaddrhashtbls[MAXCPU];
210 /* inet addr hash table */
211 u_long in_ifaddrhmask; /* mask for hash table */
213 static struct mbuf *ipforward_mtemp[MAXCPU];
215 struct ip_stats ipstats_percpu[MAXCPU] __cachealign;
218 sysctl_ipstats(SYSCTL_HANDLER_ARGS)
222 for (cpu = 0; cpu < netisr_ncpus; ++cpu) {
223 if ((error = SYSCTL_OUT(req, &ipstats_percpu[cpu],
224 sizeof(struct ip_stats))))
226 if ((error = SYSCTL_IN(req, &ipstats_percpu[cpu],
227 sizeof(struct ip_stats))))
233 SYSCTL_PROC(_net_inet_ip, IPCTL_STATS, stats, (CTLTYPE_OPAQUE | CTLFLAG_RW),
234 0, 0, sysctl_ipstats, "S,ip_stats", "IP statistics");
236 /* Packet reassembly stuff */
237 #define IPREASS_NHASH_LOG2 6
238 #define IPREASS_NHASH (1 << IPREASS_NHASH_LOG2)
239 #define IPREASS_HMASK (IPREASS_NHASH - 1)
240 #define IPREASS_HASH(x,y) \
241 (((((x) & 0xF) | ((((x) >> 8) & 0xF) << 4)) ^ (y)) & IPREASS_HMASK)
243 TAILQ_HEAD(ipqhead, ipq);
244 struct ipfrag_queue {
246 volatile int draining;
247 struct netmsg_base timeo_netmsg;
248 struct callout timeo_ch;
249 struct netmsg_base drain_netmsg;
250 struct ipqhead ipq[IPREASS_NHASH];
253 static struct ipfrag_queue ipfrag_queue_pcpu[MAXCPU];
256 SYSCTL_INT(_net_inet_ip, IPCTL_DEFMTU, mtu, CTLFLAG_RW,
257 &ip_mtu, 0, "Default MTU");
261 static int ipstealth = 0;
262 SYSCTL_INT(_net_inet_ip, OID_AUTO, stealth, CTLFLAG_RW, &ipstealth, 0, "");
264 static const int ipstealth = 0;
267 struct mbuf *(*ip_divert_p)(struct mbuf *, int, int);
269 struct pfil_head inet_pfil_hook;
272 * struct ip_srcrt_opt is used to store packet state while it travels
275 * XXX Note that the code even makes assumptions on the size and
276 * alignment of fields inside struct ip_srcrt so e.g. adding some
277 * fields will break the code. This needs to be fixed.
279 * We need to save the IP options in case a protocol wants to respond
280 * to an incoming packet over the same route if the packet got here
281 * using IP source routing. This allows connection establishment and
282 * maintenance when the remote end is on a network that is not known
286 struct in_addr dst; /* final destination */
287 char nop; /* one NOP to align */
288 char srcopt[IPOPT_OFFSET + 1]; /* OPTVAL, OLEN and OFFSET */
289 struct in_addr route[MAX_IPOPTLEN/sizeof(struct in_addr)];
292 struct ip_srcrt_opt {
294 struct ip_srcrt ip_srcrt;
297 #define IPFRAG_MPIPE_MAX 4096
298 #define MAXIPFRAG_MIN ((IPFRAG_MPIPE_MAX * 2) / 256)
300 #define IPFRAG_TIMEO (hz / PR_SLOWHZ)
302 static MALLOC_DEFINE(M_IPQ, "ipq", "IP Fragment Management");
303 static struct malloc_pipe ipq_mpipe;
305 static void save_rte(struct mbuf *, u_char *, struct in_addr);
306 static int ip_dooptions(struct mbuf *m, int, struct sockaddr_in *);
307 static void ip_freef(struct ipfrag_queue *, struct ipqhead *,
309 static void ip_input_handler(netmsg_t);
311 static void ipfrag_timeo_dispatch(netmsg_t);
312 static void ipfrag_timeo(void *);
313 static void ipfrag_drain_dispatch(netmsg_t);
316 * IP initialization: fill in IP protocol switch table.
317 * All protocols not implemented in kernel go to raw IP protocol handler.
322 struct ipfrag_queue *fragq;
327 * Make sure we can handle a reasonable number of fragments but
328 * cap it at IPFRAG_MPIPE_MAX.
330 mpipe_init(&ipq_mpipe, M_IPQ, sizeof(struct ipq),
331 IFQ_MAXLEN, IPFRAG_MPIPE_MAX, 0, NULL, NULL, NULL);
334 * Make in_ifaddrhead and in_ifaddrhashtbl available on all CPUs,
335 * since they could be accessed by any threads.
337 for (cpu = 0; cpu < ncpus; ++cpu) {
338 TAILQ_INIT(&in_ifaddrheads[cpu]);
339 in_ifaddrhashtbls[cpu] =
340 hashinit(INADDR_NHASH, M_IFADDR, &in_ifaddrhmask);
343 pr = pffindproto(PF_INET, IPPROTO_RAW, SOCK_RAW);
346 for (i = 0; i < IPPROTO_MAX; i++)
347 ip_protox[i] = pr - inetsw;
348 for (pr = inetdomain.dom_protosw;
349 pr < inetdomain.dom_protoswNPROTOSW; pr++) {
350 if (pr->pr_domain->dom_family == PF_INET && pr->pr_protocol) {
351 if (pr->pr_protocol != IPPROTO_RAW)
352 ip_protox[pr->pr_protocol] = pr - inetsw;
356 inet_pfil_hook.ph_type = PFIL_TYPE_AF;
357 inet_pfil_hook.ph_af = AF_INET;
358 if ((i = pfil_head_register(&inet_pfil_hook)) != 0) {
359 kprintf("%s: WARNING: unable to register pfil hook, "
360 "error %d\n", __func__, i);
363 maxnipq = (nmbclusters / 32) / netisr_ncpus;
364 if (maxnipq < MAXIPFRAG_MIN)
365 maxnipq = MAXIPFRAG_MIN;
366 maxfragsperpacket = 16;
368 ip_id = time_second & 0xffff; /* time_second survives reboots */
370 for (cpu = 0; cpu < netisr_ncpus; ++cpu) {
372 * Initialize IP statistics counters for each CPU.
374 bzero(&ipstats_percpu[cpu], sizeof(struct ip_stats));
377 * Preallocate mbuf template for forwarding
379 MGETHDR(ipforward_mtemp[cpu], M_WAITOK, MT_DATA);
382 * Initialize per-cpu ip fragments queues
384 fragq = &ipfrag_queue_pcpu[cpu];
385 for (i = 0; i < IPREASS_NHASH; i++)
386 TAILQ_INIT(&fragq->ipq[i]);
388 callout_init_mp(&fragq->timeo_ch);
389 netmsg_init(&fragq->timeo_netmsg, NULL, &netisr_adone_rport,
390 MSGF_PRIORITY, ipfrag_timeo_dispatch);
391 netmsg_init(&fragq->drain_netmsg, NULL, &netisr_adone_rport,
392 MSGF_PRIORITY, ipfrag_drain_dispatch);
395 netisr_register(NETISR_IP, ip_input_handler, ip_hashfn);
396 netisr_register_hashcheck(NETISR_IP, ip_hashcheck);
398 for (cpu = 0; cpu < netisr_ncpus; ++cpu) {
399 fragq = &ipfrag_queue_pcpu[cpu];
400 callout_reset_bycpu(&fragq->timeo_ch, IPFRAG_TIMEO,
401 ipfrag_timeo, NULL, cpu);
404 ip_porthash_trycount = 2 * netisr_ncpus;
407 /* Do transport protocol processing. */
409 transport_processing_oncpu(struct mbuf *m, int hlen, struct ip *ip)
411 const struct protosw *pr = &inetsw[ip_protox[ip->ip_p]];
414 * Switch out to protocol's input routine.
417 pr->pr_input(&m, &hlen, ip->ip_p);
422 transport_processing_handler(netmsg_t msg)
424 struct netmsg_packet *pmsg = &msg->packet;
428 ip = mtod(pmsg->nm_packet, struct ip *);
429 hlen = pmsg->base.lmsg.u.ms_result;
431 transport_processing_oncpu(pmsg->nm_packet, hlen, ip);
432 /* msg was embedded in the mbuf, do not reply! */
436 ip_input_handler(netmsg_t msg)
438 ip_input(msg->packet.nm_packet);
439 /* msg was embedded in the mbuf, do not reply! */
443 * IP input routine. Checksum and byte swap header. If fragmented
444 * try to reassemble. Process options. Pass to next level.
447 ip_input(struct mbuf *m)
450 struct in_ifaddr *ia = NULL;
451 struct in_ifaddr_container *iac;
454 struct in_addr pkt_dst;
455 boolean_t using_srcrt = FALSE; /* forward (by PFIL_HOOKS) */
456 struct in_addr odst; /* original dst address(NAT) */
458 struct sockaddr_in *next_hop = NULL;
461 ASSERT_NETISR_NCPUS(mycpuid);
464 /* length checks already done in ip_hashfn() */
465 KASSERT(m->m_len >= sizeof(struct ip), ("IP header not in one mbuf"));
468 * This routine is called from numerous places which may not have
469 * characterized the packet.
471 ip = mtod(m, struct ip *);
472 if (IN_MULTICAST(ntohl(ip->ip_dst.s_addr)) ||
473 (ntohs(ip->ip_off) & (IP_MF | IP_OFFMASK))) {
475 * Force hash recalculation for fragments and multicast
476 * packets; hardware may not do it correctly.
477 * XXX add flag to indicate the hash is from hardware
479 m->m_flags &= ~M_HASH;
481 if ((m->m_flags & M_HASH) == 0) {
485 KKASSERT(m->m_flags & M_HASH);
487 if (&curthread->td_msgport !=
488 netisr_hashport(m->m_pkthdr.hash)) {
489 netisr_queue(NETISR_IP, m);
490 /* Requeued to other netisr msgport; done */
494 /* mbuf could have been changed */
495 ip = mtod(m, struct ip *);
499 * Pull out certain tags
501 if (m->m_pkthdr.fw_flags & IPFORWARD_MBUF_TAGGED) {
503 mtag = m_tag_find(m, PACKET_TAG_IPFORWARD, NULL);
504 KKASSERT(mtag != NULL);
505 next_hop = m_tag_data(mtag);
508 if (m->m_pkthdr.fw_flags &
509 (DUMMYNET_MBUF_TAGGED | IPFW_MBUF_CONTINUE)) {
511 * - Dummynet already filtered this packet.
512 * - This packet was processed by ipfw on another
513 * cpu, and the rest of the ipfw processing should
514 * be carried out on this cpu.
516 ip = mtod(m, struct ip *);
517 ip->ip_len = ntohs(ip->ip_len);
518 ip->ip_off = ntohs(ip->ip_off);
519 hlen = IP_VHL_HL(ip->ip_vhl) << 2;
525 if (IP_VHL_V(ip->ip_vhl) != IPVERSION) {
526 ipstat.ips_badvers++;
530 hlen = IP_VHL_HL(ip->ip_vhl) << 2;
531 /* length checks already done in ip_hashfn() */
532 KASSERT(hlen >= sizeof(struct ip), ("IP header len too small"));
533 KASSERT(m->m_len >= hlen, ("complete IP header not in one mbuf"));
535 /* 127/8 must not appear on wire - RFC1122 */
536 if ((ntohl(ip->ip_dst.s_addr) >> IN_CLASSA_NSHIFT) == IN_LOOPBACKNET ||
537 (ntohl(ip->ip_src.s_addr) >> IN_CLASSA_NSHIFT) == IN_LOOPBACKNET) {
538 if (!(m->m_pkthdr.rcvif->if_flags & IFF_LOOPBACK)) {
539 ipstat.ips_badaddr++;
544 if (m->m_pkthdr.csum_flags & CSUM_IP_CHECKED) {
545 sum = !(m->m_pkthdr.csum_flags & CSUM_IP_VALID);
547 if (hlen == sizeof(struct ip))
548 sum = in_cksum_hdr(ip);
550 sum = in_cksum(m, hlen);
558 if (altq_input != NULL && (*altq_input)(m, AF_INET) == 0) {
559 /* packet is dropped by traffic conditioner */
564 * Convert fields to host representation.
566 ip->ip_len = ntohs(ip->ip_len);
567 ip->ip_off = ntohs(ip->ip_off);
569 /* length checks already done in ip_hashfn() */
570 KASSERT(ip->ip_len >= hlen, ("total length less then header length"));
571 KASSERT(m->m_pkthdr.len >= ip->ip_len, ("mbuf too short"));
574 * Trim mbufs if longer than the IP header would have us expect.
576 if (m->m_pkthdr.len > ip->ip_len) {
577 if (m->m_len == m->m_pkthdr.len) {
578 m->m_len = ip->ip_len;
579 m->m_pkthdr.len = ip->ip_len;
581 m_adj(m, ip->ip_len - m->m_pkthdr.len);
587 * Right now when no processing on packet has done
588 * and it is still fresh out of network we do our black
590 * - Firewall: deny/allow/divert
591 * - Xlate: translate packet's addr/port (NAT).
592 * - Pipe: pass pkt through dummynet.
593 * - Wrap: fake packet's addr/port <unimpl.>
594 * - Encapsulate: put it in another IP and send out. <unimp.>
599 * If we've been forwarded from the output side, then
600 * skip the firewall a second time
602 if (next_hop != NULL)
606 if (!pfil_has_hooks(&inet_pfil_hook)) {
607 if (m->m_pkthdr.fw_flags & DUMMYNET_MBUF_TAGGED) {
609 * Strip dummynet tags from stranded packets
611 mtag = m_tag_find(m, PACKET_TAG_DUMMYNET, NULL);
612 KKASSERT(mtag != NULL);
613 m_tag_delete(m, mtag);
614 m->m_pkthdr.fw_flags &= ~DUMMYNET_MBUF_TAGGED;
620 * Run through list of hooks for input packets.
622 * NOTE! If the packet is rewritten pf/ipfw/whoever must
626 if (pfil_run_hooks(&inet_pfil_hook, &m, m->m_pkthdr.rcvif, PFIL_IN))
628 if (m == NULL) /* consumed by filter */
630 ip = mtod(m, struct ip *);
631 hlen = IP_VHL_HL(ip->ip_vhl) << 2;
632 using_srcrt = (odst.s_addr != ip->ip_dst.s_addr);
634 if (m->m_pkthdr.fw_flags & IPFORWARD_MBUF_TAGGED) {
635 mtag = m_tag_find(m, PACKET_TAG_IPFORWARD, NULL);
636 KKASSERT(mtag != NULL);
637 next_hop = m_tag_data(mtag);
639 if (m->m_pkthdr.fw_flags & DUMMYNET_MBUF_TAGGED) {
643 if (m->m_pkthdr.fw_flags & FW_MBUF_REDISPATCH)
644 m->m_pkthdr.fw_flags &= ~FW_MBUF_REDISPATCH;
645 if (m->m_pkthdr.fw_flags & IPFW_MBUF_CONTINUE) {
646 /* ipfw was disabled/unloaded. */
651 * Process options and, if not destined for us,
652 * ship it on. ip_dooptions returns 1 when an
653 * error was detected (causing an icmp message
654 * to be sent and the original packet to be freed).
656 if (hlen > sizeof(struct ip) && ip_dooptions(m, 0, next_hop))
659 /* greedy RSVP, snatches any PATH packet of the RSVP protocol and no
660 * matter if it is destined to another node, or whether it is
661 * a multicast one, RSVP wants it! and prevents it from being forwarded
662 * anywhere else. Also checks if the rsvp daemon is running before
663 * grabbing the packet.
665 if (rsvp_on && ip->ip_p == IPPROTO_RSVP)
669 * Check our list of addresses, to see if the packet is for us.
670 * If we don't have any addresses, assume any unicast packet
671 * we receive might be for us (and let the upper layers deal
674 if (TAILQ_EMPTY(&in_ifaddrheads[mycpuid]) &&
675 !(m->m_flags & (M_MCAST | M_BCAST)))
679 * Cache the destination address of the packet; this may be
680 * changed by use of 'ipfw fwd'.
682 pkt_dst = next_hop ? next_hop->sin_addr : ip->ip_dst;
685 * Enable a consistency check between the destination address
686 * and the arrival interface for a unicast packet (the RFC 1122
687 * strong ES model) if IP forwarding is disabled and the packet
688 * is not locally generated and the packet is not subject to
691 * XXX - Checking also should be disabled if the destination
692 * address is ipnat'ed to a different interface.
694 * XXX - Checking is incompatible with IP aliases added
695 * to the loopback interface instead of the interface where
696 * the packets are received.
698 checkif = ip_checkinterface &&
700 m->m_pkthdr.rcvif != NULL &&
701 !(m->m_pkthdr.rcvif->if_flags & IFF_LOOPBACK) &&
705 * Check for exact addresses in the hash bucket.
707 LIST_FOREACH(iac, INADDR_HASH(pkt_dst.s_addr), ia_hash) {
711 * If the address matches, verify that the packet
712 * arrived via the correct interface if checking is
715 if (IA_SIN(ia)->sin_addr.s_addr == pkt_dst.s_addr &&
716 (!checkif || ia->ia_ifp == m->m_pkthdr.rcvif))
722 * Check for broadcast addresses.
724 * Only accept broadcast packets that arrive via the matching
725 * interface. Reception of forwarded directed broadcasts would
726 * be handled via ip_forward() and ether_output() with the loopback
727 * into the stack for SIMPLEX interfaces handled by ether_output().
729 if (m->m_pkthdr.rcvif != NULL &&
730 m->m_pkthdr.rcvif->if_flags & IFF_BROADCAST) {
731 struct ifaddr_container *ifac;
733 TAILQ_FOREACH(ifac, &m->m_pkthdr.rcvif->if_addrheads[mycpuid],
735 struct ifaddr *ifa = ifac->ifa;
737 if (ifa->ifa_addr == NULL) /* shutdown/startup race */
739 if (ifa->ifa_addr->sa_family != AF_INET)
742 if (satosin(&ia->ia_broadaddr)->sin_addr.s_addr ==
745 if (ia->ia_netbroadcast.s_addr == pkt_dst.s_addr)
748 if (IA_SIN(ia)->sin_addr.s_addr == INADDR_ANY)
753 if (IN_MULTICAST(ntohl(ip->ip_dst.s_addr))) {
754 struct in_multi *inm;
756 if (ip_mrouter != NULL) {
757 /* XXX Multicast routing is not MPSAFE yet */
761 * If we are acting as a multicast router, all
762 * incoming multicast packets are passed to the
763 * kernel-level multicast forwarding function.
764 * The packet is returned (relatively) intact; if
765 * ip_mforward() returns a non-zero value, the packet
766 * must be discarded, else it may be accepted below.
768 if (ip_mforward != NULL &&
769 ip_mforward(ip, m->m_pkthdr.rcvif, m, NULL) != 0) {
771 ipstat.ips_cantforward++;
779 * The process-level routing daemon needs to receive
780 * all multicast IGMP packets, whether or not this
781 * host belongs to their destination groups.
783 if (ip->ip_p == IPPROTO_IGMP)
785 ipstat.ips_forward++;
788 * See if we belong to the destination multicast group on the
791 inm = IN_LOOKUP_MULTI(&ip->ip_dst, m->m_pkthdr.rcvif);
793 ipstat.ips_notmember++;
799 if (ip->ip_dst.s_addr == INADDR_BROADCAST)
801 if (ip->ip_dst.s_addr == INADDR_ANY)
805 * Not for us; forward if possible and desirable.
808 ipstat.ips_cantforward++;
811 ip_forward(m, using_srcrt, next_hop);
818 * IPSTEALTH: Process non-routing options only
819 * if the packet is destined for us.
822 hlen > sizeof(struct ip) &&
823 ip_dooptions(m, 1, next_hop))
826 /* Count the packet in the ip address stats */
828 IFA_STAT_INC(&ia->ia_ifa, ipackets, 1);
829 IFA_STAT_INC(&ia->ia_ifa, ibytes, m->m_pkthdr.len);
833 * If offset or IP_MF are set, must reassemble.
834 * Otherwise, nothing need be done.
835 * (We could look in the reassembly queue to see
836 * if the packet was previously fragmented,
837 * but it's not worth the time; just let them time out.)
839 if (ip->ip_off & (IP_MF | IP_OFFMASK)) {
841 * Attempt reassembly; if it succeeds, proceed. ip_reass()
842 * will return a different mbuf.
844 * NOTE: ip_reass() returns m with M_HASH cleared to force
845 * us to recharacterize the packet.
850 ip = mtod(m, struct ip *);
852 /* Get the header length of the reassembled packet */
853 hlen = IP_VHL_HL(ip->ip_vhl) << 2;
859 * We must forward the packet to the correct protocol thread if
860 * we are not already in it.
862 * NOTE: ip_len is now in host form. ip_len is not adjusted
863 * further for protocol processing, instead we pass hlen
864 * to the protosw and let it deal with it.
866 ipstat.ips_delivered++;
868 if ((m->m_flags & M_HASH) == 0) {
869 m = ip_rehashm(m, hlen);
872 ip = mtod(m, struct ip *);
874 port = netisr_hashport(m->m_pkthdr.hash);
876 if (port != &curthread->td_msgport) {
877 ip_transport_redispatch(port, m, hlen);
880 atomic_add_long(&ip_dispatch_fast, 1);
882 transport_processing_oncpu(m, hlen, ip);
891 ip_rehashm(struct mbuf *m, int hlen)
893 struct ip *ip = mtod(m, struct ip *);
896 atomic_add_long(&ip_rehash_count, 1);
898 ip->ip_len = htons(ip->ip_len + hlen);
899 ip->ip_off = htons(ip->ip_off);
905 /* 'm' might be changed by ip_hashfn(). */
906 ip = mtod(m, struct ip *);
907 ip->ip_len = ntohs(ip->ip_len) - hlen;
908 ip->ip_off = ntohs(ip->ip_off);
909 KASSERT(m->m_flags & M_HASH, ("no hash"));
915 ip_transport_redispatch(struct lwkt_port *port, struct mbuf *m, int hlen)
917 struct netmsg_packet *pmsg;
920 atomic_add_long(&ip_dispatch_slow, 1);
923 pmsg = &m->m_hdr.mh_netmsg;
924 netmsg_init(&pmsg->base, NULL, &netisr_apanic_rport,
925 0, transport_processing_handler);
927 pmsg->base.lmsg.u.ms_result = hlen;
928 lwkt_sendmsg(port, &pmsg->base.lmsg);
932 * Take incoming datagram fragment and try to reassemble it into
933 * whole datagram. If a chain for reassembly of this datagram already
934 * exists, then it is given as fp; otherwise have to make a chain.
937 ip_reass(struct mbuf *m)
939 struct ipfrag_queue *fragq = &ipfrag_queue_pcpu[mycpuid];
940 struct ip *ip = mtod(m, struct ip *);
941 struct mbuf *p = NULL, *q, *nq;
943 struct ipq *fp = NULL;
944 struct ipqhead *head;
945 int hlen = IP_VHL_HL(ip->ip_vhl) << 2;
949 /* If maxnipq or maxfragsperpacket are 0, never accept fragments. */
950 if (maxnipq == 0 || maxfragsperpacket == 0) {
951 ipstat.ips_fragments++;
952 ipstat.ips_fragdropped++;
957 sum = IPREASS_HASH(ip->ip_src.s_addr, ip->ip_id);
959 * Look for queue of fragments of this datagram.
961 head = &fragq->ipq[sum];
962 TAILQ_FOREACH(fp, head, ipq_list) {
963 if (ip->ip_id == fp->ipq_id &&
964 ip->ip_src.s_addr == fp->ipq_src.s_addr &&
965 ip->ip_dst.s_addr == fp->ipq_dst.s_addr &&
966 ip->ip_p == fp->ipq_p)
973 * Enforce upper bound on number of fragmented packets
974 * for which we attempt reassembly;
975 * If maxnipq is -1, accept all fragments without limitation.
977 if (fragq->nipq > maxnipq && maxnipq > 0) {
979 * drop something from the tail of the current queue
980 * before proceeding further
982 struct ipq *q = TAILQ_LAST(head, ipqhead);
985 * The current queue is empty,
986 * so drop from one of the others.
988 for (i = 0; i < IPREASS_NHASH; i++) {
989 struct ipq *r = TAILQ_LAST(&fragq->ipq[i],
992 ipstat.ips_fragtimeout += r->ipq_nfrags;
993 ip_freef(fragq, &fragq->ipq[i], r);
998 ipstat.ips_fragtimeout += q->ipq_nfrags;
999 ip_freef(fragq, head, q);
1004 * Adjust ip_len to not reflect header,
1005 * convert offset of this to bytes.
1008 if (ip->ip_off & IP_MF) {
1010 * Make sure that fragments have a data length
1011 * that's a non-zero multiple of 8 bytes.
1013 if (ip->ip_len == 0 || (ip->ip_len & 0x7) != 0) {
1014 ipstat.ips_toosmall++; /* XXX */
1018 m->m_flags |= M_FRAG;
1020 m->m_flags &= ~M_FRAG;
1024 ipstat.ips_fragments++;
1025 m->m_pkthdr.header = ip;
1028 * If the hardware has not done csum over this fragment
1029 * then csum_data is not valid at all.
1031 if ((m->m_pkthdr.csum_flags & (CSUM_FRAG_NOT_CHECKED | CSUM_DATA_VALID))
1032 == (CSUM_FRAG_NOT_CHECKED | CSUM_DATA_VALID)) {
1033 m->m_pkthdr.csum_data = 0;
1034 m->m_pkthdr.csum_flags &= ~(CSUM_DATA_VALID | CSUM_PSEUDO_HDR);
1038 * Presence of header sizes in mbufs
1039 * would confuse code below.
1045 * If first fragment to arrive, create a reassembly queue.
1048 if ((fp = mpipe_alloc_nowait(&ipq_mpipe)) == NULL)
1050 TAILQ_INSERT_HEAD(head, fp, ipq_list);
1053 fp->ipq_ttl = IPFRAGTTL;
1054 fp->ipq_p = ip->ip_p;
1055 fp->ipq_id = ip->ip_id;
1056 fp->ipq_src = ip->ip_src;
1057 fp->ipq_dst = ip->ip_dst;
1059 m->m_nextpkt = NULL;
1064 #define GETIP(m) ((struct ip*)((m)->m_pkthdr.header))
1067 * Find a segment which begins after this one does.
1069 for (p = NULL, q = fp->ipq_frags; q; p = q, q = q->m_nextpkt) {
1070 if (GETIP(q)->ip_off > ip->ip_off)
1075 * If there is a preceding segment, it may provide some of
1076 * our data already. If so, drop the data from the incoming
1077 * segment. If it provides all of our data, drop us, otherwise
1078 * stick new segment in the proper place.
1080 * If some of the data is dropped from the the preceding
1081 * segment, then it's checksum is invalidated.
1084 i = GETIP(p)->ip_off + GETIP(p)->ip_len - ip->ip_off;
1086 if (i >= ip->ip_len)
1089 m->m_pkthdr.csum_flags = 0;
1093 m->m_nextpkt = p->m_nextpkt;
1096 m->m_nextpkt = fp->ipq_frags;
1101 * While we overlap succeeding segments trim them or,
1102 * if they are completely covered, dequeue them.
1104 for (; q != NULL && ip->ip_off + ip->ip_len > GETIP(q)->ip_off;
1106 i = (ip->ip_off + ip->ip_len) - GETIP(q)->ip_off;
1107 if (i < GETIP(q)->ip_len) {
1108 GETIP(q)->ip_len -= i;
1109 GETIP(q)->ip_off += i;
1111 q->m_pkthdr.csum_flags = 0;
1116 ipstat.ips_fragdropped++;
1118 q->m_nextpkt = NULL;
1124 * Check for complete reassembly and perform frag per packet
1127 * Frag limiting is performed here so that the nth frag has
1128 * a chance to complete the packet before we drop the packet.
1129 * As a result, n+1 frags are actually allowed per packet, but
1130 * only n will ever be stored. (n = maxfragsperpacket.)
1134 for (p = NULL, q = fp->ipq_frags; q; p = q, q = q->m_nextpkt) {
1135 if (GETIP(q)->ip_off != next) {
1136 if (fp->ipq_nfrags > maxfragsperpacket) {
1137 ipstat.ips_fragdropped += fp->ipq_nfrags;
1138 ip_freef(fragq, head, fp);
1142 next += GETIP(q)->ip_len;
1144 /* Make sure the last packet didn't have the IP_MF flag */
1145 if (p->m_flags & M_FRAG) {
1146 if (fp->ipq_nfrags > maxfragsperpacket) {
1147 ipstat.ips_fragdropped += fp->ipq_nfrags;
1148 ip_freef(fragq, head, fp);
1154 * Reassembly is complete. Make sure the packet is a sane size.
1158 if (next + (IP_VHL_HL(ip->ip_vhl) << 2) > IP_MAXPACKET) {
1159 ipstat.ips_toolong++;
1160 ipstat.ips_fragdropped += fp->ipq_nfrags;
1161 ip_freef(fragq, head, fp);
1166 * Concatenate fragments.
1173 q->m_nextpkt = NULL;
1174 for (q = nq; q != NULL; q = nq) {
1176 q->m_nextpkt = NULL;
1177 m->m_pkthdr.csum_flags &= q->m_pkthdr.csum_flags;
1178 m->m_pkthdr.csum_data += q->m_pkthdr.csum_data;
1183 * Clean up the 1's complement checksum. Carry over 16 bits must
1184 * be added back. This assumes no more then 65535 packet fragments
1185 * were reassembled. A second carry can also occur (but not a third).
1187 m->m_pkthdr.csum_data = (m->m_pkthdr.csum_data & 0xffff) +
1188 (m->m_pkthdr.csum_data >> 16);
1189 if (m->m_pkthdr.csum_data > 0xFFFF)
1190 m->m_pkthdr.csum_data -= 0xFFFF;
1193 * Create header for new ip packet by
1194 * modifying header of first packet;
1195 * dequeue and discard fragment reassembly header.
1196 * Make header visible.
1199 ip->ip_src = fp->ipq_src;
1200 ip->ip_dst = fp->ipq_dst;
1201 TAILQ_REMOVE(head, fp, ipq_list);
1203 mpipe_free(&ipq_mpipe, fp);
1204 m->m_len += (IP_VHL_HL(ip->ip_vhl) << 2);
1205 m->m_data -= (IP_VHL_HL(ip->ip_vhl) << 2);
1206 /* some debugging cruft by sklower, below, will go away soon */
1207 if (m->m_flags & M_PKTHDR) { /* XXX this should be done elsewhere */
1210 for (n = m; n; n = n->m_next)
1212 m->m_pkthdr.len = plen;
1216 * Reassembly complete, return the next protocol.
1218 * Be sure to clear M_HASH to force the packet
1219 * to be re-characterized.
1221 * Clear M_FRAG, we are no longer a fragment.
1223 m->m_flags &= ~(M_HASH | M_FRAG);
1225 ipstat.ips_reassembled++;
1229 ipstat.ips_fragdropped++;
1240 * Free a fragment reassembly header and all
1241 * associated datagrams.
1244 ip_freef(struct ipfrag_queue *fragq, struct ipqhead *fhp, struct ipq *fp)
1249 * Remove first to protect against blocking
1251 TAILQ_REMOVE(fhp, fp, ipq_list);
1254 * Clean out at our leisure
1256 while (fp->ipq_frags) {
1258 fp->ipq_frags = q->m_nextpkt;
1259 q->m_nextpkt = NULL;
1262 mpipe_free(&ipq_mpipe, fp);
1267 * If a timer expires on a reassembly queue, discard it.
1270 ipfrag_timeo_dispatch(netmsg_t nmsg)
1272 struct ipfrag_queue *fragq = &ipfrag_queue_pcpu[mycpuid];
1273 struct ipq *fp, *fp_temp;
1274 struct ipqhead *head;
1278 netisr_replymsg(&nmsg->base, 0); /* reply ASAP */
1281 if (fragq->nipq == 0)
1284 for (i = 0; i < IPREASS_NHASH; i++) {
1285 head = &fragq->ipq[i];
1286 TAILQ_FOREACH_MUTABLE(fp, head, ipq_list, fp_temp) {
1287 if (--fp->ipq_ttl == 0) {
1288 ipstat.ips_fragtimeout += fp->ipq_nfrags;
1289 ip_freef(fragq, head, fp);
1294 * If we are over the maximum number of fragments
1295 * (due to the limit being lowered), drain off
1296 * enough to get down to the new limit.
1298 if (maxnipq >= 0 && fragq->nipq > maxnipq) {
1299 for (i = 0; i < IPREASS_NHASH; i++) {
1300 head = &fragq->ipq[i];
1301 while (fragq->nipq > maxnipq && !TAILQ_EMPTY(head)) {
1302 ipstat.ips_fragdropped +=
1303 TAILQ_FIRST(head)->ipq_nfrags;
1304 ip_freef(fragq, head, TAILQ_FIRST(head));
1309 callout_reset(&fragq->timeo_ch, IPFRAG_TIMEO, ipfrag_timeo, NULL);
1313 ipfrag_timeo(void *dummy __unused)
1315 struct netmsg_base *msg = &ipfrag_queue_pcpu[mycpuid].timeo_netmsg;
1318 if (msg->lmsg.ms_flags & MSGF_DONE)
1319 netisr_sendmsg_oncpu(msg);
1324 * Drain off all datagram fragments.
1327 ipfrag_drain_oncpu(struct ipfrag_queue *fragq)
1329 struct ipqhead *head;
1332 for (i = 0; i < IPREASS_NHASH; i++) {
1333 head = &fragq->ipq[i];
1334 while (!TAILQ_EMPTY(head)) {
1335 ipstat.ips_fragdropped += TAILQ_FIRST(head)->ipq_nfrags;
1336 ip_freef(fragq, head, TAILQ_FIRST(head));
1342 ipfrag_drain_dispatch(netmsg_t nmsg)
1344 struct ipfrag_queue *fragq = &ipfrag_queue_pcpu[mycpuid];
1347 lwkt_replymsg(&nmsg->lmsg, 0); /* reply ASAP */
1350 ipfrag_drain_oncpu(fragq);
1351 fragq->draining = 0;
1355 ipfrag_drain_ipi(void *arg __unused)
1358 struct lwkt_msg *msg = &ipfrag_queue_pcpu[cpu].drain_netmsg.lmsg;
1361 if (msg->ms_flags & MSGF_DONE)
1362 lwkt_sendmsg_oncpu(netisr_cpuport(cpu), msg);
1372 CPUMASK_ASSBMASK(mask, netisr_ncpus);
1373 CPUMASK_ANDMASK(mask, smp_active_mask);
1375 if (IN_NETISR_NCPUS(mycpuid)) {
1376 ipfrag_drain_oncpu(&ipfrag_queue_pcpu[mycpuid]);
1377 CPUMASK_NANDBIT(mask, mycpuid);
1380 for (cpu = 0; cpu < netisr_ncpus; ++cpu) {
1381 struct ipfrag_queue *fragq = &ipfrag_queue_pcpu[cpu];
1383 if (!CPUMASK_TESTBIT(mask, cpu))
1386 if (fragq->nipq == 0 || fragq->draining) {
1387 /* No fragments or is draining; skip this cpu. */
1388 CPUMASK_NANDBIT(mask, cpu);
1391 fragq->draining = 1;
1394 if (CPUMASK_TESTNZERO(mask))
1395 lwkt_send_ipiq_mask(mask, ipfrag_drain_ipi, NULL);
1406 * Do option processing on a datagram,
1407 * possibly discarding it if bad options are encountered,
1408 * or forwarding it if source-routed.
1409 * The pass argument is used when operating in the IPSTEALTH
1410 * mode to tell what options to process:
1411 * [LS]SRR (pass 0) or the others (pass 1).
1412 * The reason for as many as two passes is that when doing IPSTEALTH,
1413 * non-routing options should be processed only if the packet is for us.
1414 * Returns 1 if packet has been forwarded/freed,
1415 * 0 if the packet should be processed further.
1418 ip_dooptions(struct mbuf *m, int pass, struct sockaddr_in *next_hop)
1420 struct sockaddr_in ipaddr = { sizeof ipaddr, AF_INET };
1421 struct ip *ip = mtod(m, struct ip *);
1423 struct in_ifaddr *ia;
1424 int opt, optlen, cnt, off, code, type = ICMP_PARAMPROB;
1425 boolean_t forward = FALSE;
1426 struct in_addr *sin, dst;
1430 cp = (u_char *)(ip + 1);
1431 cnt = (IP_VHL_HL(ip->ip_vhl) << 2) - sizeof(struct ip);
1432 for (; cnt > 0; cnt -= optlen, cp += optlen) {
1433 opt = cp[IPOPT_OPTVAL];
1434 if (opt == IPOPT_EOL)
1436 if (opt == IPOPT_NOP)
1439 if (cnt < IPOPT_OLEN + sizeof(*cp)) {
1440 code = &cp[IPOPT_OLEN] - (u_char *)ip;
1443 optlen = cp[IPOPT_OLEN];
1444 if (optlen < IPOPT_OLEN + sizeof(*cp) || optlen > cnt) {
1445 code = &cp[IPOPT_OLEN] - (u_char *)ip;
1455 * Source routing with record.
1456 * Find interface with current destination address.
1457 * If none on this machine then drop if strictly routed,
1458 * or do nothing if loosely routed.
1459 * Record interface address and bring up next address
1460 * component. If strictly routed make sure next
1461 * address is on directly accessible net.
1465 if (ipstealth && pass > 0)
1467 if (optlen < IPOPT_OFFSET + sizeof(*cp)) {
1468 code = &cp[IPOPT_OLEN] - (u_char *)ip;
1471 if ((off = cp[IPOPT_OFFSET]) < IPOPT_MINOFF) {
1472 code = &cp[IPOPT_OFFSET] - (u_char *)ip;
1475 ipaddr.sin_addr = ip->ip_dst;
1476 ia = (struct in_ifaddr *)
1477 ifa_ifwithaddr((struct sockaddr *)&ipaddr);
1479 if (opt == IPOPT_SSRR) {
1480 type = ICMP_UNREACH;
1481 code = ICMP_UNREACH_SRCFAIL;
1484 if (!ip_dosourceroute)
1485 goto nosourcerouting;
1487 * Loose routing, and not at next destination
1488 * yet; nothing to do except forward.
1492 off--; /* 0 origin */
1493 if (off > optlen - (int)sizeof(struct in_addr)) {
1495 * End of source route. Should be for us.
1497 if (!ip_acceptsourceroute)
1498 goto nosourcerouting;
1499 save_rte(m, cp, ip->ip_src);
1504 if (!ip_dosourceroute) {
1506 char sbuf[INET_ADDRSTRLEN];
1507 char dbuf[INET_ADDRSTRLEN];
1510 * Acting as a router, so generate ICMP
1514 "attempted source route from %s to %s\n",
1515 kinet_ntoa(ip->ip_src, sbuf),
1516 kinet_ntoa(ip->ip_dst, dbuf));
1517 type = ICMP_UNREACH;
1518 code = ICMP_UNREACH_SRCFAIL;
1522 * Not acting as a router,
1526 ipstat.ips_cantforward++;
1533 * locate outgoing interface
1535 memcpy(&ipaddr.sin_addr, cp + off,
1536 sizeof ipaddr.sin_addr);
1538 if (opt == IPOPT_SSRR) {
1539 #define INA struct in_ifaddr *
1540 #define SA struct sockaddr *
1541 if ((ia = (INA)ifa_ifwithdstaddr((SA)&ipaddr))
1543 ia = (INA)ifa_ifwithnet((SA)&ipaddr);
1545 ia = ip_rtaddr(ipaddr.sin_addr, NULL);
1548 type = ICMP_UNREACH;
1549 code = ICMP_UNREACH_SRCFAIL;
1552 ip->ip_dst = ipaddr.sin_addr;
1553 memcpy(cp + off, &IA_SIN(ia)->sin_addr,
1554 sizeof(struct in_addr));
1555 cp[IPOPT_OFFSET] += sizeof(struct in_addr);
1557 * Let ip_intr's mcast routing check handle mcast pkts
1559 forward = !IN_MULTICAST(ntohl(ip->ip_dst.s_addr));
1563 if (ipstealth && pass == 0)
1565 if (optlen < IPOPT_OFFSET + sizeof(*cp)) {
1566 code = &cp[IPOPT_OFFSET] - (u_char *)ip;
1569 if ((off = cp[IPOPT_OFFSET]) < IPOPT_MINOFF) {
1570 code = &cp[IPOPT_OFFSET] - (u_char *)ip;
1574 * If no space remains, ignore.
1576 off--; /* 0 origin */
1577 if (off > optlen - (int)sizeof(struct in_addr))
1579 memcpy(&ipaddr.sin_addr, &ip->ip_dst,
1580 sizeof ipaddr.sin_addr);
1582 * locate outgoing interface; if we're the destination,
1583 * use the incoming interface (should be same).
1585 if ((ia = (INA)ifa_ifwithaddr((SA)&ipaddr)) == NULL &&
1586 (ia = ip_rtaddr(ipaddr.sin_addr, NULL)) == NULL) {
1587 type = ICMP_UNREACH;
1588 code = ICMP_UNREACH_HOST;
1591 memcpy(cp + off, &IA_SIN(ia)->sin_addr,
1592 sizeof(struct in_addr));
1593 cp[IPOPT_OFFSET] += sizeof(struct in_addr);
1597 if (ipstealth && pass == 0)
1599 code = cp - (u_char *)ip;
1600 if (optlen < 4 || optlen > 40) {
1601 code = &cp[IPOPT_OLEN] - (u_char *)ip;
1604 if ((off = cp[IPOPT_OFFSET]) < 5) {
1605 code = &cp[IPOPT_OLEN] - (u_char *)ip;
1608 if (off > optlen - (int)sizeof(int32_t)) {
1609 cp[IPOPT_OFFSET + 1] += (1 << 4);
1610 if ((cp[IPOPT_OFFSET + 1] & 0xf0) == 0) {
1611 code = &cp[IPOPT_OFFSET] - (u_char *)ip;
1616 off--; /* 0 origin */
1617 sin = (struct in_addr *)(cp + off);
1618 switch (cp[IPOPT_OFFSET + 1] & 0x0f) {
1620 case IPOPT_TS_TSONLY:
1623 case IPOPT_TS_TSANDADDR:
1624 if (off + sizeof(n_time) +
1625 sizeof(struct in_addr) > optlen) {
1626 code = &cp[IPOPT_OFFSET] - (u_char *)ip;
1629 ipaddr.sin_addr = dst;
1630 ia = (INA)ifaof_ifpforaddr((SA)&ipaddr,
1634 memcpy(sin, &IA_SIN(ia)->sin_addr,
1635 sizeof(struct in_addr));
1636 cp[IPOPT_OFFSET] += sizeof(struct in_addr);
1637 off += sizeof(struct in_addr);
1640 case IPOPT_TS_PRESPEC:
1641 if (off + sizeof(n_time) +
1642 sizeof(struct in_addr) > optlen) {
1643 code = &cp[IPOPT_OFFSET] - (u_char *)ip;
1646 memcpy(&ipaddr.sin_addr, sin,
1647 sizeof(struct in_addr));
1648 if (ifa_ifwithaddr((SA)&ipaddr) == NULL)
1650 cp[IPOPT_OFFSET] += sizeof(struct in_addr);
1651 off += sizeof(struct in_addr);
1655 code = &cp[IPOPT_OFFSET + 1] - (u_char *)ip;
1659 memcpy(cp + off, &ntime, sizeof(n_time));
1660 cp[IPOPT_OFFSET] += sizeof(n_time);
1663 if (forward && ipforwarding) {
1664 ip_forward(m, TRUE, next_hop);
1669 icmp_error(m, type, code, 0, 0);
1670 ipstat.ips_badoptions++;
1675 * Given address of next destination (final or next hop),
1676 * return internet address info of interface to be used to get there.
1679 ip_rtaddr(struct in_addr dst, struct route *ro0)
1681 struct route sro, *ro;
1682 struct sockaddr_in *sin;
1683 struct in_ifaddr *ia;
1688 bzero(&sro, sizeof(sro));
1692 sin = (struct sockaddr_in *)&ro->ro_dst;
1694 if (ro->ro_rt == NULL || dst.s_addr != sin->sin_addr.s_addr) {
1695 if (ro->ro_rt != NULL) {
1699 sin->sin_family = AF_INET;
1700 sin->sin_len = sizeof *sin;
1701 sin->sin_addr = dst;
1702 rtalloc_ign(ro, RTF_PRCLONING);
1705 if (ro->ro_rt == NULL)
1708 ia = ifatoia(ro->ro_rt->rt_ifa);
1716 * Save incoming source route for use in replies,
1717 * to be picked up later by ip_srcroute if the receiver is interested.
1720 save_rte(struct mbuf *m, u_char *option, struct in_addr dst)
1723 struct ip_srcrt_opt *opt;
1726 mtag = m_tag_get(PACKET_TAG_IPSRCRT, sizeof(*opt), M_NOWAIT);
1729 opt = m_tag_data(mtag);
1731 olen = option[IPOPT_OLEN];
1734 kprintf("save_rte: olen %d\n", olen);
1736 if (olen > sizeof(opt->ip_srcrt) - (1 + sizeof(dst))) {
1740 bcopy(option, opt->ip_srcrt.srcopt, olen);
1741 opt->ip_nhops = (olen - IPOPT_OFFSET - 1) / sizeof(struct in_addr);
1742 opt->ip_srcrt.dst = dst;
1743 m_tag_prepend(m, mtag);
1747 * Retrieve incoming source route for use in replies,
1748 * in the same form used by setsockopt.
1749 * The first hop is placed before the options, will be removed later.
1752 ip_srcroute(struct mbuf *m0)
1754 struct in_addr *p, *q;
1757 struct ip_srcrt_opt *opt;
1762 mtag = m_tag_find(m0, PACKET_TAG_IPSRCRT, NULL);
1765 opt = m_tag_data(mtag);
1767 if (opt->ip_nhops == 0)
1769 m = m_get(M_NOWAIT, MT_HEADER);
1773 #define OPTSIZ (sizeof(opt->ip_srcrt.nop) + sizeof(opt->ip_srcrt.srcopt))
1775 /* length is (nhops+1)*sizeof(addr) + sizeof(nop + srcrt header) */
1776 m->m_len = opt->ip_nhops * sizeof(struct in_addr) +
1777 sizeof(struct in_addr) + OPTSIZ;
1780 kprintf("ip_srcroute: nhops %d mlen %d",
1781 opt->ip_nhops, m->m_len);
1786 * First save first hop for return route
1788 p = &opt->ip_srcrt.route[opt->ip_nhops - 1];
1789 *(mtod(m, struct in_addr *)) = *p--;
1792 kprintf(" hops %x", ntohl(mtod(m, struct in_addr *)->s_addr));
1796 * Copy option fields and padding (nop) to mbuf.
1798 opt->ip_srcrt.nop = IPOPT_NOP;
1799 opt->ip_srcrt.srcopt[IPOPT_OFFSET] = IPOPT_MINOFF;
1800 memcpy(mtod(m, caddr_t) + sizeof(struct in_addr), &opt->ip_srcrt.nop,
1802 q = (struct in_addr *)(mtod(m, caddr_t) +
1803 sizeof(struct in_addr) + OPTSIZ);
1806 * Record return path as an IP source route,
1807 * reversing the path (pointers are now aligned).
1809 while (p >= opt->ip_srcrt.route) {
1812 kprintf(" %x", ntohl(q->s_addr));
1817 * Last hop goes to final destination.
1819 *q = opt->ip_srcrt.dst;
1820 m_tag_delete(m0, mtag);
1823 kprintf(" %x\n", ntohl(q->s_addr));
1829 * Strip out IP options.
1832 ip_stripoptions(struct mbuf *m)
1835 struct ip *ip = mtod(m, struct ip *);
1839 optlen = (IP_VHL_HL(ip->ip_vhl) << 2) - sizeof(struct ip);
1840 opts = (caddr_t)(ip + 1);
1841 datalen = m->m_len - (sizeof(struct ip) + optlen);
1842 bcopy(opts + optlen, opts, datalen);
1844 if (m->m_flags & M_PKTHDR)
1845 m->m_pkthdr.len -= optlen;
1846 ip->ip_vhl = IP_MAKE_VHL(IPVERSION, sizeof(struct ip) >> 2);
1849 u_char inetctlerrmap[PRC_NCMDS] = {
1851 0, EMSGSIZE, EHOSTDOWN, EHOSTUNREACH,
1852 EHOSTUNREACH, EHOSTUNREACH, ECONNREFUSED, ECONNREFUSED,
1853 EMSGSIZE, EHOSTUNREACH, 0, 0,
1855 ENOPROTOOPT, ECONNREFUSED
1859 * Forward a packet. If some error occurs return the sender
1860 * an icmp packet. Note we can't always generate a meaningful
1861 * icmp message because icmp doesn't have a large enough repertoire
1862 * of codes and types.
1864 * If not forwarding, just drop the packet. This could be confusing
1865 * if ipforwarding was zero but some routing protocol was advancing
1866 * us as a gateway to somewhere. However, we must let the routing
1867 * protocol deal with that.
1869 * The using_srcrt parameter indicates whether the packet is being forwarded
1870 * via a source route.
1873 ip_forward(struct mbuf *m, boolean_t using_srcrt, struct sockaddr_in *next_hop)
1875 struct ip *ip = mtod(m, struct ip *);
1877 struct route fwd_ro;
1878 int error, type = 0, code = 0, destmtu = 0;
1879 struct mbuf *mcopy, *mtemp = NULL;
1881 struct in_addr pkt_dst;
1885 * Cache the destination address of the packet; this may be
1886 * changed by use of 'ipfw fwd'.
1888 pkt_dst = (next_hop != NULL) ? next_hop->sin_addr : ip->ip_dst;
1892 kprintf("forward: src %x dst %x ttl %x\n",
1893 ip->ip_src.s_addr, pkt_dst.s_addr, ip->ip_ttl);
1896 if (m->m_flags & (M_BCAST | M_MCAST) || !in_canforward(pkt_dst)) {
1897 ipstat.ips_cantforward++;
1901 if (!ipstealth && ip->ip_ttl <= IPTTLDEC) {
1902 icmp_error(m, ICMP_TIMXCEED, ICMP_TIMXCEED_INTRANS, dest, 0);
1906 bzero(&fwd_ro, sizeof(fwd_ro));
1907 ip_rtaddr(pkt_dst, &fwd_ro);
1908 if (fwd_ro.ro_rt == NULL) {
1909 icmp_error(m, ICMP_UNREACH, ICMP_UNREACH_HOST, dest, 0);
1914 if (curthread->td_type == TD_TYPE_NETISR) {
1916 * Save the IP header and at most 8 bytes of the payload,
1917 * in case we need to generate an ICMP message to the src.
1919 mtemp = ipforward_mtemp[mycpuid];
1920 KASSERT((mtemp->m_flags & M_EXT) == 0 &&
1921 mtemp->m_data == mtemp->m_pktdat &&
1922 m_tag_first(mtemp) == NULL,
1923 ("ip_forward invalid mtemp1"));
1925 if (!m_dup_pkthdr(mtemp, m, M_NOWAIT)) {
1927 * It's probably ok if the pkthdr dup fails (because
1928 * the deep copy of the tag chain failed), but for now
1929 * be conservative and just discard the copy since
1930 * code below may some day want the tags.
1934 mtemp->m_type = m->m_type;
1935 mtemp->m_len = imin((IP_VHL_HL(ip->ip_vhl) << 2) + 8,
1937 mtemp->m_pkthdr.len = mtemp->m_len;
1938 m_copydata(m, 0, mtemp->m_len, mtod(mtemp, caddr_t));
1943 ip->ip_ttl -= IPTTLDEC;
1946 * If forwarding packet using same interface that it came in on,
1947 * perhaps should send a redirect to sender to shortcut a hop.
1948 * Only send redirect if source is sending directly to us,
1949 * and if packet was not source routed (or has any options).
1950 * Also, don't send redirect if forwarding using a default route
1951 * or a route modified by a redirect.
1953 if (rt->rt_ifp == m->m_pkthdr.rcvif &&
1954 !(rt->rt_flags & (RTF_DYNAMIC | RTF_MODIFIED)) &&
1955 satosin(rt_key(rt))->sin_addr.s_addr != INADDR_ANY &&
1956 ipsendredirects && !using_srcrt && next_hop == NULL) {
1957 u_long src = ntohl(ip->ip_src.s_addr);
1958 struct in_ifaddr *rt_ifa = (struct in_ifaddr *)rt->rt_ifa;
1960 if (rt_ifa != NULL &&
1961 (src & rt_ifa->ia_subnetmask) == rt_ifa->ia_subnet) {
1962 if (rt->rt_flags & RTF_GATEWAY)
1963 dest = satosin(rt->rt_gateway)->sin_addr.s_addr;
1965 dest = pkt_dst.s_addr;
1967 * Router requirements says to only send
1970 type = ICMP_REDIRECT;
1971 code = ICMP_REDIRECT_HOST;
1974 kprintf("redirect (%d) to %x\n", code, dest);
1979 error = ip_output(m, NULL, &fwd_ro, IP_FORWARDING, NULL, NULL);
1981 ipstat.ips_forward++;
1984 ipflow_create(&fwd_ro, mtemp);
1987 ipstat.ips_redirectsent++;
1989 ipstat.ips_cantforward++;
1996 * Errors that do not require generating ICMP message
2001 * A router should not generate ICMP_SOURCEQUENCH as
2002 * required in RFC1812 Requirements for IP Version 4 Routers.
2003 * Source quench could be a big problem under DoS attacks,
2004 * or if the underlying interface is rate-limited.
2005 * Those who need source quench packets may re-enable them
2006 * via the net.inet.ip.sendsourcequench sysctl.
2008 if (!ip_sendsourcequench)
2012 case EACCES: /* ipfw denied packet */
2016 KASSERT((mtemp->m_flags & M_EXT) == 0 &&
2017 mtemp->m_data == mtemp->m_pktdat,
2018 ("ip_forward invalid mtemp2"));
2019 mcopy = m_copym(mtemp, 0, mtemp->m_len, M_NOWAIT);
2024 * Send ICMP message.
2027 case 0: /* forwarded, but need redirect */
2028 /* type, code set above */
2031 case ENETUNREACH: /* shouldn't happen, checked above */
2036 type = ICMP_UNREACH;
2037 code = ICMP_UNREACH_HOST;
2041 type = ICMP_UNREACH;
2042 code = ICMP_UNREACH_NEEDFRAG;
2043 if (fwd_ro.ro_rt != NULL)
2044 destmtu = fwd_ro.ro_rt->rt_ifp->if_mtu;
2045 ipstat.ips_cantfrag++;
2049 type = ICMP_SOURCEQUENCH;
2053 case EACCES: /* ipfw denied packet */
2054 panic("ip_forward EACCES should not reach");
2056 icmp_error(mcopy, type, code, dest, destmtu);
2059 m_tag_delete_chain(mtemp);
2060 if (fwd_ro.ro_rt != NULL)
2061 RTFREE(fwd_ro.ro_rt);
2065 ip_savecontrol(struct inpcb *inp, struct mbuf **mp, struct ip *ip,
2068 if (inp->inp_socket->so_options & SO_TIMESTAMP) {
2072 *mp = sbcreatecontrol((caddr_t) &tv, sizeof(tv),
2073 SCM_TIMESTAMP, SOL_SOCKET);
2075 mp = &(*mp)->m_next;
2077 if (inp->inp_flags & INP_RECVDSTADDR) {
2078 *mp = sbcreatecontrol((caddr_t) &ip->ip_dst,
2079 sizeof(struct in_addr), IP_RECVDSTADDR, IPPROTO_IP);
2081 mp = &(*mp)->m_next;
2083 if (inp->inp_flags & INP_RECVTTL) {
2084 *mp = sbcreatecontrol((caddr_t) &ip->ip_ttl,
2085 sizeof(u_char), IP_RECVTTL, IPPROTO_IP);
2087 mp = &(*mp)->m_next;
2091 * Moving these out of udp_input() made them even more broken
2092 * than they already were.
2094 /* options were tossed already */
2095 if (inp->inp_flags & INP_RECVOPTS) {
2096 *mp = sbcreatecontrol((caddr_t) opts_deleted_above,
2097 sizeof(struct in_addr), IP_RECVOPTS, IPPROTO_IP);
2099 mp = &(*mp)->m_next;
2101 /* ip_srcroute doesn't do what we want here, need to fix */
2102 if (inp->inp_flags & INP_RECVRETOPTS) {
2103 *mp = sbcreatecontrol((caddr_t) ip_srcroute(m),
2104 sizeof(struct in_addr), IP_RECVRETOPTS, IPPROTO_IP);
2106 mp = &(*mp)->m_next;
2109 if (inp->inp_flags & INP_RECVIF) {
2112 struct sockaddr_dl sdl;
2115 struct sockaddr_dl *sdp;
2116 struct sockaddr_dl *sdl2 = &sdlbuf.sdl;
2118 if (((ifp = m->m_pkthdr.rcvif)) &&
2119 ((ifp->if_index != 0) && (ifp->if_index <= if_index))) {
2120 sdp = IF_LLSOCKADDR(ifp);
2122 * Change our mind and don't try copy.
2124 if ((sdp->sdl_family != AF_LINK) ||
2125 (sdp->sdl_len > sizeof(sdlbuf))) {
2128 bcopy(sdp, sdl2, sdp->sdl_len);
2132 offsetof(struct sockaddr_dl, sdl_data[0]);
2133 sdl2->sdl_family = AF_LINK;
2134 sdl2->sdl_index = 0;
2135 sdl2->sdl_nlen = sdl2->sdl_alen = sdl2->sdl_slen = 0;
2137 *mp = sbcreatecontrol((caddr_t) sdl2, sdl2->sdl_len,
2138 IP_RECVIF, IPPROTO_IP);
2140 mp = &(*mp)->m_next;
2145 * XXX these routines are called from the upper part of the kernel.
2147 * They could also be moved to ip_mroute.c, since all the RSVP
2148 * handling is done there already.
2151 ip_rsvp_init(struct socket *so)
2153 if (so->so_type != SOCK_RAW ||
2154 so->so_proto->pr_protocol != IPPROTO_RSVP)
2157 if (ip_rsvpd != NULL)
2162 * This may seem silly, but we need to be sure we don't over-increment
2163 * the RSVP counter, in case something slips up.
2178 * This may seem silly, but we need to be sure we don't over-decrement
2179 * the RSVP counter, in case something slips up.
2189 rsvp_input(struct mbuf **mp, int *offp, int proto)
2191 struct mbuf *m = *mp;
2195 if (rsvp_input_p) { /* call the real one if loaded */
2197 rsvp_input_p(mp, offp, proto);
2198 return(IPPROTO_DONE);
2201 /* Can still get packets with rsvp_on = 0 if there is a local member
2202 * of the group to which the RSVP packet is addressed. But in this
2203 * case we want to throw the packet away.
2208 return(IPPROTO_DONE);
2211 if (ip_rsvpd != NULL) {
2213 rip_input(mp, offp, proto);
2214 return(IPPROTO_DONE);
2216 /* Drop the packet */
2218 return(IPPROTO_DONE);