2 * Copyright (c) 1982, 1986, 1988, 1993
3 * The Regents of the University of California. All rights reserved.
5 * Redistribution and use in source and binary forms, with or without
6 * modification, are permitted provided that the following conditions
8 * 1. Redistributions of source code must retain the above copyright
9 * notice, this list of conditions and the following disclaimer.
10 * 2. Redistributions in binary form must reproduce the above copyright
11 * notice, this list of conditions and the following disclaimer in the
12 * documentation and/or other materials provided with the distribution.
13 * 3. All advertising materials mentioning features or use of this software
14 * must display the following acknowledgement:
15 * This product includes software developed by the University of
16 * California, Berkeley and its contributors.
17 * 4. Neither the name of the University nor the names of its contributors
18 * may be used to endorse or promote products derived from this software
19 * without specific prior written permission.
21 * THIS SOFTWARE IS PROVIDED BY THE REGENTS AND CONTRIBUTORS ``AS IS'' AND
22 * ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
23 * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE
24 * ARE DISCLAIMED. IN NO EVENT SHALL THE REGENTS OR CONTRIBUTORS BE LIABLE
25 * FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL
26 * DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS
27 * OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION)
28 * HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT
29 * LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY
30 * OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF
33 * @(#)ip_input.c 8.2 (Berkeley) 1/4/94
34 * $FreeBSD: src/sys/netinet/ip_input.c,v 1.130.2.52 2003/03/07 07:01:28 silby Exp $
35 * $DragonFly: src/sys/netinet/ip_input.c,v 1.17 2004/04/09 22:34:10 hsu Exp $
40 #include "opt_bootp.h"
43 #include "opt_ipdivert.h"
44 #include "opt_ipfilter.h"
45 #include "opt_ipstealth.h"
46 #include "opt_ipsec.h"
47 #include "opt_pfil_hooks.h"
48 #include "opt_random_ip_id.h"
50 #include <sys/param.h>
51 #include <sys/systm.h>
53 #include <sys/malloc.h>
54 #include <sys/domain.h>
55 #include <sys/protosw.h>
56 #include <sys/socket.h>
58 #include <sys/kernel.h>
59 #include <sys/syslog.h>
60 #include <sys/sysctl.h>
61 #include <sys/in_cksum.h>
63 #include <sys/thread2.h>
64 #include <sys/msgport2.h>
67 #include <net/if_types.h>
68 #include <net/if_var.h>
69 #include <net/if_dl.h>
73 #include <net/route.h>
74 #include <net/netisr.h>
75 #include <net/intrq.h>
77 #include <netinet/in.h>
78 #include <netinet/in_systm.h>
79 #include <netinet/in_var.h>
80 #include <netinet/ip.h>
81 #include <netinet/in_pcb.h>
82 #include <netinet/ip_var.h>
83 #include <netinet/ip_icmp.h>
85 #include <netinet/ipprotosw.h>
87 #include <sys/socketvar.h>
89 #include <net/ipfw/ip_fw.h>
90 #include <net/dummynet/ip_dummynet.h>
93 #include <netinet6/ipsec.h>
94 #include <netproto/key/key.h>
98 #include <netipsec/ipsec.h>
99 #include <netipsec/key.h>
103 static int ip_rsvp_on;
104 struct socket *ip_rsvpd;
106 int ipforwarding = 0;
107 SYSCTL_INT(_net_inet_ip, IPCTL_FORWARDING, forwarding, CTLFLAG_RW,
108 &ipforwarding, 0, "Enable IP forwarding between interfaces");
110 static int ipsendredirects = 1; /* XXX */
111 SYSCTL_INT(_net_inet_ip, IPCTL_SENDREDIRECTS, redirect, CTLFLAG_RW,
112 &ipsendredirects, 0, "Enable sending IP redirects");
114 int ip_defttl = IPDEFTTL;
115 SYSCTL_INT(_net_inet_ip, IPCTL_DEFTTL, ttl, CTLFLAG_RW,
116 &ip_defttl, 0, "Maximum TTL on IP packets");
118 static int ip_dosourceroute = 0;
119 SYSCTL_INT(_net_inet_ip, IPCTL_SOURCEROUTE, sourceroute, CTLFLAG_RW,
120 &ip_dosourceroute, 0, "Enable forwarding source routed IP packets");
122 static int ip_acceptsourceroute = 0;
123 SYSCTL_INT(_net_inet_ip, IPCTL_ACCEPTSOURCEROUTE, accept_sourceroute,
124 CTLFLAG_RW, &ip_acceptsourceroute, 0,
125 "Enable accepting source routed IP packets");
127 static int ip_keepfaith = 0;
128 SYSCTL_INT(_net_inet_ip, IPCTL_KEEPFAITH, keepfaith, CTLFLAG_RW,
130 "Enable packet capture for FAITH IPv4->IPv6 translater daemon");
132 static int nipq = 0; /* total # of reass queues */
134 SYSCTL_INT(_net_inet_ip, OID_AUTO, maxfragpackets, CTLFLAG_RW,
136 "Maximum number of IPv4 fragment reassembly queue entries");
138 static int maxfragsperpacket;
139 SYSCTL_INT(_net_inet_ip, OID_AUTO, maxfragsperpacket, CTLFLAG_RW,
140 &maxfragsperpacket, 0,
141 "Maximum number of IPv4 fragments allowed per packet");
143 static int ip_sendsourcequench = 0;
144 SYSCTL_INT(_net_inet_ip, OID_AUTO, sendsourcequench, CTLFLAG_RW,
145 &ip_sendsourcequench, 0,
146 "Enable the transmission of source quench packets");
149 * XXX - Setting ip_checkinterface mostly implements the receive side of
150 * the Strong ES model described in RFC 1122, but since the routing table
151 * and transmit implementation do not implement the Strong ES model,
152 * setting this to 1 results in an odd hybrid.
154 * XXX - ip_checkinterface currently must be disabled if you use ipnat
155 * to translate the destination address to another local interface.
157 * XXX - ip_checkinterface must be disabled if you add IP aliases
158 * to the loopback interface instead of the interface where the
159 * packets for those addresses are received.
161 static int ip_checkinterface = 0;
162 SYSCTL_INT(_net_inet_ip, OID_AUTO, check_interface, CTLFLAG_RW,
163 &ip_checkinterface, 0, "Verify packet arrives on correct interface");
166 static int ipprintfs = 0;
169 static struct ifqueue ipintrq;
170 static int ipqmaxlen = IFQ_MAXLEN;
172 extern struct domain inetdomain;
173 extern struct ipprotosw inetsw[];
174 u_char ip_protox[IPPROTO_MAX];
175 struct in_ifaddrhead in_ifaddrhead; /* first inet address */
176 struct in_ifaddrhashhead *in_ifaddrhashtbl; /* inet addr hash table */
177 u_long in_ifaddrhmask; /* mask for hash table */
179 SYSCTL_INT(_net_inet_ip, IPCTL_INTRQMAXLEN, intr_queue_maxlen, CTLFLAG_RW,
180 &ipintrq.ifq_maxlen, 0, "Maximum size of the IP input queue");
181 SYSCTL_INT(_net_inet_ip, IPCTL_INTRQDROPS, intr_queue_drops, CTLFLAG_RD,
182 &ipintrq.ifq_drops, 0, "Number of packets dropped from the IP input queue");
184 struct ipstat ipstat;
185 SYSCTL_STRUCT(_net_inet_ip, IPCTL_STATS, stats, CTLFLAG_RW,
186 &ipstat, ipstat, "IP statistics (struct ipstat, netinet/ip_var.h)");
188 /* Packet reassembly stuff */
189 #define IPREASS_NHASH_LOG2 6
190 #define IPREASS_NHASH (1 << IPREASS_NHASH_LOG2)
191 #define IPREASS_HMASK (IPREASS_NHASH - 1)
192 #define IPREASS_HASH(x,y) \
193 (((((x) & 0xF) | ((((x) >> 8) & 0xF) << 4)) ^ (y)) & IPREASS_HMASK)
195 static struct ipq ipq[IPREASS_NHASH];
196 const int ipintrq_present = 1;
199 SYSCTL_INT(_net_inet_ip, IPCTL_DEFMTU, mtu, CTLFLAG_RW,
200 &ip_mtu, 0, "Default MTU");
204 static int ipstealth = 0;
205 SYSCTL_INT(_net_inet_ip, OID_AUTO, stealth, CTLFLAG_RW, &ipstealth, 0, "");
207 static const int ipstealth = 0;
212 ip_fw_chk_t *ip_fw_chk_ptr;
217 ip_dn_io_t *ip_dn_io_ptr;
220 struct pfil_head inet_pfil_hook;
224 * XXX this is ugly -- the following two global variables are
225 * used to store packet state while it travels through the stack.
226 * Note that the code even makes assumptions on the size and
227 * alignment of fields inside struct ip_srcrt so e.g. adding some
228 * fields will break the code. This needs to be fixed.
230 * We need to save the IP options in case a protocol wants to respond
231 * to an incoming packet over the same route if the packet got here
232 * using IP source routing. This allows connection establishment and
233 * maintenance when the remote end is on a network that is not known
236 static int ip_nhops = 0;
238 static struct ip_srcrt {
239 struct in_addr dst; /* final destination */
240 char nop; /* one NOP to align */
241 char srcopt[IPOPT_OFFSET + 1]; /* OPTVAL, OLEN and OFFSET */
242 struct in_addr route[MAX_IPOPTLEN/sizeof(struct in_addr)];
245 static void save_rte(u_char *, struct in_addr);
246 static int ip_dooptions(struct mbuf *m, int,
247 struct sockaddr_in *next_hop);
248 static void ip_forward(struct mbuf *m, int srcrt,
249 struct sockaddr_in *next_hop);
250 static void ip_freef(struct ipq *);
251 static struct mbuf *ip_reass(struct mbuf *, struct ipq *,
252 struct ipq *, u_int32_t *, u_int16_t *);
255 * IP initialization: fill in IP protocol switch table.
256 * All protocols not implemented in kernel go to raw IP protocol handler.
261 struct ipprotosw *pr;
264 TAILQ_INIT(&in_ifaddrhead);
265 in_ifaddrhashtbl = hashinit(INADDR_NHASH, M_IFADDR, &in_ifaddrhmask);
266 pr = (struct ipprotosw *)pffindproto(PF_INET, IPPROTO_RAW, SOCK_RAW);
269 for (i = 0; i < IPPROTO_MAX; i++)
270 ip_protox[i] = pr - inetsw;
271 for (pr = (struct ipprotosw *)inetdomain.dom_protosw;
272 pr < (struct ipprotosw *)inetdomain.dom_protoswNPROTOSW; pr++)
273 if (pr->pr_domain->dom_family == PF_INET &&
274 pr->pr_protocol && pr->pr_protocol != IPPROTO_RAW)
275 ip_protox[pr->pr_protocol] = pr - inetsw;
278 inet_pfil_hook.ph_type = PFIL_TYPE_AF;
279 inet_pfil_hook.ph_af = AF_INET;
280 if ((i = pfil_head_register(&inet_pfil_hook)) != 0)
281 printf("%s: WARNING: unable to register pfil hook, "
282 "error %d\n", __func__, i);
285 for (i = 0; i < IPREASS_NHASH; i++)
286 ipq[i].next = ipq[i].prev = &ipq[i];
288 maxnipq = nmbclusters / 32;
289 maxfragsperpacket = 16;
292 ip_id = time_second & 0xffff;
294 ipintrq.ifq_maxlen = ipqmaxlen;
296 netisr_register(NETISR_IP, ip_mport, ip_input);
300 * XXX watch out this one. It is perhaps used as a cache for
301 * the most recently used route ? it is cleared in in_addroute()
302 * when a new route is successfully created.
304 struct route ipforward_rt;
305 static struct sockaddr_in ipaddr = { sizeof(ipaddr), AF_INET };
307 /* Do transport protocol processing. */
309 transport_processing_oncpu(struct mbuf *m, int hlen, struct ip *ip,
310 struct sockaddr_in *nexthop)
313 * Switch out to protocol's input routine.
315 if (nexthop && ip->ip_p == IPPROTO_TCP) {
316 /* TCP needs IPFORWARD info if available */
319 tag.mh_type = MT_TAG;
320 tag.mh_flags = PACKET_TAG_IPFORWARD;
321 tag.mh_data = (caddr_t)nexthop;
324 (*inetsw[ip_protox[ip->ip_p]].pr_input)
325 ((struct mbuf *)&tag, hlen, ip->ip_p);
327 (*inetsw[ip_protox[ip->ip_p]].pr_input)(m, hlen, ip->ip_p);
331 struct netmsg_transport_packet {
332 struct lwkt_msg nm_lmsg;
333 netisr_fn_t nm_handler;
334 struct mbuf *nm_mbuf;
336 boolean_t nm_hasnexthop;
337 struct sockaddr_in nm_nexthop;
341 transport_processing_handler(struct netmsg *msg0)
343 struct netmsg_transport_packet *msg =
344 (struct netmsg_transport_packet *)msg0;
345 struct sockaddr_in *nexthop;
348 ip = mtod(msg->nm_mbuf, struct ip *);
349 nexthop = msg->nm_hasnexthop ? &msg->nm_nexthop : NULL;
350 transport_processing_oncpu(msg->nm_mbuf, msg->nm_hlen, ip, nexthop);
351 lwkt_replymsg(&msg0->nm_lmsg, 0);
355 * Ip input routine. Checksum and byte swap header. If fragmented
356 * try to reassemble. Process options. Pass to next level.
359 ip_input(struct netmsg *msg0)
361 struct mbuf *m = ((struct netmsg_packet *)msg0)->nm_packet;
364 struct in_ifaddr *ia = NULL;
366 int i, hlen, checkif;
368 struct in_addr pkt_dst;
369 u_int32_t divert_info = 0; /* packet divert/tee info */
370 struct ip_fw_args args;
371 boolean_t using_srcrt = FALSE; /* forward (by PFIL_HOOKS) */
372 boolean_t needredispatch = FALSE;
374 struct in_addr odst; /* original dst address(NAT) */
378 struct tdb_ident *tdbi;
379 struct secpolicy *sp;
386 args.divert_rule = 0; /* divert cookie */
387 args.next_hop = NULL;
389 /* Grab info from MT_TAG mbufs prepended to the chain. */
390 for (; m && m->m_type == MT_TAG; m = m->m_next) {
391 switch(m->_m_tag_id) {
393 printf("ip_input: unrecognised MT_TAG tag %d\n",
397 case PACKET_TAG_DUMMYNET:
398 args.rule = ((struct dn_pkt *)m)->rule;
401 case PACKET_TAG_DIVERT:
402 args.divert_rule = (int)m->m_hdr.mh_data & 0xffff;
405 case PACKET_TAG_IPFORWARD:
406 args.next_hop = (struct sockaddr_in *)m->m_hdr.mh_data;
411 KASSERT(m != NULL && (m->m_flags & M_PKTHDR) != 0,
412 ("ip_input: no HDR"));
414 if (args.rule) { /* dummynet already filtered us */
415 ip = mtod(m, struct ip *);
416 hlen = IP_VHL_HL(ip->ip_vhl) << 2;
422 /* length checks already done in ip_demux() */
423 KASSERT(m->m_len >= sizeof(ip), ("IP header not in one mbuf"));
425 ip = mtod(m, struct ip *);
427 if (IP_VHL_V(ip->ip_vhl) != IPVERSION) {
428 ipstat.ips_badvers++;
432 hlen = IP_VHL_HL(ip->ip_vhl) << 2;
433 /* length checks already done in ip_demux() */
434 KASSERT(hlen >= sizeof(struct ip), ("IP header len too small"));
435 KASSERT(m->m_len >= hlen, ("packet shorter than IP header length"));
437 /* 127/8 must not appear on wire - RFC1122 */
438 if ((ntohl(ip->ip_dst.s_addr) >> IN_CLASSA_NSHIFT) == IN_LOOPBACKNET ||
439 (ntohl(ip->ip_src.s_addr) >> IN_CLASSA_NSHIFT) == IN_LOOPBACKNET) {
440 if (!(m->m_pkthdr.rcvif->if_flags & IFF_LOOPBACK)) {
441 ipstat.ips_badaddr++;
446 if (m->m_pkthdr.csum_flags & CSUM_IP_CHECKED) {
447 sum = !(m->m_pkthdr.csum_flags & CSUM_IP_VALID);
449 if (hlen == sizeof(struct ip)) {
450 sum = in_cksum_hdr(ip);
452 sum = in_cksum(m, hlen);
461 * Convert fields to host representation.
463 ip->ip_len = ntohs(ip->ip_len);
464 if (ip->ip_len < hlen) {
468 ip->ip_off = ntohs(ip->ip_off);
471 * Check that the amount of data in the buffers
472 * is as at least much as the IP header would have us expect.
473 * Trim mbufs if longer than we expect.
474 * Drop packet if shorter than we expect.
476 if (m->m_pkthdr.len < ip->ip_len) {
477 ipstat.ips_tooshort++;
480 if (m->m_pkthdr.len > ip->ip_len) {
481 if (m->m_len == m->m_pkthdr.len) {
482 m->m_len = ip->ip_len;
483 m->m_pkthdr.len = ip->ip_len;
485 m_adj(m, ip->ip_len - m->m_pkthdr.len);
487 #if defined(IPSEC) && !defined(IPSEC_FILTERGIF)
489 * Bypass packet filtering for packets from a tunnel (gif).
491 if (ipsec_gethist(m, NULL))
497 * Right now when no processing on packet has done
498 * and it is still fresh out of network we do our black
500 * - Firewall: deny/allow/divert
501 * - Xlate: translate packet's addr/port (NAT).
502 * - Pipe: pass pkt through dummynet.
503 * - Wrap: fake packet's addr/port <unimpl.>
504 * - Encapsulate: put it in another IP and send out. <unimp.>
511 * Run through list of hooks for input packets.
513 * NB: Beware of the destination address changing (e.g.
514 * by NAT rewriting). When this happens, tell
515 * ip_forward to do the right thing.
518 if (pfil_run_hooks(&inet_pfil_hook, &m, m->m_pkthdr.rcvif, PFIL_IN))
520 if (m == NULL) /* consumed by filter */
522 ip = mtod(m, struct ip *);
523 using_srcrt = (odst.s_addr != ip->ip_dst.s_addr);
526 if (fw_enable && IPFW_LOADED) {
528 * If we've been forwarded from the output side, then
529 * skip the firewall a second time
535 i = ip_fw_chk_ptr(&args);
538 if ( (i & IP_FW_PORT_DENY_FLAG) || m == NULL) { /* drop */
543 ip = mtod(m, struct ip *); /* just in case m changed */
544 if (i == 0 && args.next_hop == NULL) /* common case */
546 if (DUMMYNET_LOADED && (i & IP_FW_PORT_DYNT_FLAG)) {
547 /* Send packet to the appropriate pipe */
548 ip_dn_io_ptr(m, i&0xffff, DN_TO_IP_IN, &args);
552 if (i != 0 && !(i & IP_FW_PORT_DYNT_FLAG)) {
553 /* Divert or tee packet */
558 if (i == 0 && args.next_hop != NULL)
561 * if we get here, the packet must be dropped
569 * Process options and, if not destined for us,
570 * ship it on. ip_dooptions returns 1 when an
571 * error was detected (causing an icmp message
572 * to be sent and the original packet to be freed).
574 ip_nhops = 0; /* for source routed packets */
575 if (hlen > sizeof(struct ip) && ip_dooptions(m, 0, args.next_hop))
578 /* greedy RSVP, snatches any PATH packet of the RSVP protocol and no
579 * matter if it is destined to another node, or whether it is
580 * a multicast one, RSVP wants it! and prevents it from being forwarded
581 * anywhere else. Also checks if the rsvp daemon is running before
582 * grabbing the packet.
584 if (rsvp_on && ip->ip_p == IPPROTO_RSVP)
588 * Check our list of addresses, to see if the packet is for us.
589 * If we don't have any addresses, assume any unicast packet
590 * we receive might be for us (and let the upper layers deal
593 if (TAILQ_EMPTY(&in_ifaddrhead) && !(m->m_flags & (M_MCAST | M_BCAST)))
597 * Cache the destination address of the packet; this may be
598 * changed by use of 'ipfw fwd'.
600 pkt_dst = args.next_hop ? args.next_hop->sin_addr : ip->ip_dst;
603 * Enable a consistency check between the destination address
604 * and the arrival interface for a unicast packet (the RFC 1122
605 * strong ES model) if IP forwarding is disabled and the packet
606 * is not locally generated and the packet is not subject to
609 * XXX - Checking also should be disabled if the destination
610 * address is ipnat'ed to a different interface.
612 * XXX - Checking is incompatible with IP aliases added
613 * to the loopback interface instead of the interface where
614 * the packets are received.
616 checkif = ip_checkinterface &&
618 m->m_pkthdr.rcvif != NULL &&
619 !(m->m_pkthdr.rcvif->if_flags & IFF_LOOPBACK) &&
620 (args.next_hop == NULL);
623 * Check for exact addresses in the hash bucket.
625 LIST_FOREACH(ia, INADDR_HASH(pkt_dst.s_addr), ia_hash) {
627 * If the address matches, verify that the packet
628 * arrived via the correct interface if checking is
631 if (IA_SIN(ia)->sin_addr.s_addr == pkt_dst.s_addr &&
632 (!checkif || ia->ia_ifp == m->m_pkthdr.rcvif))
636 * Check for broadcast addresses.
638 * Only accept broadcast packets that arrive via the matching
639 * interface. Reception of forwarded directed broadcasts would
640 * be handled via ip_forward() and ether_output() with the loopback
641 * into the stack for SIMPLEX interfaces handled by ether_output().
643 if (m->m_pkthdr.rcvif->if_flags & IFF_BROADCAST) {
644 TAILQ_FOREACH(ifa, &m->m_pkthdr.rcvif->if_addrhead, ifa_link) {
645 if (ifa->ifa_addr->sa_family != AF_INET)
648 if (satosin(&ia->ia_broadaddr)->sin_addr.s_addr ==
651 if (ia->ia_netbroadcast.s_addr == pkt_dst.s_addr)
654 if (IA_SIN(ia)->sin_addr.s_addr == INADDR_ANY)
659 if (IN_MULTICAST(ntohl(ip->ip_dst.s_addr))) {
660 struct in_multi *inm;
663 * If we are acting as a multicast router, all
664 * incoming multicast packets are passed to the
665 * kernel-level multicast forwarding function.
666 * The packet is returned (relatively) intact; if
667 * ip_mforward() returns a non-zero value, the packet
668 * must be discarded, else it may be accepted below.
671 ip_mforward(ip, m->m_pkthdr.rcvif, m, NULL) != 0) {
672 ipstat.ips_cantforward++;
678 * The process-level routing daemon needs to receive
679 * all multicast IGMP packets, whether or not this
680 * host belongs to their destination groups.
682 if (ip->ip_p == IPPROTO_IGMP)
684 ipstat.ips_forward++;
687 * See if we belong to the destination multicast group on the
690 IN_LOOKUP_MULTI(ip->ip_dst, m->m_pkthdr.rcvif, inm);
692 ipstat.ips_notmember++;
698 if (ip->ip_dst.s_addr == INADDR_BROADCAST)
700 if (ip->ip_dst.s_addr == INADDR_ANY)
704 * FAITH(Firewall Aided Internet Translator)
706 if (m->m_pkthdr.rcvif && m->m_pkthdr.rcvif->if_type == IFT_FAITH) {
708 if (ip->ip_p == IPPROTO_TCP || ip->ip_p == IPPROTO_ICMP)
716 * Not for us; forward if possible and desirable.
719 ipstat.ips_cantforward++;
724 * Enforce inbound IPsec SPD.
726 if (ipsec4_in_reject(m, NULL)) {
727 ipsecstat.in_polvio++;
732 mtag = m_tag_find(m, PACKET_TAG_IPSEC_IN_DONE, NULL);
735 tdbi = (struct tdb_ident *)(mtag + 1);
736 sp = ipsec_getpolicy(tdbi, IPSEC_DIR_INBOUND);
738 sp = ipsec_getpolicybyaddr(m, IPSEC_DIR_INBOUND,
739 IP_FORWARDING, &error);
741 if (sp == NULL) { /* NB: can happen if error */
743 /*XXX error stat???*/
744 DPRINTF(("ip_input: no SP for forwarding\n")); /*XXX*/
749 * Check security policy against packet attributes.
751 error = ipsec_in_reject(sp, m);
755 ipstat.ips_cantforward++;
759 ip_forward(m, using_srcrt, args.next_hop);
766 * IPSTEALTH: Process non-routing options only
767 * if the packet is destined for us.
770 hlen > sizeof(struct ip) &&
771 ip_dooptions(m, 1, args.next_hop))
774 /* Count the packet in the ip address stats */
776 ia->ia_ifa.if_ipackets++;
777 ia->ia_ifa.if_ibytes += m->m_pkthdr.len;
781 * If offset or IP_MF are set, must reassemble.
782 * Otherwise, nothing need be done.
783 * (We could look in the reassembly queue to see
784 * if the packet was previously fragmented,
785 * but it's not worth the time; just let them time out.)
787 if (ip->ip_off & (IP_MF | IP_OFFMASK)) {
789 /* If maxnipq is 0, never accept fragments. */
791 ipstat.ips_fragments++;
792 ipstat.ips_fragdropped++;
796 sum = IPREASS_HASH(ip->ip_src.s_addr, ip->ip_id);
798 * Look for queue of fragments
801 for (fp = ipq[sum].next; fp != &ipq[sum]; fp = fp->next)
802 if (ip->ip_id == fp->ipq_id &&
803 ip->ip_src.s_addr == fp->ipq_src.s_addr &&
804 ip->ip_dst.s_addr == fp->ipq_dst.s_addr &&
805 ip->ip_p == fp->ipq_p)
811 * Enforce upper bound on number of fragmented packets
812 * for which we attempt reassembly;
813 * If maxnipq is -1, accept all fragments without limitation.
815 if ((nipq > maxnipq) && (maxnipq > 0)) {
817 * drop something from the tail of the current queue
818 * before proceeding further
820 if (ipq[sum].prev == &ipq[sum]) { /* gak */
821 for (i = 0; i < IPREASS_NHASH; i++) {
822 if (ipq[i].prev != &ipq[i]) {
823 ipstat.ips_fragtimeout +=
824 ipq[i].prev->ipq_nfrags;
825 ip_freef(ipq[i].prev);
830 ipstat.ips_fragtimeout +=
831 ipq[sum].prev->ipq_nfrags;
832 ip_freef(ipq[sum].prev);
837 * Adjust ip_len to not reflect header,
838 * convert offset of this to bytes.
841 if (ip->ip_off & IP_MF) {
843 * Make sure that fragments have a data length
844 * that's a non-zero multiple of 8 bytes.
846 if (ip->ip_len == 0 || (ip->ip_len & 0x7) != 0) {
847 ipstat.ips_toosmall++; /* XXX */
850 m->m_flags |= M_FRAG;
852 m->m_flags &= ~M_FRAG;
856 * Attempt reassembly; if it succeeds, proceed.
857 * ip_reass() will return a different mbuf, and update
858 * the divert info in divert_info and args.divert_rule.
860 ipstat.ips_fragments++;
861 m->m_pkthdr.header = ip;
862 m = ip_reass(m, fp, &ipq[sum], &divert_info, &args.divert_rule);
865 ipstat.ips_reassembled++;
866 needredispatch = TRUE;
867 ip = mtod(m, struct ip *);
868 /* Get the header length of the reassembled packet */
869 hlen = IP_VHL_HL(ip->ip_vhl) << 2;
871 /* Restore original checksum before diverting packet */
872 if (divert_info != 0) {
874 ip->ip_len = htons(ip->ip_len);
875 ip->ip_off = htons(ip->ip_off);
877 if (hlen == sizeof(struct ip))
878 ip->ip_sum = in_cksum_hdr(ip);
880 ip->ip_sum = in_cksum(m, hlen);
881 ip->ip_off = ntohs(ip->ip_off);
882 ip->ip_len = ntohs(ip->ip_len);
892 * Divert or tee packet to the divert protocol if required.
894 if (divert_info != 0) {
895 struct mbuf *clone = NULL;
897 /* Clone packet if we're doing a 'tee' */
898 if ((divert_info & IP_FW_PORT_TEE_FLAG) != 0)
899 clone = m_dup(m, M_DONTWAIT);
901 /* Restore packet header fields to original values */
903 ip->ip_len = htons(ip->ip_len);
904 ip->ip_off = htons(ip->ip_off);
906 /* Deliver packet to divert input routine */
907 divert_packet(m, 1, divert_info & 0xffff, args.divert_rule);
908 ipstat.ips_delivered++;
910 /* If 'tee', continue with original packet */
914 ip = mtod(m, struct ip *);
917 * Jump backwards to complete processing of the
918 * packet. But first clear divert_info to avoid
919 * entering this block again.
920 * We do not need to clear args.divert_rule
921 * or args.next_hop as they will not be used.
930 * enforce IPsec policy checking if we are seeing last header.
931 * note that we do not visit this with protocols with pcb layer
932 * code - like udp/tcp/raw ip.
934 if ((inetsw[ip_protox[ip->ip_p]].pr_flags & PR_LASTHDR) &&
935 ipsec4_in_reject(m, NULL)) {
936 ipsecstat.in_polvio++;
942 * enforce IPsec policy checking if we are seeing last header.
943 * note that we do not visit this with protocols with pcb layer
944 * code - like udp/tcp/raw ip.
946 if (inetsw[ip_protox[ip->ip_p]].pr_flags & PR_LASTHDR) {
948 * Check if the packet has already had IPsec processing
949 * done. If so, then just pass it along. This tag gets
950 * set during AH, ESP, etc. input handling, before the
951 * packet is returned to the ip input queue for delivery.
953 mtag = m_tag_find(m, PACKET_TAG_IPSEC_IN_DONE, NULL);
956 tdbi = (struct tdb_ident *)(mtag + 1);
957 sp = ipsec_getpolicy(tdbi, IPSEC_DIR_INBOUND);
959 sp = ipsec_getpolicybyaddr(m, IPSEC_DIR_INBOUND,
960 IP_FORWARDING, &error);
964 * Check security policy against packet attributes.
966 error = ipsec_in_reject(sp, m);
969 /* XXX error stat??? */
971 DPRINTF(("ip_input: no SP, packet discarded\n"));/*XXX*/
978 #endif /* FAST_IPSEC */
980 ipstat.ips_delivered++;
981 if (needredispatch) {
982 struct netmsg_transport_packet *msg;
985 msg = malloc(sizeof(struct netmsg_transport_packet),
986 M_LWKTMSG, M_NOWAIT);
989 lwkt_initmsg_rp(&msg->nm_lmsg, &netisr_afree_rport,
991 msg->nm_handler = transport_processing_handler;
994 msg->nm_hasnexthop = (args.next_hop != NULL);
995 if (msg->nm_hasnexthop)
996 msg->nm_nexthop = *args.next_hop; /* structure copy */
998 ip->ip_off = htons(ip->ip_off);
999 ip->ip_len = htons(ip->ip_len);
1001 ip->ip_len = ntohs(ip->ip_len);
1002 ip->ip_off = ntohs(ip->ip_off);
1004 lwkt_sendmsg(port, &msg->nm_lmsg);
1006 transport_processing_oncpu(m, hlen, ip, args.next_hop);
1008 lwkt_replymsg(&msg0->nm_lmsg, 0);
1013 lwkt_replymsg(&msg0->nm_lmsg, 0);
1017 * Take incoming datagram fragment and try to reassemble it into
1018 * whole datagram. If a chain for reassembly of this datagram already
1019 * exists, then it is given as fp; otherwise have to make a chain.
1021 * When IPDIVERT enabled, keep additional state with each packet that
1022 * tells us if we need to divert or tee the packet we're building.
1023 * In particular, *divinfo includes the port and TEE flag,
1024 * *divert_rule is the number of the matching rule.
1027 static struct mbuf *
1028 ip_reass(struct mbuf *m, struct ipq *fp, struct ipq *where,
1029 u_int32_t *divinfo, u_int16_t *divert_rule)
1031 struct ip *ip = mtod(m, struct ip *);
1032 struct mbuf *p = NULL, *q, *nq;
1034 int hlen = IP_VHL_HL(ip->ip_vhl) << 2;
1038 * Presence of header sizes in mbufs
1039 * would confuse code below.
1045 * If first fragment to arrive, create a reassembly queue.
1048 if ((t = m_get(M_DONTWAIT, MT_FTABLE)) == NULL)
1050 fp = mtod(t, struct ipq *);
1054 fp->ipq_ttl = IPFRAGTTL;
1055 fp->ipq_p = ip->ip_p;
1056 fp->ipq_id = ip->ip_id;
1057 fp->ipq_src = ip->ip_src;
1058 fp->ipq_dst = ip->ip_dst;
1060 m->m_nextpkt = NULL;
1062 fp->ipq_div_info = 0;
1063 fp->ipq_div_cookie = 0;
1070 #define GETIP(m) ((struct ip*)((m)->m_pkthdr.header))
1073 * Find a segment which begins after this one does.
1075 for (p = NULL, q = fp->ipq_frags; q; p = q, q = q->m_nextpkt)
1076 if (GETIP(q)->ip_off > ip->ip_off)
1080 * If there is a preceding segment, it may provide some of
1081 * our data already. If so, drop the data from the incoming
1082 * segment. If it provides all of our data, drop us, otherwise
1083 * stick new segment in the proper place.
1085 * If some of the data is dropped from the the preceding
1086 * segment, then it's checksum is invalidated.
1089 i = GETIP(p)->ip_off + GETIP(p)->ip_len - ip->ip_off;
1091 if (i >= ip->ip_len)
1094 m->m_pkthdr.csum_flags = 0;
1098 m->m_nextpkt = p->m_nextpkt;
1101 m->m_nextpkt = fp->ipq_frags;
1106 * While we overlap succeeding segments trim them or,
1107 * if they are completely covered, dequeue them.
1109 for (; q != NULL && ip->ip_off + ip->ip_len > GETIP(q)->ip_off;
1111 i = (ip->ip_off + ip->ip_len) - GETIP(q)->ip_off;
1112 if (i < GETIP(q)->ip_len) {
1113 GETIP(q)->ip_len -= i;
1114 GETIP(q)->ip_off += i;
1116 q->m_pkthdr.csum_flags = 0;
1121 ipstat.ips_fragdropped++;
1130 * Transfer firewall instructions to the fragment structure.
1131 * Only trust info in the fragment at offset 0.
1133 if (ip->ip_off == 0) {
1134 fp->ipq_div_info = *divinfo;
1135 fp->ipq_div_cookie = *divert_rule;
1142 * Check for complete reassembly and perform frag per packet
1145 * Frag limiting is performed here so that the nth frag has
1146 * a chance to complete the packet before we drop the packet.
1147 * As a result, n+1 frags are actually allowed per packet, but
1148 * only n will ever be stored. (n = maxfragsperpacket.)
1152 for (p = NULL, q = fp->ipq_frags; q; p = q, q = q->m_nextpkt) {
1153 if (GETIP(q)->ip_off != next) {
1154 if (fp->ipq_nfrags > maxfragsperpacket) {
1155 ipstat.ips_fragdropped += fp->ipq_nfrags;
1160 next += GETIP(q)->ip_len;
1162 /* Make sure the last packet didn't have the IP_MF flag */
1163 if (p->m_flags & M_FRAG) {
1164 if (fp->ipq_nfrags > maxfragsperpacket) {
1165 ipstat.ips_fragdropped += fp->ipq_nfrags;
1172 * Reassembly is complete. Make sure the packet is a sane size.
1176 if (next + (IP_VHL_HL(ip->ip_vhl) << 2) > IP_MAXPACKET) {
1177 ipstat.ips_toolong++;
1178 ipstat.ips_fragdropped += fp->ipq_nfrags;
1184 * Concatenate fragments.
1191 q->m_nextpkt = NULL;
1192 for (q = nq; q != NULL; q = nq) {
1194 q->m_nextpkt = NULL;
1195 m->m_pkthdr.csum_flags &= q->m_pkthdr.csum_flags;
1196 m->m_pkthdr.csum_data += q->m_pkthdr.csum_data;
1202 * Extract firewall instructions from the fragment structure.
1204 *divinfo = fp->ipq_div_info;
1205 *divert_rule = fp->ipq_div_cookie;
1209 * Create header for new ip packet by
1210 * modifying header of first packet;
1211 * dequeue and discard fragment reassembly header.
1212 * Make header visible.
1215 ip->ip_src = fp->ipq_src;
1216 ip->ip_dst = fp->ipq_dst;
1219 (void) m_free(dtom(fp));
1220 m->m_len += (IP_VHL_HL(ip->ip_vhl) << 2);
1221 m->m_data -= (IP_VHL_HL(ip->ip_vhl) << 2);
1222 /* some debugging cruft by sklower, below, will go away soon */
1223 if (m->m_flags & M_PKTHDR) { /* XXX this should be done elsewhere */
1226 for (t = m; t; t = t->m_next)
1228 m->m_pkthdr.len = plen;
1237 ipstat.ips_fragdropped++;
1247 * Free a fragment reassembly header and all
1248 * associated datagrams.
1251 ip_freef(struct ipq *fp)
1255 while (fp->ipq_frags) {
1257 fp->ipq_frags = q->m_nextpkt;
1261 (void) m_free(dtom(fp));
1266 * IP timer processing;
1267 * if a timer expires on a reassembly
1268 * queue, discard it.
1277 for (i = 0; i < IPREASS_NHASH; i++) {
1281 while (fp != &ipq[i]) {
1284 if (fp->prev->ipq_ttl == 0) {
1285 ipstat.ips_fragtimeout += fp->prev->ipq_nfrags;
1291 * If we are over the maximum number of fragments
1292 * (due to the limit being lowered), drain off
1293 * enough to get down to the new limit.
1295 if (maxnipq >= 0 && nipq > maxnipq) {
1296 for (i = 0; i < IPREASS_NHASH; i++) {
1297 while (nipq > maxnipq &&
1298 (ipq[i].next != &ipq[i])) {
1299 ipstat.ips_fragdropped +=
1300 ipq[i].next->ipq_nfrags;
1301 ip_freef(ipq[i].next);
1310 * Drain off all datagram fragments.
1317 for (i = 0; i < IPREASS_NHASH; i++) {
1318 while (ipq[i].next != &ipq[i]) {
1319 ipstat.ips_fragdropped += ipq[i].next->ipq_nfrags;
1320 ip_freef(ipq[i].next);
1327 * Do option processing on a datagram,
1328 * possibly discarding it if bad options are encountered,
1329 * or forwarding it if source-routed.
1330 * The pass argument is used when operating in the IPSTEALTH
1331 * mode to tell what options to process:
1332 * [LS]SRR (pass 0) or the others (pass 1).
1333 * The reason for as many as two passes is that when doing IPSTEALTH,
1334 * non-routing options should be processed only if the packet is for us.
1335 * Returns 1 if packet has been forwarded/freed,
1336 * 0 if the packet should be processed further.
1339 ip_dooptions(struct mbuf *m, int pass, struct sockaddr_in *next_hop)
1341 struct ip *ip = mtod(m, struct ip *);
1343 struct in_ifaddr *ia;
1344 int opt, optlen, cnt, off, code, type = ICMP_PARAMPROB;
1345 boolean_t forward = FALSE;
1346 struct in_addr *sin, dst;
1350 cp = (u_char *)(ip + 1);
1351 cnt = (IP_VHL_HL(ip->ip_vhl) << 2) - sizeof(struct ip);
1352 for (; cnt > 0; cnt -= optlen, cp += optlen) {
1353 opt = cp[IPOPT_OPTVAL];
1354 if (opt == IPOPT_EOL)
1356 if (opt == IPOPT_NOP)
1359 if (cnt < IPOPT_OLEN + sizeof(*cp)) {
1360 code = &cp[IPOPT_OLEN] - (u_char *)ip;
1363 optlen = cp[IPOPT_OLEN];
1364 if (optlen < IPOPT_OLEN + sizeof(*cp) || optlen > cnt) {
1365 code = &cp[IPOPT_OLEN] - (u_char *)ip;
1375 * Source routing with record.
1376 * Find interface with current destination address.
1377 * If none on this machine then drop if strictly routed,
1378 * or do nothing if loosely routed.
1379 * Record interface address and bring up next address
1380 * component. If strictly routed make sure next
1381 * address is on directly accessible net.
1385 if (ipstealth && pass > 0)
1387 if (optlen < IPOPT_OFFSET + sizeof(*cp)) {
1388 code = &cp[IPOPT_OLEN] - (u_char *)ip;
1391 if ((off = cp[IPOPT_OFFSET]) < IPOPT_MINOFF) {
1392 code = &cp[IPOPT_OFFSET] - (u_char *)ip;
1395 ipaddr.sin_addr = ip->ip_dst;
1396 ia = (struct in_ifaddr *)
1397 ifa_ifwithaddr((struct sockaddr *)&ipaddr);
1399 if (opt == IPOPT_SSRR) {
1400 type = ICMP_UNREACH;
1401 code = ICMP_UNREACH_SRCFAIL;
1404 if (!ip_dosourceroute)
1405 goto nosourcerouting;
1407 * Loose routing, and not at next destination
1408 * yet; nothing to do except forward.
1412 off--; /* 0 origin */
1413 if (off > optlen - (int)sizeof(struct in_addr)) {
1415 * End of source route. Should be for us.
1417 if (!ip_acceptsourceroute)
1418 goto nosourcerouting;
1419 save_rte(cp, ip->ip_src);
1424 if (!ip_dosourceroute) {
1426 char buf[16]; /* aaa.bbb.ccc.ddd\0 */
1428 * Acting as a router, so generate ICMP
1431 strcpy(buf, inet_ntoa(ip->ip_dst));
1433 "attempted source route from %s to %s\n",
1434 inet_ntoa(ip->ip_src), buf);
1435 type = ICMP_UNREACH;
1436 code = ICMP_UNREACH_SRCFAIL;
1440 * Not acting as a router,
1444 ipstat.ips_cantforward++;
1451 * locate outgoing interface
1453 (void)memcpy(&ipaddr.sin_addr, cp + off,
1454 sizeof(ipaddr.sin_addr));
1456 if (opt == IPOPT_SSRR) {
1457 #define INA struct in_ifaddr *
1458 #define SA struct sockaddr *
1459 if ((ia = (INA)ifa_ifwithdstaddr((SA)&ipaddr))
1461 ia = (INA)ifa_ifwithnet((SA)&ipaddr);
1463 ia = ip_rtaddr(ipaddr.sin_addr, &ipforward_rt);
1465 type = ICMP_UNREACH;
1466 code = ICMP_UNREACH_SRCFAIL;
1469 ip->ip_dst = ipaddr.sin_addr;
1470 (void)memcpy(cp + off, &(IA_SIN(ia)->sin_addr),
1471 sizeof(struct in_addr));
1472 cp[IPOPT_OFFSET] += sizeof(struct in_addr);
1474 * Let ip_intr's mcast routing check handle mcast pkts
1476 forward = !IN_MULTICAST(ntohl(ip->ip_dst.s_addr));
1480 if (ipstealth && pass == 0)
1482 if (optlen < IPOPT_OFFSET + sizeof(*cp)) {
1483 code = &cp[IPOPT_OFFSET] - (u_char *)ip;
1486 if ((off = cp[IPOPT_OFFSET]) < IPOPT_MINOFF) {
1487 code = &cp[IPOPT_OFFSET] - (u_char *)ip;
1491 * If no space remains, ignore.
1493 off--; /* 0 origin */
1494 if (off > optlen - (int)sizeof(struct in_addr))
1496 (void)memcpy(&ipaddr.sin_addr, &ip->ip_dst,
1497 sizeof(ipaddr.sin_addr));
1499 * locate outgoing interface; if we're the destination,
1500 * use the incoming interface (should be same).
1502 if ((ia = (INA)ifa_ifwithaddr((SA)&ipaddr)) == NULL &&
1503 (ia = ip_rtaddr(ipaddr.sin_addr, &ipforward_rt))
1505 type = ICMP_UNREACH;
1506 code = ICMP_UNREACH_HOST;
1509 (void)memcpy(cp + off, &(IA_SIN(ia)->sin_addr),
1510 sizeof(struct in_addr));
1511 cp[IPOPT_OFFSET] += sizeof(struct in_addr);
1515 if (ipstealth && pass == 0)
1517 code = cp - (u_char *)ip;
1518 if (optlen < 4 || optlen > 40) {
1519 code = &cp[IPOPT_OLEN] - (u_char *)ip;
1522 if ((off = cp[IPOPT_OFFSET]) < 5) {
1523 code = &cp[IPOPT_OLEN] - (u_char *)ip;
1526 if (off > optlen - (int)sizeof(int32_t)) {
1527 cp[IPOPT_OFFSET + 1] += (1 << 4);
1528 if ((cp[IPOPT_OFFSET + 1] & 0xf0) == 0) {
1529 code = &cp[IPOPT_OFFSET] - (u_char *)ip;
1534 off--; /* 0 origin */
1535 sin = (struct in_addr *)(cp + off);
1536 switch (cp[IPOPT_OFFSET + 1] & 0x0f) {
1538 case IPOPT_TS_TSONLY:
1541 case IPOPT_TS_TSANDADDR:
1542 if (off + sizeof(n_time) +
1543 sizeof(struct in_addr) > optlen) {
1544 code = &cp[IPOPT_OFFSET] - (u_char *)ip;
1547 ipaddr.sin_addr = dst;
1548 ia = (INA)ifaof_ifpforaddr((SA)&ipaddr,
1552 (void)memcpy(sin, &IA_SIN(ia)->sin_addr,
1553 sizeof(struct in_addr));
1554 cp[IPOPT_OFFSET] += sizeof(struct in_addr);
1555 off += sizeof(struct in_addr);
1558 case IPOPT_TS_PRESPEC:
1559 if (off + sizeof(n_time) +
1560 sizeof(struct in_addr) > optlen) {
1561 code = &cp[IPOPT_OFFSET] - (u_char *)ip;
1564 (void)memcpy(&ipaddr.sin_addr, sin,
1565 sizeof(struct in_addr));
1566 if (ifa_ifwithaddr((SA)&ipaddr) == NULL)
1568 cp[IPOPT_OFFSET] += sizeof(struct in_addr);
1569 off += sizeof(struct in_addr);
1573 code = &cp[IPOPT_OFFSET + 1] - (u_char *)ip;
1577 (void)memcpy(cp + off, &ntime, sizeof(n_time));
1578 cp[IPOPT_OFFSET] += sizeof(n_time);
1581 if (forward && ipforwarding) {
1582 ip_forward(m, 1, next_hop);
1587 icmp_error(m, type, code, 0, NULL);
1588 ipstat.ips_badoptions++;
1593 * Given address of next destination (final or next hop),
1594 * return internet address info of interface to be used to get there.
1597 ip_rtaddr(struct in_addr dst, struct route *rt)
1599 struct sockaddr_in *sin;
1601 sin = (struct sockaddr_in *)&rt->ro_dst;
1603 if (rt->ro_rt == NULL || dst.s_addr != sin->sin_addr.s_addr) {
1608 sin->sin_family = AF_INET;
1609 sin->sin_len = sizeof(*sin);
1610 sin->sin_addr = dst;
1611 rtalloc_ign(rt, RTF_PRCLONING);
1614 if (rt->ro_rt == NULL)
1617 return (ifatoia(rt->ro_rt->rt_ifa));
1621 * Save incoming source route for use in replies,
1622 * to be picked up later by ip_srcroute if the receiver is interested.
1625 save_rte(u_char *option, struct in_addr dst)
1629 olen = option[IPOPT_OLEN];
1632 printf("save_rte: olen %d\n", olen);
1634 if (olen > sizeof(ip_srcrt) - (1 + sizeof(dst)))
1636 bcopy(option, ip_srcrt.srcopt, olen);
1637 ip_nhops = (olen - IPOPT_OFFSET - 1) / sizeof(struct in_addr);
1642 * Retrieve incoming source route for use in replies,
1643 * in the same form used by setsockopt.
1644 * The first hop is placed before the options, will be removed later.
1649 struct in_addr *p, *q;
1654 m = m_get(M_DONTWAIT, MT_HEADER);
1658 #define OPTSIZ (sizeof(ip_srcrt.nop) + sizeof(ip_srcrt.srcopt))
1660 /* length is (nhops+1)*sizeof(addr) + sizeof(nop + srcrt header) */
1661 m->m_len = ip_nhops * sizeof(struct in_addr) + sizeof(struct in_addr) +
1665 printf("ip_srcroute: nhops %d mlen %d", ip_nhops, m->m_len);
1669 * First save first hop for return route
1671 p = &ip_srcrt.route[ip_nhops - 1];
1672 *(mtod(m, struct in_addr *)) = *p--;
1675 printf(" hops %lx", ntohl(mtod(m, struct in_addr *)->s_addr));
1679 * Copy option fields and padding (nop) to mbuf.
1681 ip_srcrt.nop = IPOPT_NOP;
1682 ip_srcrt.srcopt[IPOPT_OFFSET] = IPOPT_MINOFF;
1683 (void)memcpy(mtod(m, caddr_t) + sizeof(struct in_addr), &ip_srcrt.nop,
1685 q = (struct in_addr *)(mtod(m, caddr_t) +
1686 sizeof(struct in_addr) + OPTSIZ);
1689 * Record return path as an IP source route,
1690 * reversing the path (pointers are now aligned).
1692 while (p >= ip_srcrt.route) {
1695 printf(" %lx", ntohl(q->s_addr));
1700 * Last hop goes to final destination.
1705 printf(" %lx\n", ntohl(q->s_addr));
1711 * Strip out IP options.
1714 ip_stripoptions(struct mbuf *m)
1717 struct ip *ip = mtod(m, struct ip *);
1721 optlen = (IP_VHL_HL(ip->ip_vhl) << 2) - sizeof(struct ip);
1722 opts = (caddr_t)(ip + 1);
1723 datalen = m->m_len - (sizeof(struct ip) + optlen);
1724 bcopy(opts + optlen, opts, datalen);
1726 if (m->m_flags & M_PKTHDR)
1727 m->m_pkthdr.len -= optlen;
1728 ip->ip_vhl = IP_MAKE_VHL(IPVERSION, sizeof(struct ip) >> 2);
1731 u_char inetctlerrmap[PRC_NCMDS] = {
1733 0, EMSGSIZE, EHOSTDOWN, EHOSTUNREACH,
1734 EHOSTUNREACH, EHOSTUNREACH, ECONNREFUSED, ECONNREFUSED,
1735 EMSGSIZE, EHOSTUNREACH, 0, 0,
1737 ENOPROTOOPT, ECONNREFUSED
1741 * Forward a packet. If some error occurs return the sender
1742 * an icmp packet. Note we can't always generate a meaningful
1743 * icmp message because icmp doesn't have a large enough repertoire
1744 * of codes and types.
1746 * If not forwarding, just drop the packet. This could be confusing
1747 * if ipforwarding was zero but some routing protocol was advancing
1748 * us as a gateway to somewhere. However, we must let the routing
1749 * protocol deal with that.
1751 * The using_srcrt parameter indicates whether the packet is being forwarded
1752 * via a source route.
1755 ip_forward(struct mbuf *m, int using_srcrt, struct sockaddr_in *next_hop)
1757 struct ip *ip = mtod(m, struct ip *);
1758 struct sockaddr_in *sin;
1760 int error, type = 0, code = 0;
1763 struct in_addr pkt_dst;
1764 struct ifnet *destifp;
1766 #if defined(IPSEC) || defined(FAST_IPSEC)
1767 struct ifnet dummyifp;
1772 * Cache the destination address of the packet; this may be
1773 * changed by use of 'ipfw fwd'.
1775 pkt_dst = next_hop ? next_hop->sin_addr : ip->ip_dst;
1779 printf("forward: src %lx dst %lx ttl %x\n",
1780 ip->ip_src.s_addr, pkt_dst.s_addr, ip->ip_ttl);
1783 if (m->m_flags & (M_BCAST | M_MCAST) || !in_canforward(pkt_dst)) {
1784 ipstat.ips_cantforward++;
1788 if (!ipstealth && ip->ip_ttl <= IPTTLDEC) {
1789 icmp_error(m, ICMP_TIMXCEED, ICMP_TIMXCEED_INTRANS, dest, NULL);
1793 sin = (struct sockaddr_in *)&ipforward_rt.ro_dst;
1794 if ((rt = ipforward_rt.ro_rt) == NULL ||
1795 pkt_dst.s_addr != sin->sin_addr.s_addr) {
1796 if (ipforward_rt.ro_rt) {
1797 RTFREE(ipforward_rt.ro_rt);
1798 ipforward_rt.ro_rt = NULL;
1800 sin->sin_family = AF_INET;
1801 sin->sin_len = sizeof(*sin);
1802 sin->sin_addr = pkt_dst;
1804 rtalloc_ign(&ipforward_rt, RTF_PRCLONING);
1805 if (ipforward_rt.ro_rt == NULL) {
1806 icmp_error(m, ICMP_UNREACH, ICMP_UNREACH_HOST, dest,
1810 rt = ipforward_rt.ro_rt;
1814 * Save the IP header and at most 8 bytes of the payload,
1815 * in case we need to generate an ICMP message to the src.
1817 * XXX this can be optimized a lot by saving the data in a local
1818 * buffer on the stack (72 bytes at most), and only allocating the
1819 * mbuf if really necessary. The vast majority of the packets
1820 * are forwarded without having to send an ICMP back (either
1821 * because unnecessary, or because rate limited), so we are
1822 * really we are wasting a lot of work here.
1824 * We don't use m_copy() because it might return a reference
1825 * to a shared cluster. Both this function and ip_output()
1826 * assume exclusive access to the IP header in `m', so any
1827 * data in a cluster may change before we reach icmp_error().
1829 MGET(mcopy, M_DONTWAIT, m->m_type);
1830 if (mcopy != NULL && !m_dup_pkthdr(mcopy, m, M_DONTWAIT)) {
1832 * It's probably ok if the pkthdr dup fails (because
1833 * the deep copy of the tag chain failed), but for now
1834 * be conservative and just discard the copy since
1835 * code below may some day want the tags.
1840 if (mcopy != NULL) {
1841 mcopy->m_len = imin((IP_VHL_HL(ip->ip_vhl) << 2) + 8,
1843 m_copydata(m, 0, mcopy->m_len, mtod(mcopy, caddr_t));
1847 ip->ip_ttl -= IPTTLDEC;
1850 * If forwarding packet using same interface that it came in on,
1851 * perhaps should send a redirect to sender to shortcut a hop.
1852 * Only send redirect if source is sending directly to us,
1853 * and if packet was not source routed (or has any options).
1854 * Also, don't send redirect if forwarding using a default route
1855 * or a route modified by a redirect.
1857 if (rt->rt_ifp == m->m_pkthdr.rcvif &&
1858 !(rt->rt_flags & (RTF_DYNAMIC | RTF_MODIFIED)) &&
1859 satosin(rt_key(rt))->sin_addr.s_addr != INADDR_ANY &&
1860 ipsendredirects && !using_srcrt && next_hop != NULL) {
1861 u_long src = ntohl(ip->ip_src.s_addr);
1863 #define RTA(rt) ((struct in_ifaddr *)(rt->rt_ifa))
1864 if (RTA(rt) != NULL &&
1865 (src & RTA(rt)->ia_subnetmask) == RTA(rt)->ia_subnet) {
1866 if (rt->rt_flags & RTF_GATEWAY)
1867 dest = satosin(rt->rt_gateway)->sin_addr.s_addr;
1869 dest = pkt_dst.s_addr;
1871 * Router requirements says to only send
1874 type = ICMP_REDIRECT;
1875 code = ICMP_REDIRECT_HOST;
1878 printf("redirect (%d) to %lx\n", code, dest);
1884 /* Pass IPFORWARD info if available */
1886 tag.mh_type = MT_TAG;
1887 tag.mh_flags = PACKET_TAG_IPFORWARD;
1888 tag.mh_data = (caddr_t)next_hop;
1890 m = (struct mbuf *)&tag;
1893 error = ip_output(m, NULL, &ipforward_rt, IP_FORWARDING, NULL, NULL);
1896 ipstat.ips_cantforward++;
1898 ipstat.ips_forward++;
1900 ipstat.ips_redirectsent++;
1903 ipflow_create(&ipforward_rt, mcopy);
1915 case 0: /* forwarded, but need redirect */
1916 /* type, code set above */
1919 case ENETUNREACH: /* shouldn't happen, checked above */
1924 type = ICMP_UNREACH;
1925 code = ICMP_UNREACH_HOST;
1929 type = ICMP_UNREACH;
1930 code = ICMP_UNREACH_NEEDFRAG;
1933 * If the packet is routed over IPsec tunnel, tell the
1934 * originator the tunnel MTU.
1935 * tunnel MTU = if MTU - sizeof(IP) - ESP/AH hdrsiz
1938 if (ipforward_rt.ro_rt) {
1939 struct secpolicy *sp = NULL;
1944 sp = ipsec4_getpolicybyaddr(mcopy,
1950 destifp = ipforward_rt.ro_rt->rt_ifp;
1952 /* count IPsec header size */
1953 ipsechdr = ipsec4_hdrsiz(mcopy,
1958 * find the correct route for outer IPv4
1959 * header, compute tunnel MTU.
1962 * The "dummyifp" code relies upon the fact
1963 * that icmp_error() touches only ifp->if_mtu.
1968 && sp->req->sav != NULL
1969 && sp->req->sav->sah != NULL) {
1970 ro = &sp->req->sav->sah->sa_route;
1971 if (ro->ro_rt && ro->ro_rt->rt_ifp) {
1973 ro->ro_rt->rt_ifp->if_mtu;
1974 dummyifp.if_mtu -= ipsechdr;
1975 destifp = &dummyifp;
1984 * If the packet is routed over IPsec tunnel, tell the
1985 * originator the tunnel MTU.
1986 * tunnel MTU = if MTU - sizeof(IP) - ESP/AH hdrsiz
1989 if (ipforward_rt.ro_rt) {
1990 struct secpolicy *sp = NULL;
1995 sp = ipsec_getpolicybyaddr(mcopy,
2001 destifp = ipforward_rt.ro_rt->rt_ifp;
2003 /* count IPsec header size */
2004 ipsechdr = ipsec4_hdrsiz(mcopy,
2009 * find the correct route for outer IPv4
2010 * header, compute tunnel MTU.
2013 * The "dummyifp" code relies upon the fact
2014 * that icmp_error() touches only ifp->if_mtu.
2019 && sp->req->sav != NULL
2020 && sp->req->sav->sah != NULL) {
2021 ro = &sp->req->sav->sah->sa_route;
2022 if (ro->ro_rt && ro->ro_rt->rt_ifp) {
2024 ro->ro_rt->rt_ifp->if_mtu;
2025 dummyifp.if_mtu -= ipsechdr;
2026 destifp = &dummyifp;
2033 #else /* !IPSEC && !FAST_IPSEC */
2034 if (ipforward_rt.ro_rt)
2035 destifp = ipforward_rt.ro_rt->rt_ifp;
2037 ipstat.ips_cantfrag++;
2042 * A router should not generate ICMP_SOURCEQUENCH as
2043 * required in RFC1812 Requirements for IP Version 4 Routers.
2044 * Source quench could be a big problem under DoS attacks,
2045 * or if the underlying interface is rate-limited.
2046 * Those who need source quench packets may re-enable them
2047 * via the net.inet.ip.sendsourcequench sysctl.
2049 if (!ip_sendsourcequench) {
2053 type = ICMP_SOURCEQUENCH;
2058 case EACCES: /* ipfw denied packet */
2062 icmp_error(mcopy, type, code, dest, destifp);
2066 ip_savecontrol(struct inpcb *inp, struct mbuf **mp, struct ip *ip,
2069 if (inp->inp_socket->so_options & SO_TIMESTAMP) {
2073 *mp = sbcreatecontrol((caddr_t) &tv, sizeof(tv),
2074 SCM_TIMESTAMP, SOL_SOCKET);
2076 mp = &(*mp)->m_next;
2078 if (inp->inp_flags & INP_RECVDSTADDR) {
2079 *mp = sbcreatecontrol((caddr_t) &ip->ip_dst,
2080 sizeof(struct in_addr), IP_RECVDSTADDR, IPPROTO_IP);
2082 mp = &(*mp)->m_next;
2086 * Moving these out of udp_input() made them even more broken
2087 * than they already were.
2089 /* options were tossed already */
2090 if (inp->inp_flags & INP_RECVOPTS) {
2091 *mp = sbcreatecontrol((caddr_t) opts_deleted_above,
2092 sizeof(struct in_addr), IP_RECVOPTS, IPPROTO_IP);
2094 mp = &(*mp)->m_next;
2096 /* ip_srcroute doesn't do what we want here, need to fix */
2097 if (inp->inp_flags & INP_RECVRETOPTS) {
2098 *mp = sbcreatecontrol((caddr_t) ip_srcroute(),
2099 sizeof(struct in_addr), IP_RECVRETOPTS, IPPROTO_IP);
2101 mp = &(*mp)->m_next;
2104 if (inp->inp_flags & INP_RECVIF) {
2107 struct sockaddr_dl sdl;
2110 struct sockaddr_dl *sdp;
2111 struct sockaddr_dl *sdl2 = &sdlbuf.sdl;
2113 if (((ifp = m->m_pkthdr.rcvif)) &&
2114 ((ifp->if_index != 0) && (ifp->if_index <= if_index))) {
2115 sdp = (struct sockaddr_dl *)
2116 ifnet_addrs[ifp->if_index - 1]->ifa_addr;
2118 * Change our mind and don't try copy.
2120 if ((sdp->sdl_family != AF_LINK) ||
2121 (sdp->sdl_len > sizeof(sdlbuf))) {
2124 bcopy(sdp, sdl2, sdp->sdl_len);
2128 offsetof(struct sockaddr_dl, sdl_data[0]);
2129 sdl2->sdl_family = AF_LINK;
2130 sdl2->sdl_index = 0;
2131 sdl2->sdl_nlen = sdl2->sdl_alen = sdl2->sdl_slen = 0;
2133 *mp = sbcreatecontrol((caddr_t) sdl2, sdl2->sdl_len,
2134 IP_RECVIF, IPPROTO_IP);
2136 mp = &(*mp)->m_next;
2141 * XXX these routines are called from the upper part of the kernel.
2143 * They could also be moved to ip_mroute.c, since all the RSVP
2144 * handling is done there already.
2147 ip_rsvp_init(struct socket *so)
2149 if (so->so_type != SOCK_RAW ||
2150 so->so_proto->pr_protocol != IPPROTO_RSVP)
2153 if (ip_rsvpd != NULL)
2158 * This may seem silly, but we need to be sure we don't over-increment
2159 * the RSVP counter, in case something slips up.
2174 * This may seem silly, but we need to be sure we don't over-decrement
2175 * the RSVP counter, in case something slips up.
2185 rsvp_input(struct mbuf *m, int off, int proto) /* XXX must fixup manually */
2187 if (rsvp_input_p) { /* call the real one if loaded */
2188 rsvp_input_p(m, off, proto);
2192 /* Can still get packets with rsvp_on = 0 if there is a local member
2193 * of the group to which the RSVP packet is addressed. But in this
2194 * case we want to throw the packet away.
2202 if (ip_rsvpd != NULL) {
2203 rip_input(m, off, proto);
2206 /* Drop the packet */