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. All advertising materials mentioning features or use of this software
47 * must display the following acknowledgement:
48 * This product includes software developed by the University of
49 * California, Berkeley and its contributors.
50 * 4. Neither the name of the University nor the names of its contributors
51 * may be used to endorse or promote products derived from this software
52 * without specific prior written permission.
54 * THIS SOFTWARE IS PROVIDED BY THE REGENTS AND CONTRIBUTORS ``AS IS'' AND
55 * ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
56 * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE
57 * ARE DISCLAIMED. IN NO EVENT SHALL THE REGENTS OR CONTRIBUTORS BE LIABLE
58 * FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL
59 * DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS
60 * OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION)
61 * HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT
62 * LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY
63 * OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF
66 * @(#)ip_input.c 8.2 (Berkeley) 1/4/94
67 * $FreeBSD: src/sys/netinet/ip_input.c,v 1.130.2.52 2003/03/07 07:01:28 silby Exp $
68 * $DragonFly: src/sys/netinet/ip_input.c,v 1.77 2008/03/07 11:34:20 sephe Exp $
73 #include "opt_bootp.h"
76 #include "opt_ipdivert.h"
77 #include "opt_ipfilter.h"
78 #include "opt_ipstealth.h"
79 #include "opt_ipsec.h"
81 #include <sys/param.h>
82 #include <sys/systm.h>
84 #include <sys/malloc.h>
85 #include <sys/mpipe.h>
86 #include <sys/domain.h>
87 #include <sys/protosw.h>
88 #include <sys/socket.h>
90 #include <sys/globaldata.h>
91 #include <sys/thread.h>
92 #include <sys/kernel.h>
93 #include <sys/syslog.h>
94 #include <sys/sysctl.h>
95 #include <sys/in_cksum.h>
97 #include <machine/stdarg.h>
100 #include <net/if_types.h>
101 #include <net/if_var.h>
102 #include <net/if_dl.h>
103 #include <net/pfil.h>
104 #include <net/route.h>
105 #include <net/netisr.h>
107 #include <netinet/in.h>
108 #include <netinet/in_systm.h>
109 #include <netinet/in_var.h>
110 #include <netinet/ip.h>
111 #include <netinet/in_pcb.h>
112 #include <netinet/ip_var.h>
113 #include <netinet/ip_icmp.h>
115 #include <sys/thread2.h>
116 #include <sys/msgport2.h>
117 #include <net/netmsg2.h>
119 #include <sys/socketvar.h>
121 #include <net/ipfw/ip_fw.h>
122 #include <net/dummynet/ip_dummynet.h>
125 #include <netinet6/ipsec.h>
126 #include <netproto/key/key.h>
130 #include <netproto/ipsec/ipsec.h>
131 #include <netproto/ipsec/key.h>
135 static int ip_rsvp_on;
136 struct socket *ip_rsvpd;
138 int ipforwarding = 0;
139 SYSCTL_INT(_net_inet_ip, IPCTL_FORWARDING, forwarding, CTLFLAG_RW,
140 &ipforwarding, 0, "Enable IP forwarding between interfaces");
142 static int ipsendredirects = 1; /* XXX */
143 SYSCTL_INT(_net_inet_ip, IPCTL_SENDREDIRECTS, redirect, CTLFLAG_RW,
144 &ipsendredirects, 0, "Enable sending IP redirects");
146 int ip_defttl = IPDEFTTL;
147 SYSCTL_INT(_net_inet_ip, IPCTL_DEFTTL, ttl, CTLFLAG_RW,
148 &ip_defttl, 0, "Maximum TTL on IP packets");
150 static int ip_dosourceroute = 0;
151 SYSCTL_INT(_net_inet_ip, IPCTL_SOURCEROUTE, sourceroute, CTLFLAG_RW,
152 &ip_dosourceroute, 0, "Enable forwarding source routed IP packets");
154 static int ip_acceptsourceroute = 0;
155 SYSCTL_INT(_net_inet_ip, IPCTL_ACCEPTSOURCEROUTE, accept_sourceroute,
156 CTLFLAG_RW, &ip_acceptsourceroute, 0,
157 "Enable accepting source routed IP packets");
159 static int ip_keepfaith = 0;
160 SYSCTL_INT(_net_inet_ip, IPCTL_KEEPFAITH, keepfaith, CTLFLAG_RW,
162 "Enable packet capture for FAITH IPv4->IPv6 translater daemon");
164 static int nipq = 0; /* total # of reass queues */
166 SYSCTL_INT(_net_inet_ip, OID_AUTO, maxfragpackets, CTLFLAG_RW,
168 "Maximum number of IPv4 fragment reassembly queue entries");
170 static int maxfragsperpacket;
171 SYSCTL_INT(_net_inet_ip, OID_AUTO, maxfragsperpacket, CTLFLAG_RW,
172 &maxfragsperpacket, 0,
173 "Maximum number of IPv4 fragments allowed per packet");
175 static int ip_sendsourcequench = 0;
176 SYSCTL_INT(_net_inet_ip, OID_AUTO, sendsourcequench, CTLFLAG_RW,
177 &ip_sendsourcequench, 0,
178 "Enable the transmission of source quench packets");
180 int ip_do_randomid = 1;
181 SYSCTL_INT(_net_inet_ip, OID_AUTO, random_id, CTLFLAG_RW,
183 "Assign random ip_id values");
185 * XXX - Setting ip_checkinterface mostly implements the receive side of
186 * the Strong ES model described in RFC 1122, but since the routing table
187 * and transmit implementation do not implement the Strong ES model,
188 * setting this to 1 results in an odd hybrid.
190 * XXX - ip_checkinterface currently must be disabled if you use ipnat
191 * to translate the destination address to another local interface.
193 * XXX - ip_checkinterface must be disabled if you add IP aliases
194 * to the loopback interface instead of the interface where the
195 * packets for those addresses are received.
197 static int ip_checkinterface = 0;
198 SYSCTL_INT(_net_inet_ip, OID_AUTO, check_interface, CTLFLAG_RW,
199 &ip_checkinterface, 0, "Verify packet arrives on correct interface");
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_ifaddrhead; /* first inet address */
209 struct in_ifaddrhashhead *in_ifaddrhashtbl; /* inet addr hash table */
210 u_long in_ifaddrhmask; /* mask for hash table */
212 struct ip_stats ipstats_percpu[MAXCPU];
215 sysctl_ipstats(SYSCTL_HANDLER_ARGS)
219 for (cpu = 0; cpu < ncpus; ++cpu) {
220 if ((error = SYSCTL_OUT(req, &ipstats_percpu[cpu],
221 sizeof(struct ip_stats))))
223 if ((error = SYSCTL_IN(req, &ipstats_percpu[cpu],
224 sizeof(struct ip_stats))))
230 SYSCTL_PROC(_net_inet_ip, IPCTL_STATS, stats, (CTLTYPE_OPAQUE | CTLFLAG_RW),
231 0, 0, sysctl_ipstats, "S,ip_stats", "IP statistics");
233 SYSCTL_STRUCT(_net_inet_ip, IPCTL_STATS, stats, CTLFLAG_RW,
234 &ipstat, ip_stats, "IP statistics");
237 /* Packet reassembly stuff */
238 #define IPREASS_NHASH_LOG2 6
239 #define IPREASS_NHASH (1 << IPREASS_NHASH_LOG2)
240 #define IPREASS_HMASK (IPREASS_NHASH - 1)
241 #define IPREASS_HASH(x,y) \
242 (((((x) & 0xF) | ((((x) >> 8) & 0xF) << 4)) ^ (y)) & IPREASS_HMASK)
244 static struct ipq ipq[IPREASS_NHASH];
247 SYSCTL_INT(_net_inet_ip, IPCTL_DEFMTU, mtu, CTLFLAG_RW,
248 &ip_mtu, 0, "Default MTU");
252 static int ipstealth = 0;
253 SYSCTL_INT(_net_inet_ip, OID_AUTO, stealth, CTLFLAG_RW, &ipstealth, 0, "");
255 static const int ipstealth = 0;
260 ip_fw_chk_t *ip_fw_chk_ptr;
261 ip_fw_dn_io_t *ip_fw_dn_io_ptr;
265 struct pfil_head inet_pfil_hook;
268 * XXX this is ugly -- the following two global variables are
269 * used to store packet state while it travels through the stack.
270 * Note that the code even makes assumptions on the size and
271 * alignment of fields inside struct ip_srcrt so e.g. adding some
272 * fields will break the code. This needs to be fixed.
274 * We need to save the IP options in case a protocol wants to respond
275 * to an incoming packet over the same route if the packet got here
276 * using IP source routing. This allows connection establishment and
277 * maintenance when the remote end is on a network that is not known
280 static int ip_nhops = 0;
282 static struct ip_srcrt {
283 struct in_addr dst; /* final destination */
284 char nop; /* one NOP to align */
285 char srcopt[IPOPT_OFFSET + 1]; /* OPTVAL, OLEN and OFFSET */
286 struct in_addr route[MAX_IPOPTLEN/sizeof(struct in_addr)];
289 static MALLOC_DEFINE(M_IPQ, "ipq", "IP Fragment Management");
290 static struct malloc_pipe ipq_mpipe;
292 static void save_rte (u_char *, struct in_addr);
293 static int ip_dooptions (struct mbuf *m, int,
294 struct sockaddr_in *next_hop);
295 static void ip_forward (struct mbuf *m, boolean_t using_srcrt,
296 struct sockaddr_in *next_hop);
297 static void ip_freef (struct ipq *);
298 static void ip_input_handler (struct netmsg *);
299 static struct mbuf *ip_reass (struct mbuf *, struct ipq *,
300 struct ipq *, u_int32_t *);
303 * IP initialization: fill in IP protocol switch table.
304 * All protocols not implemented in kernel go to raw IP protocol handler.
316 * Make sure we can handle a reasonable number of fragments but
317 * cap it at 4000 (XXX).
319 mpipe_init(&ipq_mpipe, M_IPQ, sizeof(struct ipq),
320 IFQ_MAXLEN, 4000, 0, NULL);
321 TAILQ_INIT(&in_ifaddrhead);
322 in_ifaddrhashtbl = hashinit(INADDR_NHASH, M_IFADDR, &in_ifaddrhmask);
323 pr = pffindproto(PF_INET, IPPROTO_RAW, SOCK_RAW);
326 for (i = 0; i < IPPROTO_MAX; i++)
327 ip_protox[i] = pr - inetsw;
328 for (pr = inetdomain.dom_protosw;
329 pr < inetdomain.dom_protoswNPROTOSW; pr++)
330 if (pr->pr_domain->dom_family == PF_INET &&
331 pr->pr_protocol && pr->pr_protocol != IPPROTO_RAW)
332 ip_protox[pr->pr_protocol] = pr - inetsw;
334 inet_pfil_hook.ph_type = PFIL_TYPE_AF;
335 inet_pfil_hook.ph_af = AF_INET;
336 if ((i = pfil_head_register(&inet_pfil_hook)) != 0) {
337 kprintf("%s: WARNING: unable to register pfil hook, "
338 "error %d\n", __func__, i);
341 for (i = 0; i < IPREASS_NHASH; i++)
342 ipq[i].next = ipq[i].prev = &ipq[i];
344 maxnipq = nmbclusters / 32;
345 maxfragsperpacket = 16;
347 ip_id = time_second & 0xffff;
350 * Initialize IP statistics counters for each CPU.
354 for (cpu = 0; cpu < ncpus; ++cpu) {
355 bzero(&ipstats_percpu[cpu], sizeof(struct ip_stats));
358 bzero(&ipstat, sizeof(struct ip_stats));
361 netisr_register(NETISR_IP, ip_mport_in, ip_input_handler);
365 * XXX watch out this one. It is perhaps used as a cache for
366 * the most recently used route ? it is cleared in in_addroute()
367 * when a new route is successfully created.
369 struct route ipforward_rt[MAXCPU];
371 /* Do transport protocol processing. */
373 transport_processing_oncpu(struct mbuf *m, int hlen, struct ip *ip,
374 struct sockaddr_in *nexthop)
377 * Switch out to protocol's input routine.
379 if (nexthop && ip->ip_p == IPPROTO_TCP) {
380 /* TCP needs IPFORWARD info if available */
383 tag.mh_type = MT_TAG;
384 tag.mh_flags = PACKET_TAG_IPFORWARD;
385 tag.mh_data = (caddr_t)nexthop;
388 (*inetsw[ip_protox[ip->ip_p]].pr_input)
389 ((struct mbuf *)&tag, hlen, ip->ip_p);
391 (*inetsw[ip_protox[ip->ip_p]].pr_input)(m, hlen, ip->ip_p);
395 struct netmsg_transport_packet {
396 struct netmsg nm_netmsg;
397 struct mbuf *nm_mbuf;
399 boolean_t nm_hasnexthop;
400 struct sockaddr_in nm_nexthop;
404 transport_processing_handler(netmsg_t netmsg)
406 struct netmsg_transport_packet *msg = (void *)netmsg;
407 struct sockaddr_in *nexthop;
410 ip = mtod(msg->nm_mbuf, struct ip *);
411 nexthop = msg->nm_hasnexthop ? &msg->nm_nexthop : NULL;
412 transport_processing_oncpu(msg->nm_mbuf, msg->nm_hlen, ip, nexthop);
413 lwkt_replymsg(&msg->nm_netmsg.nm_lmsg, 0);
417 ip_input_handler(struct netmsg *msg0)
419 struct mbuf *m = ((struct netmsg_packet *)msg0)->nm_packet;
422 /* msg0 was embedded in the mbuf, do not reply! */
426 * IP input routine. Checksum and byte swap header. If fragmented
427 * try to reassemble. Process options. Pass to next level.
430 ip_input(struct mbuf *m)
434 struct in_ifaddr *ia = NULL;
435 int i, hlen, checkif;
437 struct in_addr pkt_dst;
438 u_int32_t divert_info = 0; /* packet divert/tee info */
439 struct ip_fw_args args;
440 boolean_t using_srcrt = FALSE; /* forward (by PFIL_HOOKS) */
441 boolean_t needredispatch = FALSE;
442 struct in_addr odst; /* original dst address(NAT) */
445 struct tdb_ident *tdbi;
446 struct secpolicy *sp;
453 args.next_hop = NULL;
455 /* Grab info from MT_TAG mbufs prepended to the chain. */
456 while (m != NULL && m->m_type == MT_TAG) {
457 switch(m->_m_tag_id) {
458 case PACKET_TAG_IPFORWARD:
459 args.next_hop = (struct sockaddr_in *)m->m_hdr.mh_data;
462 kprintf("ip_input: unrecognised MT_TAG tag %d\n",
470 /* Extract info from dummynet tag */
471 mtag = m_tag_find(m, PACKET_TAG_DUMMYNET, NULL);
473 args.rule = ((struct dn_pkt *)m_tag_data(mtag))->dn_priv;
475 m_tag_delete(m, mtag);
479 if (args.rule != NULL) { /* dummynet already filtered us */
480 ip = mtod(m, struct ip *);
481 hlen = IP_VHL_HL(ip->ip_vhl) << 2;
487 /* length checks already done in ip_demux() */
488 KASSERT(m->m_len >= sizeof(ip), ("IP header not in one mbuf"));
490 ip = mtod(m, struct ip *);
492 if (IP_VHL_V(ip->ip_vhl) != IPVERSION) {
493 ipstat.ips_badvers++;
497 hlen = IP_VHL_HL(ip->ip_vhl) << 2;
498 /* length checks already done in ip_demux() */
499 KASSERT(hlen >= sizeof(struct ip), ("IP header len too small"));
500 KASSERT(m->m_len >= hlen, ("packet shorter than IP header length"));
502 /* 127/8 must not appear on wire - RFC1122 */
503 if ((ntohl(ip->ip_dst.s_addr) >> IN_CLASSA_NSHIFT) == IN_LOOPBACKNET ||
504 (ntohl(ip->ip_src.s_addr) >> IN_CLASSA_NSHIFT) == IN_LOOPBACKNET) {
505 if (!(m->m_pkthdr.rcvif->if_flags & IFF_LOOPBACK)) {
506 ipstat.ips_badaddr++;
511 if (m->m_pkthdr.csum_flags & CSUM_IP_CHECKED) {
512 sum = !(m->m_pkthdr.csum_flags & CSUM_IP_VALID);
514 if (hlen == sizeof(struct ip)) {
515 sum = in_cksum_hdr(ip);
517 sum = in_cksum(m, hlen);
526 if (altq_input != NULL && (*altq_input)(m, AF_INET) == 0) {
527 /* packet is dropped by traffic conditioner */
532 * Convert fields to host representation.
534 ip->ip_len = ntohs(ip->ip_len);
535 if (ip->ip_len < hlen) {
539 ip->ip_off = ntohs(ip->ip_off);
542 * Check that the amount of data in the buffers
543 * is as at least much as the IP header would have us expect.
544 * Trim mbufs if longer than we expect.
545 * Drop packet if shorter than we expect.
547 if (m->m_pkthdr.len < ip->ip_len) {
548 ipstat.ips_tooshort++;
551 if (m->m_pkthdr.len > ip->ip_len) {
552 if (m->m_len == m->m_pkthdr.len) {
553 m->m_len = ip->ip_len;
554 m->m_pkthdr.len = ip->ip_len;
556 m_adj(m, ip->ip_len - m->m_pkthdr.len);
558 #if defined(IPSEC) && !defined(IPSEC_FILTERGIF)
560 * Bypass packet filtering for packets from a tunnel (gif).
562 if (ipsec_gethist(m, NULL))
568 * Right now when no processing on packet has done
569 * and it is still fresh out of network we do our black
571 * - Firewall: deny/allow/divert
572 * - Xlate: translate packet's addr/port (NAT).
573 * - Pipe: pass pkt through dummynet.
574 * - Wrap: fake packet's addr/port <unimpl.>
575 * - Encapsulate: put it in another IP and send out. <unimp.>
581 * Run through list of hooks for input packets.
583 * NB: Beware of the destination address changing (e.g.
584 * by NAT rewriting). When this happens, tell
585 * ip_forward to do the right thing.
587 if (pfil_has_hooks(&inet_pfil_hook)) {
589 if (pfil_run_hooks(&inet_pfil_hook, &m,
590 m->m_pkthdr.rcvif, PFIL_IN)) {
593 if (m == NULL) /* consumed by filter */
595 ip = mtod(m, struct ip *);
596 using_srcrt = (odst.s_addr != ip->ip_dst.s_addr);
599 if (fw_enable && IPFW_LOADED) {
601 * If we've been forwarded from the output side, then
602 * skip the firewall a second time
604 if (args.next_hop != NULL)
608 i = ip_fw_chk_ptr(&args);
611 if ((i & IP_FW_PORT_DENY_FLAG) || m == NULL) { /* drop */
616 ip = mtod(m, struct ip *); /* just in case m changed */
617 if (i == 0 && args.next_hop == NULL) /* common case */
619 if (i & IP_FW_PORT_DYNT_FLAG) {
620 /* Send packet to the appropriate pipe */
621 ip_fw_dn_io_ptr(m, i&0xffff, DN_TO_IP_IN, &args);
625 if (i != 0 && !(i & IP_FW_PORT_DYNT_FLAG)) {
626 /* Divert or tee packet */
631 if (i == 0 && args.next_hop != NULL)
634 * if we get here, the packet must be dropped
642 * Process options and, if not destined for us,
643 * ship it on. ip_dooptions returns 1 when an
644 * error was detected (causing an icmp message
645 * to be sent and the original packet to be freed).
647 ip_nhops = 0; /* for source routed packets */
648 if (hlen > sizeof(struct ip) && ip_dooptions(m, 0, args.next_hop))
651 /* greedy RSVP, snatches any PATH packet of the RSVP protocol and no
652 * matter if it is destined to another node, or whether it is
653 * a multicast one, RSVP wants it! and prevents it from being forwarded
654 * anywhere else. Also checks if the rsvp daemon is running before
655 * grabbing the packet.
657 if (rsvp_on && ip->ip_p == IPPROTO_RSVP)
661 * Check our list of addresses, to see if the packet is for us.
662 * If we don't have any addresses, assume any unicast packet
663 * we receive might be for us (and let the upper layers deal
666 if (TAILQ_EMPTY(&in_ifaddrhead) && !(m->m_flags & (M_MCAST | M_BCAST)))
670 * Cache the destination address of the packet; this may be
671 * changed by use of 'ipfw fwd'.
673 pkt_dst = args.next_hop ? args.next_hop->sin_addr : ip->ip_dst;
676 * Enable a consistency check between the destination address
677 * and the arrival interface for a unicast packet (the RFC 1122
678 * strong ES model) if IP forwarding is disabled and the packet
679 * is not locally generated and the packet is not subject to
682 * XXX - Checking also should be disabled if the destination
683 * address is ipnat'ed to a different interface.
685 * XXX - Checking is incompatible with IP aliases added
686 * to the loopback interface instead of the interface where
687 * the packets are received.
689 checkif = ip_checkinterface &&
691 m->m_pkthdr.rcvif != NULL &&
692 !(m->m_pkthdr.rcvif->if_flags & IFF_LOOPBACK) &&
693 (args.next_hop == NULL);
696 * Check for exact addresses in the hash bucket.
698 LIST_FOREACH(ia, INADDR_HASH(pkt_dst.s_addr), ia_hash) {
700 * If the address matches, verify that the packet
701 * arrived via the correct interface if checking is
704 if (IA_SIN(ia)->sin_addr.s_addr == pkt_dst.s_addr &&
705 (!checkif || ia->ia_ifp == m->m_pkthdr.rcvif))
709 * Check for broadcast addresses.
711 * Only accept broadcast packets that arrive via the matching
712 * interface. Reception of forwarded directed broadcasts would
713 * be handled via ip_forward() and ether_output() with the loopback
714 * into the stack for SIMPLEX interfaces handled by ether_output().
716 if (m->m_pkthdr.rcvif->if_flags & IFF_BROADCAST) {
717 struct ifaddr_container *ifac;
719 TAILQ_FOREACH(ifac, &m->m_pkthdr.rcvif->if_addrheads[mycpuid],
721 struct ifaddr *ifa = ifac->ifa;
723 if (ifa->ifa_addr == NULL) /* shutdown/startup race */
725 if (ifa->ifa_addr->sa_family != AF_INET)
728 if (satosin(&ia->ia_broadaddr)->sin_addr.s_addr ==
731 if (ia->ia_netbroadcast.s_addr == pkt_dst.s_addr)
734 if (IA_SIN(ia)->sin_addr.s_addr == INADDR_ANY)
739 if (IN_MULTICAST(ntohl(ip->ip_dst.s_addr))) {
740 struct in_multi *inm;
742 if (ip_mrouter != NULL) {
744 * If we are acting as a multicast router, all
745 * incoming multicast packets are passed to the
746 * kernel-level multicast forwarding function.
747 * The packet is returned (relatively) intact; if
748 * ip_mforward() returns a non-zero value, the packet
749 * must be discarded, else it may be accepted below.
751 if (ip_mforward != NULL &&
752 ip_mforward(ip, m->m_pkthdr.rcvif, m, NULL) != 0) {
753 ipstat.ips_cantforward++;
759 * The process-level routing daemon needs to receive
760 * all multicast IGMP packets, whether or not this
761 * host belongs to their destination groups.
763 if (ip->ip_p == IPPROTO_IGMP)
765 ipstat.ips_forward++;
768 * See if we belong to the destination multicast group on the
771 IN_LOOKUP_MULTI(ip->ip_dst, m->m_pkthdr.rcvif, inm);
773 ipstat.ips_notmember++;
779 if (ip->ip_dst.s_addr == INADDR_BROADCAST)
781 if (ip->ip_dst.s_addr == INADDR_ANY)
785 * FAITH(Firewall Aided Internet Translator)
787 if (m->m_pkthdr.rcvif && m->m_pkthdr.rcvif->if_type == IFT_FAITH) {
789 if (ip->ip_p == IPPROTO_TCP || ip->ip_p == IPPROTO_ICMP)
797 * Not for us; forward if possible and desirable.
800 ipstat.ips_cantforward++;
805 * Enforce inbound IPsec SPD.
807 if (ipsec4_in_reject(m, NULL)) {
808 ipsecstat.in_polvio++;
813 mtag = m_tag_find(m, PACKET_TAG_IPSEC_IN_DONE, NULL);
816 tdbi = (struct tdb_ident *)m_tag_data(mtag);
817 sp = ipsec_getpolicy(tdbi, IPSEC_DIR_INBOUND);
819 sp = ipsec_getpolicybyaddr(m, IPSEC_DIR_INBOUND,
820 IP_FORWARDING, &error);
822 if (sp == NULL) { /* NB: can happen if error */
824 /*XXX error stat???*/
825 DPRINTF(("ip_input: no SP for forwarding\n")); /*XXX*/
830 * Check security policy against packet attributes.
832 error = ipsec_in_reject(sp, m);
836 ipstat.ips_cantforward++;
840 ip_forward(m, using_srcrt, args.next_hop);
847 * IPSTEALTH: Process non-routing options only
848 * if the packet is destined for us.
851 hlen > sizeof(struct ip) &&
852 ip_dooptions(m, 1, args.next_hop))
855 /* Count the packet in the ip address stats */
857 ia->ia_ifa.if_ipackets++;
858 ia->ia_ifa.if_ibytes += m->m_pkthdr.len;
862 * If offset or IP_MF are set, must reassemble.
863 * Otherwise, nothing need be done.
864 * (We could look in the reassembly queue to see
865 * if the packet was previously fragmented,
866 * but it's not worth the time; just let them time out.)
868 if (ip->ip_off & (IP_MF | IP_OFFMASK)) {
870 /* If maxnipq is 0, never accept fragments. */
872 ipstat.ips_fragments++;
873 ipstat.ips_fragdropped++;
877 sum = IPREASS_HASH(ip->ip_src.s_addr, ip->ip_id);
879 * Look for queue of fragments
882 for (fp = ipq[sum].next; fp != &ipq[sum]; fp = fp->next)
883 if (ip->ip_id == fp->ipq_id &&
884 ip->ip_src.s_addr == fp->ipq_src.s_addr &&
885 ip->ip_dst.s_addr == fp->ipq_dst.s_addr &&
886 ip->ip_p == fp->ipq_p)
892 * Enforce upper bound on number of fragmented packets
893 * for which we attempt reassembly;
894 * If maxnipq is -1, accept all fragments without limitation.
896 if ((nipq > maxnipq) && (maxnipq > 0)) {
898 * drop something from the tail of the current queue
899 * before proceeding further
901 if (ipq[sum].prev == &ipq[sum]) { /* gak */
902 for (i = 0; i < IPREASS_NHASH; i++) {
903 if (ipq[i].prev != &ipq[i]) {
904 ipstat.ips_fragtimeout +=
905 ipq[i].prev->ipq_nfrags;
906 ip_freef(ipq[i].prev);
911 ipstat.ips_fragtimeout +=
912 ipq[sum].prev->ipq_nfrags;
913 ip_freef(ipq[sum].prev);
918 * Adjust ip_len to not reflect header,
919 * convert offset of this to bytes.
922 if (ip->ip_off & IP_MF) {
924 * Make sure that fragments have a data length
925 * that's a non-zero multiple of 8 bytes.
927 if (ip->ip_len == 0 || (ip->ip_len & 0x7) != 0) {
928 ipstat.ips_toosmall++; /* XXX */
931 m->m_flags |= M_FRAG;
933 m->m_flags &= ~M_FRAG;
937 * Attempt reassembly; if it succeeds, proceed.
938 * ip_reass() will return a different mbuf, and update
939 * the divert info in divert_info.
941 ipstat.ips_fragments++;
942 m->m_pkthdr.header = ip;
943 m = ip_reass(m, fp, &ipq[sum], &divert_info);
946 ipstat.ips_reassembled++;
947 needredispatch = TRUE;
948 ip = mtod(m, struct ip *);
949 /* Get the header length of the reassembled packet */
950 hlen = IP_VHL_HL(ip->ip_vhl) << 2;
952 /* Restore original checksum before diverting packet */
953 if (divert_info != 0) {
955 ip->ip_len = htons(ip->ip_len);
956 ip->ip_off = htons(ip->ip_off);
958 if (hlen == sizeof(struct ip))
959 ip->ip_sum = in_cksum_hdr(ip);
961 ip->ip_sum = in_cksum(m, hlen);
962 ip->ip_off = ntohs(ip->ip_off);
963 ip->ip_len = ntohs(ip->ip_len);
973 * Divert or tee packet to the divert protocol if required.
975 if (divert_info != 0) {
976 struct mbuf *clone = NULL;
978 /* Clone packet if we're doing a 'tee' */
979 if ((divert_info & IP_FW_PORT_TEE_FLAG) != 0)
980 clone = m_dup(m, MB_DONTWAIT);
982 /* Restore packet header fields to original values */
984 ip->ip_len = htons(ip->ip_len);
985 ip->ip_off = htons(ip->ip_off);
987 /* Deliver packet to divert input routine */
988 divert_packet(m, 1, divert_info & 0xffff);
989 ipstat.ips_delivered++;
991 /* If 'tee', continue with original packet */
995 ip = mtod(m, struct ip *);
998 * Jump backwards to complete processing of the
999 * packet. But first clear divert_info to avoid
1000 * entering this block again.
1001 * We do not need to clear args.divert_rule
1002 * or args.next_hop as they will not be used.
1004 * XXX Better safe than sorry, remove the DIVERT tag.
1006 mtag = m_tag_find(m, PACKET_TAG_IPFW_DIVERT, NULL);
1008 m_tag_delete(m, mtag);
1017 * enforce IPsec policy checking if we are seeing last header.
1018 * note that we do not visit this with protocols with pcb layer
1019 * code - like udp/tcp/raw ip.
1021 if ((inetsw[ip_protox[ip->ip_p]].pr_flags & PR_LASTHDR) &&
1022 ipsec4_in_reject(m, NULL)) {
1023 ipsecstat.in_polvio++;
1029 * enforce IPsec policy checking if we are seeing last header.
1030 * note that we do not visit this with protocols with pcb layer
1031 * code - like udp/tcp/raw ip.
1033 if (inetsw[ip_protox[ip->ip_p]].pr_flags & PR_LASTHDR) {
1035 * Check if the packet has already had IPsec processing
1036 * done. If so, then just pass it along. This tag gets
1037 * set during AH, ESP, etc. input handling, before the
1038 * packet is returned to the ip input queue for delivery.
1040 mtag = m_tag_find(m, PACKET_TAG_IPSEC_IN_DONE, NULL);
1043 tdbi = (struct tdb_ident *)m_tag_data(mtag);
1044 sp = ipsec_getpolicy(tdbi, IPSEC_DIR_INBOUND);
1046 sp = ipsec_getpolicybyaddr(m, IPSEC_DIR_INBOUND,
1047 IP_FORWARDING, &error);
1051 * Check security policy against packet attributes.
1053 error = ipsec_in_reject(sp, m);
1056 /* XXX error stat??? */
1058 DPRINTF(("ip_input: no SP, packet discarded\n"));/*XXX*/
1065 #endif /* FAST_IPSEC */
1067 ipstat.ips_delivered++;
1068 if (needredispatch) {
1069 struct netmsg_transport_packet *msg;
1072 ip->ip_off = htons(ip->ip_off);
1073 ip->ip_len = htons(ip->ip_len);
1074 port = ip_mport_in(&m);
1078 msg = kmalloc(sizeof(struct netmsg_transport_packet), M_LWKTMSG,
1079 M_INTWAIT | M_NULLOK);
1083 netmsg_init(&msg->nm_netmsg, &netisr_afree_rport, 0,
1084 transport_processing_handler);
1085 msg->nm_hlen = hlen;
1086 msg->nm_hasnexthop = (args.next_hop != NULL);
1087 if (msg->nm_hasnexthop)
1088 msg->nm_nexthop = *args.next_hop; /* structure copy */
1091 ip = mtod(m, struct ip *);
1092 ip->ip_len = ntohs(ip->ip_len);
1093 ip->ip_off = ntohs(ip->ip_off);
1094 lwkt_sendmsg(port, &msg->nm_netmsg.nm_lmsg);
1096 transport_processing_oncpu(m, hlen, ip, args.next_hop);
1105 * Take incoming datagram fragment and try to reassemble it into
1106 * whole datagram. If a chain for reassembly of this datagram already
1107 * exists, then it is given as fp; otherwise have to make a chain.
1109 * When IPDIVERT enabled, keep additional state with each packet that
1110 * tells us if we need to divert or tee the packet we're building.
1111 * In particular, *divinfo includes the port and TEE flag.
1114 static struct mbuf *
1115 ip_reass(struct mbuf *m, struct ipq *fp, struct ipq *where,
1118 struct ip *ip = mtod(m, struct ip *);
1119 struct mbuf *p = NULL, *q, *nq;
1121 int hlen = IP_VHL_HL(ip->ip_vhl) << 2;
1128 * If the hardware has not done csum over this fragment
1129 * then csum_data is not valid at all.
1131 if ((m->m_pkthdr.csum_flags & (CSUM_FRAG_NOT_CHECKED | CSUM_DATA_VALID))
1132 == (CSUM_FRAG_NOT_CHECKED | CSUM_DATA_VALID)) {
1133 m->m_pkthdr.csum_data = 0;
1134 m->m_pkthdr.csum_flags &= ~(CSUM_DATA_VALID | CSUM_PSEUDO_HDR);
1138 * Presence of header sizes in mbufs
1139 * would confuse code below.
1145 * If first fragment to arrive, create a reassembly queue.
1148 if ((fp = mpipe_alloc_nowait(&ipq_mpipe)) == NULL)
1153 fp->ipq_ttl = IPFRAGTTL;
1154 fp->ipq_p = ip->ip_p;
1155 fp->ipq_id = ip->ip_id;
1156 fp->ipq_src = ip->ip_src;
1157 fp->ipq_dst = ip->ip_dst;
1159 m->m_nextpkt = NULL;
1161 fp->ipq_div_info = 0;
1168 #define GETIP(m) ((struct ip*)((m)->m_pkthdr.header))
1171 * Find a segment which begins after this one does.
1173 for (p = NULL, q = fp->ipq_frags; q; p = q, q = q->m_nextpkt)
1174 if (GETIP(q)->ip_off > ip->ip_off)
1178 * If there is a preceding segment, it may provide some of
1179 * our data already. If so, drop the data from the incoming
1180 * segment. If it provides all of our data, drop us, otherwise
1181 * stick new segment in the proper place.
1183 * If some of the data is dropped from the the preceding
1184 * segment, then it's checksum is invalidated.
1187 i = GETIP(p)->ip_off + GETIP(p)->ip_len - ip->ip_off;
1189 if (i >= ip->ip_len)
1192 m->m_pkthdr.csum_flags = 0;
1196 m->m_nextpkt = p->m_nextpkt;
1199 m->m_nextpkt = fp->ipq_frags;
1204 * While we overlap succeeding segments trim them or,
1205 * if they are completely covered, dequeue them.
1207 for (; q != NULL && ip->ip_off + ip->ip_len > GETIP(q)->ip_off;
1209 i = (ip->ip_off + ip->ip_len) - GETIP(q)->ip_off;
1210 if (i < GETIP(q)->ip_len) {
1211 GETIP(q)->ip_len -= i;
1212 GETIP(q)->ip_off += i;
1214 q->m_pkthdr.csum_flags = 0;
1219 ipstat.ips_fragdropped++;
1221 q->m_nextpkt = NULL;
1229 * Transfer firewall instructions to the fragment structure.
1230 * Only trust info in the fragment at offset 0.
1232 if (ip->ip_off == 0) {
1233 fp->ipq_div_info = *divinfo;
1235 mtag = m_tag_find(m, PACKET_TAG_IPFW_DIVERT, NULL);
1237 m_tag_delete(m, mtag);
1243 * Check for complete reassembly and perform frag per packet
1246 * Frag limiting is performed here so that the nth frag has
1247 * a chance to complete the packet before we drop the packet.
1248 * As a result, n+1 frags are actually allowed per packet, but
1249 * only n will ever be stored. (n = maxfragsperpacket.)
1253 for (p = NULL, q = fp->ipq_frags; q; p = q, q = q->m_nextpkt) {
1254 if (GETIP(q)->ip_off != next) {
1255 if (fp->ipq_nfrags > maxfragsperpacket) {
1256 ipstat.ips_fragdropped += fp->ipq_nfrags;
1261 next += GETIP(q)->ip_len;
1263 /* Make sure the last packet didn't have the IP_MF flag */
1264 if (p->m_flags & M_FRAG) {
1265 if (fp->ipq_nfrags > maxfragsperpacket) {
1266 ipstat.ips_fragdropped += fp->ipq_nfrags;
1273 * Reassembly is complete. Make sure the packet is a sane size.
1277 if (next + (IP_VHL_HL(ip->ip_vhl) << 2) > IP_MAXPACKET) {
1278 ipstat.ips_toolong++;
1279 ipstat.ips_fragdropped += fp->ipq_nfrags;
1285 * Concatenate fragments.
1292 q->m_nextpkt = NULL;
1293 for (q = nq; q != NULL; q = nq) {
1295 q->m_nextpkt = NULL;
1296 m->m_pkthdr.csum_flags &= q->m_pkthdr.csum_flags;
1297 m->m_pkthdr.csum_data += q->m_pkthdr.csum_data;
1302 * Clean up the 1's complement checksum. Carry over 16 bits must
1303 * be added back. This assumes no more then 65535 packet fragments
1304 * were reassembled. A second carry can also occur (but not a third).
1306 m->m_pkthdr.csum_data = (m->m_pkthdr.csum_data & 0xffff) +
1307 (m->m_pkthdr.csum_data >> 16);
1308 if (m->m_pkthdr.csum_data > 0xFFFF)
1309 m->m_pkthdr.csum_data -= 0xFFFF;
1314 * Extract firewall instructions from the fragment structure.
1316 *divinfo = fp->ipq_div_info;
1320 * Create header for new ip packet by
1321 * modifying header of first packet;
1322 * dequeue and discard fragment reassembly header.
1323 * Make header visible.
1326 ip->ip_src = fp->ipq_src;
1327 ip->ip_dst = fp->ipq_dst;
1330 mpipe_free(&ipq_mpipe, fp);
1331 m->m_len += (IP_VHL_HL(ip->ip_vhl) << 2);
1332 m->m_data -= (IP_VHL_HL(ip->ip_vhl) << 2);
1333 /* some debugging cruft by sklower, below, will go away soon */
1334 if (m->m_flags & M_PKTHDR) { /* XXX this should be done elsewhere */
1337 for (n = m; n; n = n->m_next)
1339 m->m_pkthdr.len = plen;
1347 ipstat.ips_fragdropped++;
1357 * Free a fragment reassembly header and all
1358 * associated datagrams.
1361 ip_freef(struct ipq *fp)
1365 while (fp->ipq_frags) {
1367 fp->ipq_frags = q->m_nextpkt;
1368 q->m_nextpkt = NULL;
1372 mpipe_free(&ipq_mpipe, fp);
1377 * IP timer processing;
1378 * if a timer expires on a reassembly
1379 * queue, discard it.
1388 for (i = 0; i < IPREASS_NHASH; i++) {
1392 while (fp != &ipq[i]) {
1395 if (fp->prev->ipq_ttl == 0) {
1396 ipstat.ips_fragtimeout += fp->prev->ipq_nfrags;
1402 * If we are over the maximum number of fragments
1403 * (due to the limit being lowered), drain off
1404 * enough to get down to the new limit.
1406 if (maxnipq >= 0 && nipq > maxnipq) {
1407 for (i = 0; i < IPREASS_NHASH; i++) {
1408 while (nipq > maxnipq &&
1409 (ipq[i].next != &ipq[i])) {
1410 ipstat.ips_fragdropped +=
1411 ipq[i].next->ipq_nfrags;
1412 ip_freef(ipq[i].next);
1421 * Drain off all datagram fragments.
1428 for (i = 0; i < IPREASS_NHASH; i++) {
1429 while (ipq[i].next != &ipq[i]) {
1430 ipstat.ips_fragdropped += ipq[i].next->ipq_nfrags;
1431 ip_freef(ipq[i].next);
1438 * Do option processing on a datagram,
1439 * possibly discarding it if bad options are encountered,
1440 * or forwarding it if source-routed.
1441 * The pass argument is used when operating in the IPSTEALTH
1442 * mode to tell what options to process:
1443 * [LS]SRR (pass 0) or the others (pass 1).
1444 * The reason for as many as two passes is that when doing IPSTEALTH,
1445 * non-routing options should be processed only if the packet is for us.
1446 * Returns 1 if packet has been forwarded/freed,
1447 * 0 if the packet should be processed further.
1450 ip_dooptions(struct mbuf *m, int pass, struct sockaddr_in *next_hop)
1452 struct sockaddr_in ipaddr = { sizeof ipaddr, AF_INET };
1453 struct ip *ip = mtod(m, struct ip *);
1455 struct in_ifaddr *ia;
1456 int opt, optlen, cnt, off, code, type = ICMP_PARAMPROB;
1457 boolean_t forward = FALSE;
1458 struct in_addr *sin, dst;
1462 cp = (u_char *)(ip + 1);
1463 cnt = (IP_VHL_HL(ip->ip_vhl) << 2) - sizeof(struct ip);
1464 for (; cnt > 0; cnt -= optlen, cp += optlen) {
1465 opt = cp[IPOPT_OPTVAL];
1466 if (opt == IPOPT_EOL)
1468 if (opt == IPOPT_NOP)
1471 if (cnt < IPOPT_OLEN + sizeof(*cp)) {
1472 code = &cp[IPOPT_OLEN] - (u_char *)ip;
1475 optlen = cp[IPOPT_OLEN];
1476 if (optlen < IPOPT_OLEN + sizeof(*cp) || optlen > cnt) {
1477 code = &cp[IPOPT_OLEN] - (u_char *)ip;
1487 * Source routing with record.
1488 * Find interface with current destination address.
1489 * If none on this machine then drop if strictly routed,
1490 * or do nothing if loosely routed.
1491 * Record interface address and bring up next address
1492 * component. If strictly routed make sure next
1493 * address is on directly accessible net.
1497 if (ipstealth && pass > 0)
1499 if (optlen < IPOPT_OFFSET + sizeof(*cp)) {
1500 code = &cp[IPOPT_OLEN] - (u_char *)ip;
1503 if ((off = cp[IPOPT_OFFSET]) < IPOPT_MINOFF) {
1504 code = &cp[IPOPT_OFFSET] - (u_char *)ip;
1507 ipaddr.sin_addr = ip->ip_dst;
1508 ia = (struct in_ifaddr *)
1509 ifa_ifwithaddr((struct sockaddr *)&ipaddr);
1511 if (opt == IPOPT_SSRR) {
1512 type = ICMP_UNREACH;
1513 code = ICMP_UNREACH_SRCFAIL;
1516 if (!ip_dosourceroute)
1517 goto nosourcerouting;
1519 * Loose routing, and not at next destination
1520 * yet; nothing to do except forward.
1524 off--; /* 0 origin */
1525 if (off > optlen - (int)sizeof(struct in_addr)) {
1527 * End of source route. Should be for us.
1529 if (!ip_acceptsourceroute)
1530 goto nosourcerouting;
1531 save_rte(cp, ip->ip_src);
1536 if (!ip_dosourceroute) {
1538 char buf[sizeof "aaa.bbb.ccc.ddd"];
1541 * Acting as a router, so generate ICMP
1544 strcpy(buf, inet_ntoa(ip->ip_dst));
1546 "attempted source route from %s to %s\n",
1547 inet_ntoa(ip->ip_src), buf);
1548 type = ICMP_UNREACH;
1549 code = ICMP_UNREACH_SRCFAIL;
1553 * Not acting as a router,
1557 ipstat.ips_cantforward++;
1564 * locate outgoing interface
1566 memcpy(&ipaddr.sin_addr, cp + off,
1567 sizeof ipaddr.sin_addr);
1569 if (opt == IPOPT_SSRR) {
1570 #define INA struct in_ifaddr *
1571 #define SA struct sockaddr *
1572 if ((ia = (INA)ifa_ifwithdstaddr((SA)&ipaddr))
1574 ia = (INA)ifa_ifwithnet((SA)&ipaddr);
1576 ia = ip_rtaddr(ipaddr.sin_addr,
1577 &ipforward_rt[mycpuid]);
1579 type = ICMP_UNREACH;
1580 code = ICMP_UNREACH_SRCFAIL;
1583 ip->ip_dst = ipaddr.sin_addr;
1584 memcpy(cp + off, &IA_SIN(ia)->sin_addr,
1585 sizeof(struct in_addr));
1586 cp[IPOPT_OFFSET] += sizeof(struct in_addr);
1588 * Let ip_intr's mcast routing check handle mcast pkts
1590 forward = !IN_MULTICAST(ntohl(ip->ip_dst.s_addr));
1594 if (ipstealth && pass == 0)
1596 if (optlen < IPOPT_OFFSET + sizeof(*cp)) {
1597 code = &cp[IPOPT_OFFSET] - (u_char *)ip;
1600 if ((off = cp[IPOPT_OFFSET]) < IPOPT_MINOFF) {
1601 code = &cp[IPOPT_OFFSET] - (u_char *)ip;
1605 * If no space remains, ignore.
1607 off--; /* 0 origin */
1608 if (off > optlen - (int)sizeof(struct in_addr))
1610 memcpy(&ipaddr.sin_addr, &ip->ip_dst,
1611 sizeof ipaddr.sin_addr);
1613 * locate outgoing interface; if we're the destination,
1614 * use the incoming interface (should be same).
1616 if ((ia = (INA)ifa_ifwithaddr((SA)&ipaddr)) == NULL &&
1617 (ia = ip_rtaddr(ipaddr.sin_addr,
1618 &ipforward_rt[mycpuid]))
1620 type = ICMP_UNREACH;
1621 code = ICMP_UNREACH_HOST;
1624 memcpy(cp + off, &IA_SIN(ia)->sin_addr,
1625 sizeof(struct in_addr));
1626 cp[IPOPT_OFFSET] += sizeof(struct in_addr);
1630 if (ipstealth && pass == 0)
1632 code = cp - (u_char *)ip;
1633 if (optlen < 4 || optlen > 40) {
1634 code = &cp[IPOPT_OLEN] - (u_char *)ip;
1637 if ((off = cp[IPOPT_OFFSET]) < 5) {
1638 code = &cp[IPOPT_OLEN] - (u_char *)ip;
1641 if (off > optlen - (int)sizeof(int32_t)) {
1642 cp[IPOPT_OFFSET + 1] += (1 << 4);
1643 if ((cp[IPOPT_OFFSET + 1] & 0xf0) == 0) {
1644 code = &cp[IPOPT_OFFSET] - (u_char *)ip;
1649 off--; /* 0 origin */
1650 sin = (struct in_addr *)(cp + off);
1651 switch (cp[IPOPT_OFFSET + 1] & 0x0f) {
1653 case IPOPT_TS_TSONLY:
1656 case IPOPT_TS_TSANDADDR:
1657 if (off + sizeof(n_time) +
1658 sizeof(struct in_addr) > optlen) {
1659 code = &cp[IPOPT_OFFSET] - (u_char *)ip;
1662 ipaddr.sin_addr = dst;
1663 ia = (INA)ifaof_ifpforaddr((SA)&ipaddr,
1667 memcpy(sin, &IA_SIN(ia)->sin_addr,
1668 sizeof(struct in_addr));
1669 cp[IPOPT_OFFSET] += sizeof(struct in_addr);
1670 off += sizeof(struct in_addr);
1673 case IPOPT_TS_PRESPEC:
1674 if (off + sizeof(n_time) +
1675 sizeof(struct in_addr) > optlen) {
1676 code = &cp[IPOPT_OFFSET] - (u_char *)ip;
1679 memcpy(&ipaddr.sin_addr, sin,
1680 sizeof(struct in_addr));
1681 if (ifa_ifwithaddr((SA)&ipaddr) == NULL)
1683 cp[IPOPT_OFFSET] += sizeof(struct in_addr);
1684 off += sizeof(struct in_addr);
1688 code = &cp[IPOPT_OFFSET + 1] - (u_char *)ip;
1692 memcpy(cp + off, &ntime, sizeof(n_time));
1693 cp[IPOPT_OFFSET] += sizeof(n_time);
1696 if (forward && ipforwarding) {
1697 ip_forward(m, TRUE, next_hop);
1702 icmp_error(m, type, code, 0, 0);
1703 ipstat.ips_badoptions++;
1708 * Given address of next destination (final or next hop),
1709 * return internet address info of interface to be used to get there.
1712 ip_rtaddr(struct in_addr dst, struct route *ro)
1714 struct sockaddr_in *sin;
1716 sin = (struct sockaddr_in *)&ro->ro_dst;
1718 if (ro->ro_rt == NULL || dst.s_addr != sin->sin_addr.s_addr) {
1719 if (ro->ro_rt != NULL) {
1723 sin->sin_family = AF_INET;
1724 sin->sin_len = sizeof *sin;
1725 sin->sin_addr = dst;
1726 rtalloc_ign(ro, RTF_PRCLONING);
1729 if (ro->ro_rt == NULL)
1732 return (ifatoia(ro->ro_rt->rt_ifa));
1736 * Save incoming source route for use in replies,
1737 * to be picked up later by ip_srcroute if the receiver is interested.
1740 save_rte(u_char *option, struct in_addr dst)
1744 olen = option[IPOPT_OLEN];
1747 kprintf("save_rte: olen %d\n", olen);
1749 if (olen > sizeof(ip_srcrt) - (1 + sizeof(dst)))
1751 bcopy(option, ip_srcrt.srcopt, olen);
1752 ip_nhops = (olen - IPOPT_OFFSET - 1) / sizeof(struct in_addr);
1757 * Retrieve incoming source route for use in replies,
1758 * in the same form used by setsockopt.
1759 * The first hop is placed before the options, will be removed later.
1764 struct in_addr *p, *q;
1769 m = m_get(MB_DONTWAIT, MT_HEADER);
1773 #define OPTSIZ (sizeof(ip_srcrt.nop) + sizeof(ip_srcrt.srcopt))
1775 /* length is (nhops+1)*sizeof(addr) + sizeof(nop + srcrt header) */
1776 m->m_len = ip_nhops * sizeof(struct in_addr) + sizeof(struct in_addr) +
1780 kprintf("ip_srcroute: nhops %d mlen %d", ip_nhops, m->m_len);
1784 * First save first hop for return route
1786 p = &ip_srcrt.route[ip_nhops - 1];
1787 *(mtod(m, struct in_addr *)) = *p--;
1790 kprintf(" hops %x", ntohl(mtod(m, struct in_addr *)->s_addr));
1794 * Copy option fields and padding (nop) to mbuf.
1796 ip_srcrt.nop = IPOPT_NOP;
1797 ip_srcrt.srcopt[IPOPT_OFFSET] = IPOPT_MINOFF;
1798 memcpy(mtod(m, caddr_t) + sizeof(struct in_addr), &ip_srcrt.nop,
1800 q = (struct in_addr *)(mtod(m, caddr_t) +
1801 sizeof(struct in_addr) + OPTSIZ);
1804 * Record return path as an IP source route,
1805 * reversing the path (pointers are now aligned).
1807 while (p >= ip_srcrt.route) {
1810 kprintf(" %x", ntohl(q->s_addr));
1815 * Last hop goes to final destination.
1820 kprintf(" %x\n", ntohl(q->s_addr));
1826 * Strip out IP options.
1829 ip_stripoptions(struct mbuf *m)
1832 struct ip *ip = mtod(m, struct ip *);
1836 optlen = (IP_VHL_HL(ip->ip_vhl) << 2) - sizeof(struct ip);
1837 opts = (caddr_t)(ip + 1);
1838 datalen = m->m_len - (sizeof(struct ip) + optlen);
1839 bcopy(opts + optlen, opts, datalen);
1841 if (m->m_flags & M_PKTHDR)
1842 m->m_pkthdr.len -= optlen;
1843 ip->ip_vhl = IP_MAKE_VHL(IPVERSION, sizeof(struct ip) >> 2);
1846 u_char inetctlerrmap[PRC_NCMDS] = {
1848 0, EMSGSIZE, EHOSTDOWN, EHOSTUNREACH,
1849 EHOSTUNREACH, EHOSTUNREACH, ECONNREFUSED, ECONNREFUSED,
1850 EMSGSIZE, EHOSTUNREACH, 0, 0,
1852 ENOPROTOOPT, ECONNREFUSED
1856 * Forward a packet. If some error occurs return the sender
1857 * an icmp packet. Note we can't always generate a meaningful
1858 * icmp message because icmp doesn't have a large enough repertoire
1859 * of codes and types.
1861 * If not forwarding, just drop the packet. This could be confusing
1862 * if ipforwarding was zero but some routing protocol was advancing
1863 * us as a gateway to somewhere. However, we must let the routing
1864 * protocol deal with that.
1866 * The using_srcrt parameter indicates whether the packet is being forwarded
1867 * via a source route.
1870 ip_forward(struct mbuf *m, boolean_t using_srcrt, struct sockaddr_in *next_hop)
1872 struct ip *ip = mtod(m, struct ip *);
1873 struct sockaddr_in *ipforward_rtaddr;
1875 int error, type = 0, code = 0, destmtu = 0;
1878 struct in_addr pkt_dst;
1880 struct route *cache_rt = &ipforward_rt[mycpuid];
1884 * Cache the destination address of the packet; this may be
1885 * changed by use of 'ipfw fwd'.
1887 pkt_dst = (next_hop != NULL) ? next_hop->sin_addr : ip->ip_dst;
1891 kprintf("forward: src %x dst %x ttl %x\n",
1892 ip->ip_src.s_addr, pkt_dst.s_addr, ip->ip_ttl);
1895 if (m->m_flags & (M_BCAST | M_MCAST) || !in_canforward(pkt_dst)) {
1896 ipstat.ips_cantforward++;
1900 if (!ipstealth && ip->ip_ttl <= IPTTLDEC) {
1901 icmp_error(m, ICMP_TIMXCEED, ICMP_TIMXCEED_INTRANS, dest, 0);
1905 ipforward_rtaddr = (struct sockaddr_in *) &cache_rt->ro_dst;
1906 if (cache_rt->ro_rt == NULL ||
1907 ipforward_rtaddr->sin_addr.s_addr != pkt_dst.s_addr) {
1908 if (cache_rt->ro_rt != NULL) {
1909 RTFREE(cache_rt->ro_rt);
1910 cache_rt->ro_rt = NULL;
1912 ipforward_rtaddr->sin_family = AF_INET;
1913 ipforward_rtaddr->sin_len = sizeof(struct sockaddr_in);
1914 ipforward_rtaddr->sin_addr = pkt_dst;
1915 rtalloc_ign(cache_rt, RTF_PRCLONING);
1916 if (cache_rt->ro_rt == NULL) {
1917 icmp_error(m, ICMP_UNREACH, ICMP_UNREACH_HOST, dest, 0);
1921 rt = cache_rt->ro_rt;
1924 * Save the IP header and at most 8 bytes of the payload,
1925 * in case we need to generate an ICMP message to the src.
1927 * XXX this can be optimized a lot by saving the data in a local
1928 * buffer on the stack (72 bytes at most), and only allocating the
1929 * mbuf if really necessary. The vast majority of the packets
1930 * are forwarded without having to send an ICMP back (either
1931 * because unnecessary, or because rate limited), so we are
1932 * really we are wasting a lot of work here.
1934 * We don't use m_copy() because it might return a reference
1935 * to a shared cluster. Both this function and ip_output()
1936 * assume exclusive access to the IP header in `m', so any
1937 * data in a cluster may change before we reach icmp_error().
1939 MGETHDR(mcopy, MB_DONTWAIT, m->m_type);
1940 if (mcopy != NULL && !m_dup_pkthdr(mcopy, m, MB_DONTWAIT)) {
1942 * It's probably ok if the pkthdr dup fails (because
1943 * the deep copy of the tag chain failed), but for now
1944 * be conservative and just discard the copy since
1945 * code below may some day want the tags.
1950 if (mcopy != NULL) {
1951 mcopy->m_len = imin((IP_VHL_HL(ip->ip_vhl) << 2) + 8,
1953 mcopy->m_pkthdr.len = mcopy->m_len;
1954 m_copydata(m, 0, mcopy->m_len, mtod(mcopy, caddr_t));
1958 ip->ip_ttl -= IPTTLDEC;
1961 * If forwarding packet using same interface that it came in on,
1962 * perhaps should send a redirect to sender to shortcut a hop.
1963 * Only send redirect if source is sending directly to us,
1964 * and if packet was not source routed (or has any options).
1965 * Also, don't send redirect if forwarding using a default route
1966 * or a route modified by a redirect.
1968 if (rt->rt_ifp == m->m_pkthdr.rcvif &&
1969 !(rt->rt_flags & (RTF_DYNAMIC | RTF_MODIFIED)) &&
1970 satosin(rt_key(rt))->sin_addr.s_addr != INADDR_ANY &&
1971 ipsendredirects && !using_srcrt && next_hop == NULL) {
1972 u_long src = ntohl(ip->ip_src.s_addr);
1973 struct in_ifaddr *rt_ifa = (struct in_ifaddr *)rt->rt_ifa;
1975 if (rt_ifa != NULL &&
1976 (src & rt_ifa->ia_subnetmask) == rt_ifa->ia_subnet) {
1977 if (rt->rt_flags & RTF_GATEWAY)
1978 dest = satosin(rt->rt_gateway)->sin_addr.s_addr;
1980 dest = pkt_dst.s_addr;
1982 * Router requirements says to only send
1985 type = ICMP_REDIRECT;
1986 code = ICMP_REDIRECT_HOST;
1989 kprintf("redirect (%d) to %x\n", code, dest);
1994 if (next_hop != NULL) {
1995 /* Pass IPFORWARD info if available */
1996 tag.mh_type = MT_TAG;
1997 tag.mh_flags = PACKET_TAG_IPFORWARD;
1998 tag.mh_data = (caddr_t)next_hop;
2000 m = (struct mbuf *)&tag;
2003 error = ip_output(m, NULL, cache_rt, IP_FORWARDING, NULL,
2006 ipstat.ips_forward++;
2009 ipflow_create(cache_rt, mcopy);
2012 return; /* most common case */
2014 ipstat.ips_redirectsent++;
2017 ipstat.ips_cantforward++;
2024 * Send ICMP message.
2029 case 0: /* forwarded, but need redirect */
2030 /* type, code set above */
2033 case ENETUNREACH: /* shouldn't happen, checked above */
2038 type = ICMP_UNREACH;
2039 code = ICMP_UNREACH_HOST;
2043 type = ICMP_UNREACH;
2044 code = ICMP_UNREACH_NEEDFRAG;
2047 * If the packet is routed over IPsec tunnel, tell the
2048 * originator the tunnel MTU.
2049 * tunnel MTU = if MTU - sizeof(IP) - ESP/AH hdrsiz
2052 if (cache_rt->ro_rt != NULL) {
2053 struct secpolicy *sp = NULL;
2058 sp = ipsec4_getpolicybyaddr(mcopy,
2064 destmtu = cache_rt->ro_rt->rt_ifp->if_mtu;
2066 /* count IPsec header size */
2067 ipsechdr = ipsec4_hdrsiz(mcopy,
2072 * find the correct route for outer IPv4
2073 * header, compute tunnel MTU.
2076 if (sp->req != NULL && sp->req->sav != NULL &&
2077 sp->req->sav->sah != NULL) {
2078 ro = &sp->req->sav->sah->sa_route;
2079 if (ro->ro_rt != NULL &&
2080 ro->ro_rt->rt_ifp != NULL) {
2082 ro->ro_rt->rt_ifp->if_mtu;
2083 destmtu -= ipsechdr;
2092 * If the packet is routed over IPsec tunnel, tell the
2093 * originator the tunnel MTU.
2094 * tunnel MTU = if MTU - sizeof(IP) - ESP/AH hdrsiz
2097 if (cache_rt->ro_rt != NULL) {
2098 struct secpolicy *sp = NULL;
2103 sp = ipsec_getpolicybyaddr(mcopy,
2109 destmtu = cache_rt->ro_rt->rt_ifp->if_mtu;
2111 /* count IPsec header size */
2112 ipsechdr = ipsec4_hdrsiz(mcopy,
2117 * find the correct route for outer IPv4
2118 * header, compute tunnel MTU.
2121 if (sp->req != NULL &&
2122 sp->req->sav != NULL &&
2123 sp->req->sav->sah != NULL) {
2124 ro = &sp->req->sav->sah->sa_route;
2125 if (ro->ro_rt != NULL &&
2126 ro->ro_rt->rt_ifp != NULL) {
2128 ro->ro_rt->rt_ifp->if_mtu;
2129 destmtu -= ipsechdr;
2136 #else /* !IPSEC && !FAST_IPSEC */
2137 if (cache_rt->ro_rt != NULL)
2138 destmtu = cache_rt->ro_rt->rt_ifp->if_mtu;
2140 ipstat.ips_cantfrag++;
2145 * A router should not generate ICMP_SOURCEQUENCH as
2146 * required in RFC1812 Requirements for IP Version 4 Routers.
2147 * Source quench could be a big problem under DoS attacks,
2148 * or if the underlying interface is rate-limited.
2149 * Those who need source quench packets may re-enable them
2150 * via the net.inet.ip.sendsourcequench sysctl.
2152 if (!ip_sendsourcequench) {
2156 type = ICMP_SOURCEQUENCH;
2161 case EACCES: /* ipfw denied packet */
2165 icmp_error(mcopy, type, code, dest, destmtu);
2169 ip_savecontrol(struct inpcb *inp, struct mbuf **mp, struct ip *ip,
2172 if (inp->inp_socket->so_options & SO_TIMESTAMP) {
2176 *mp = sbcreatecontrol((caddr_t) &tv, sizeof(tv),
2177 SCM_TIMESTAMP, SOL_SOCKET);
2179 mp = &(*mp)->m_next;
2181 if (inp->inp_flags & INP_RECVDSTADDR) {
2182 *mp = sbcreatecontrol((caddr_t) &ip->ip_dst,
2183 sizeof(struct in_addr), IP_RECVDSTADDR, IPPROTO_IP);
2185 mp = &(*mp)->m_next;
2187 if (inp->inp_flags & INP_RECVTTL) {
2188 *mp = sbcreatecontrol((caddr_t) &ip->ip_ttl,
2189 sizeof(u_char), IP_RECVTTL, IPPROTO_IP);
2191 mp = &(*mp)->m_next;
2195 * Moving these out of udp_input() made them even more broken
2196 * than they already were.
2198 /* options were tossed already */
2199 if (inp->inp_flags & INP_RECVOPTS) {
2200 *mp = sbcreatecontrol((caddr_t) opts_deleted_above,
2201 sizeof(struct in_addr), IP_RECVOPTS, IPPROTO_IP);
2203 mp = &(*mp)->m_next;
2205 /* ip_srcroute doesn't do what we want here, need to fix */
2206 if (inp->inp_flags & INP_RECVRETOPTS) {
2207 *mp = sbcreatecontrol((caddr_t) ip_srcroute(),
2208 sizeof(struct in_addr), IP_RECVRETOPTS, IPPROTO_IP);
2210 mp = &(*mp)->m_next;
2213 if (inp->inp_flags & INP_RECVIF) {
2216 struct sockaddr_dl sdl;
2219 struct sockaddr_dl *sdp;
2220 struct sockaddr_dl *sdl2 = &sdlbuf.sdl;
2222 if (((ifp = m->m_pkthdr.rcvif)) &&
2223 ((ifp->if_index != 0) && (ifp->if_index <= if_index))) {
2224 sdp = IF_LLSOCKADDR(ifp);
2226 * Change our mind and don't try copy.
2228 if ((sdp->sdl_family != AF_LINK) ||
2229 (sdp->sdl_len > sizeof(sdlbuf))) {
2232 bcopy(sdp, sdl2, sdp->sdl_len);
2236 offsetof(struct sockaddr_dl, sdl_data[0]);
2237 sdl2->sdl_family = AF_LINK;
2238 sdl2->sdl_index = 0;
2239 sdl2->sdl_nlen = sdl2->sdl_alen = sdl2->sdl_slen = 0;
2241 *mp = sbcreatecontrol((caddr_t) sdl2, sdl2->sdl_len,
2242 IP_RECVIF, IPPROTO_IP);
2244 mp = &(*mp)->m_next;
2249 * XXX these routines are called from the upper part of the kernel.
2251 * They could also be moved to ip_mroute.c, since all the RSVP
2252 * handling is done there already.
2255 ip_rsvp_init(struct socket *so)
2257 if (so->so_type != SOCK_RAW ||
2258 so->so_proto->pr_protocol != IPPROTO_RSVP)
2261 if (ip_rsvpd != NULL)
2266 * This may seem silly, but we need to be sure we don't over-increment
2267 * the RSVP counter, in case something slips up.
2282 * This may seem silly, but we need to be sure we don't over-decrement
2283 * the RSVP counter, in case something slips up.
2293 rsvp_input(struct mbuf *m, ...) /* XXX must fixup manually */
2299 off = __va_arg(ap, int);
2300 proto = __va_arg(ap, int);
2303 if (rsvp_input_p) { /* call the real one if loaded */
2304 rsvp_input_p(m, off, proto);
2308 /* Can still get packets with rsvp_on = 0 if there is a local member
2309 * of the group to which the RSVP packet is addressed. But in this
2310 * case we want to throw the packet away.
2318 if (ip_rsvpd != NULL) {
2319 rip_input(m, off, proto);
2322 /* Drop the packet */