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.14 2004/04/01 23:04:50 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>
64 #include <net/if_types.h>
65 #include <net/if_var.h>
66 #include <net/if_dl.h>
70 #include <net/route.h>
71 #include <net/netisr.h>
72 #include <net/intrq.h>
74 #include <netinet/in.h>
75 #include <netinet/in_systm.h>
76 #include <netinet/in_var.h>
77 #include <netinet/ip.h>
78 #include <netinet/in_pcb.h>
79 #include <netinet/ip_var.h>
80 #include <netinet/ip_icmp.h>
82 #include <netinet/ipprotosw.h>
84 #include <sys/socketvar.h>
86 #include <net/ipfw/ip_fw.h>
87 #include <net/dummynet/ip_dummynet.h>
90 #include <netinet6/ipsec.h>
91 #include <netproto/key/key.h>
95 #include <netipsec/ipsec.h>
96 #include <netipsec/key.h>
100 static int ip_rsvp_on;
101 struct socket *ip_rsvpd;
103 int ipforwarding = 0;
104 SYSCTL_INT(_net_inet_ip, IPCTL_FORWARDING, forwarding, CTLFLAG_RW,
105 &ipforwarding, 0, "Enable IP forwarding between interfaces");
107 static int ipsendredirects = 1; /* XXX */
108 SYSCTL_INT(_net_inet_ip, IPCTL_SENDREDIRECTS, redirect, CTLFLAG_RW,
109 &ipsendredirects, 0, "Enable sending IP redirects");
111 int ip_defttl = IPDEFTTL;
112 SYSCTL_INT(_net_inet_ip, IPCTL_DEFTTL, ttl, CTLFLAG_RW,
113 &ip_defttl, 0, "Maximum TTL on IP packets");
115 static int ip_dosourceroute = 0;
116 SYSCTL_INT(_net_inet_ip, IPCTL_SOURCEROUTE, sourceroute, CTLFLAG_RW,
117 &ip_dosourceroute, 0, "Enable forwarding source routed IP packets");
119 static int ip_acceptsourceroute = 0;
120 SYSCTL_INT(_net_inet_ip, IPCTL_ACCEPTSOURCEROUTE, accept_sourceroute,
121 CTLFLAG_RW, &ip_acceptsourceroute, 0,
122 "Enable accepting source routed IP packets");
124 static int ip_keepfaith = 0;
125 SYSCTL_INT(_net_inet_ip, IPCTL_KEEPFAITH, keepfaith, CTLFLAG_RW,
127 "Enable packet capture for FAITH IPv4->IPv6 translater daemon");
129 static int nipq = 0; /* total # of reass queues */
131 SYSCTL_INT(_net_inet_ip, OID_AUTO, maxfragpackets, CTLFLAG_RW,
133 "Maximum number of IPv4 fragment reassembly queue entries");
135 static int maxfragsperpacket;
136 SYSCTL_INT(_net_inet_ip, OID_AUTO, maxfragsperpacket, CTLFLAG_RW,
137 &maxfragsperpacket, 0,
138 "Maximum number of IPv4 fragments allowed per packet");
140 static int ip_sendsourcequench = 0;
141 SYSCTL_INT(_net_inet_ip, OID_AUTO, sendsourcequench, CTLFLAG_RW,
142 &ip_sendsourcequench, 0,
143 "Enable the transmission of source quench packets");
146 * XXX - Setting ip_checkinterface mostly implements the receive side of
147 * the Strong ES model described in RFC 1122, but since the routing table
148 * and transmit implementation do not implement the Strong ES model,
149 * setting this to 1 results in an odd hybrid.
151 * XXX - ip_checkinterface currently must be disabled if you use ipnat
152 * to translate the destination address to another local interface.
154 * XXX - ip_checkinterface must be disabled if you add IP aliases
155 * to the loopback interface instead of the interface where the
156 * packets for those addresses are received.
158 static int ip_checkinterface = 0;
159 SYSCTL_INT(_net_inet_ip, OID_AUTO, check_interface, CTLFLAG_RW,
160 &ip_checkinterface, 0, "Verify packet arrives on correct interface");
163 static int ipprintfs = 0;
166 static struct ifqueue ipintrq;
167 static int ipqmaxlen = IFQ_MAXLEN;
169 extern struct domain inetdomain;
170 extern struct ipprotosw inetsw[];
171 u_char ip_protox[IPPROTO_MAX];
172 struct in_ifaddrhead in_ifaddrhead; /* first inet address */
173 struct in_ifaddrhashhead *in_ifaddrhashtbl; /* inet addr hash table */
174 u_long in_ifaddrhmask; /* mask for hash table */
175 SYSCTL_INT(_net_inet_ip, IPCTL_INTRQMAXLEN, intr_queue_maxlen, CTLFLAG_RW,
176 &ipintrq.ifq_maxlen, 0, "Maximum size of the IP input queue");
177 SYSCTL_INT(_net_inet_ip, IPCTL_INTRQDROPS, intr_queue_drops, CTLFLAG_RD,
178 &ipintrq.ifq_drops, 0, "Number of packets dropped from the IP input queue");
180 struct ipstat ipstat;
181 SYSCTL_STRUCT(_net_inet_ip, IPCTL_STATS, stats, CTLFLAG_RW,
182 &ipstat, ipstat, "IP statistics (struct ipstat, netinet/ip_var.h)");
184 /* Packet reassembly stuff */
185 #define IPREASS_NHASH_LOG2 6
186 #define IPREASS_NHASH (1 << IPREASS_NHASH_LOG2)
187 #define IPREASS_HMASK (IPREASS_NHASH - 1)
188 #define IPREASS_HASH(x,y) \
189 (((((x) & 0xF) | ((((x) >> 8) & 0xF) << 4)) ^ (y)) & IPREASS_HMASK)
191 static struct ipq ipq[IPREASS_NHASH];
192 const int ipintrq_present = 1;
195 SYSCTL_INT(_net_inet_ip, IPCTL_DEFMTU, mtu, CTLFLAG_RW,
196 &ip_mtu, 0, "Default MTU");
200 static int ipstealth = 0;
201 SYSCTL_INT(_net_inet_ip, OID_AUTO, stealth, CTLFLAG_RW,
207 ip_fw_chk_t *ip_fw_chk_ptr;
212 ip_dn_io_t *ip_dn_io_ptr;
215 struct pfil_head inet_pfil_hook;
216 #endif /* PFIL_HOOKS */
219 * XXX this is ugly -- the following two global variables are
220 * used to store packet state while it travels through the stack.
221 * Note that the code even makes assumptions on the size and
222 * alignment of fields inside struct ip_srcrt so e.g. adding some
223 * fields will break the code. This needs to be fixed.
225 * We need to save the IP options in case a protocol wants to respond
226 * to an incoming packet over the same route if the packet got here
227 * using IP source routing. This allows connection establishment and
228 * maintenance when the remote end is on a network that is not known
231 static int ip_nhops = 0;
232 static struct ip_srcrt {
233 struct in_addr dst; /* final destination */
234 char nop; /* one NOP to align */
235 char srcopt[IPOPT_OFFSET + 1]; /* OPTVAL, OLEN and OFFSET */
236 struct in_addr route[MAX_IPOPTLEN/sizeof(struct in_addr)];
239 static void save_rte(u_char *, struct in_addr);
240 static int ip_dooptions(struct mbuf *m, int,
241 struct sockaddr_in *next_hop);
242 static void ip_forward(struct mbuf *m, int srcrt,
243 struct sockaddr_in *next_hop);
244 static void ip_freef(struct ipq *);
245 static struct mbuf *ip_reass(struct mbuf *, struct ipq *,
246 struct ipq *, u_int32_t *, u_int16_t *);
249 * IP initialization: fill in IP protocol switch table.
250 * All protocols not implemented in kernel go to raw IP protocol handler.
255 struct ipprotosw *pr;
258 TAILQ_INIT(&in_ifaddrhead);
259 in_ifaddrhashtbl = hashinit(INADDR_NHASH, M_IFADDR, &in_ifaddrhmask);
260 pr = (struct ipprotosw *)pffindproto(PF_INET, IPPROTO_RAW, SOCK_RAW);
263 for (i = 0; i < IPPROTO_MAX; i++)
264 ip_protox[i] = pr - inetsw;
265 for (pr = (struct ipprotosw *)inetdomain.dom_protosw;
266 pr < (struct ipprotosw *)inetdomain.dom_protoswNPROTOSW; pr++)
267 if (pr->pr_domain->dom_family == PF_INET &&
268 pr->pr_protocol && pr->pr_protocol != IPPROTO_RAW)
269 ip_protox[pr->pr_protocol] = pr - inetsw;
272 inet_pfil_hook.ph_type = PFIL_TYPE_AF;
273 inet_pfil_hook.ph_af = AF_INET;
274 if ((i = pfil_head_register(&inet_pfil_hook)) != 0)
275 printf("%s: WARNING: unable to register pfil hook, "
276 "error %d\n", __func__, i);
277 #endif /* PFIL_HOOKS */
279 for (i = 0; i < IPREASS_NHASH; i++)
280 ipq[i].next = ipq[i].prev = &ipq[i];
282 maxnipq = nmbclusters / 32;
283 maxfragsperpacket = 16;
286 ip_id = time_second & 0xffff;
288 ipintrq.ifq_maxlen = ipqmaxlen;
290 netisr_register(NETISR_IP, ip_mport, ip_input);
294 * XXX watch out this one. It is perhaps used as a cache for
295 * the most recently used route ? it is cleared in in_addroute()
296 * when a new route is successfully created.
298 struct route ipforward_rt;
299 static struct sockaddr_in ipaddr = { sizeof(ipaddr), AF_INET };
302 * Ip input routine. Checksum and byte swap header. If fragmented
303 * try to reassemble. Process options. Pass to next level.
306 ip_input(struct netmsg *msg)
308 struct mbuf *m = ((struct netmsg_packet *)msg)->nm_packet;
311 struct in_ifaddr *ia = NULL;
313 int i, hlen, checkif;
315 struct in_addr pkt_dst;
316 u_int32_t divert_info = 0; /* packet divert/tee info */
317 struct ip_fw_args args;
318 int srcrt = 0; /* forward (by PFIL_HOOKS) */
320 struct in_addr odst; /* original dst address(NAT) */
324 struct tdb_ident *tdbi;
325 struct secpolicy *sp;
327 #endif /* FAST_IPSEC */
332 args.divert_rule = 0; /* divert cookie */
333 args.next_hop = NULL;
335 /* Grab info from MT_TAG mbufs prepended to the chain. */
336 for (; m && m->m_type == MT_TAG; m = m->m_next) {
337 switch(m->_m_tag_id) {
339 printf("ip_input: unrecognised MT_TAG tag %d\n",
343 case PACKET_TAG_DUMMYNET:
344 args.rule = ((struct dn_pkt *)m)->rule;
347 case PACKET_TAG_DIVERT:
348 args.divert_rule = (int)m->m_hdr.mh_data & 0xffff;
351 case PACKET_TAG_IPFORWARD:
352 args.next_hop = (struct sockaddr_in *)m->m_hdr.mh_data;
357 KASSERT(m != NULL && (m->m_flags & M_PKTHDR) != 0,
358 ("ip_input: no HDR"));
360 if (args.rule) { /* dummynet already filtered us */
361 ip = mtod(m, struct ip *);
362 hlen = IP_VHL_HL(ip->ip_vhl) << 2;
368 /* length checks already done in ip_demux() */
369 KASSERT(m->m_len >= sizeof(ip), ("IP header not in one mbuf"));
371 ip = mtod(m, struct ip *);
373 if (IP_VHL_V(ip->ip_vhl) != IPVERSION) {
374 ipstat.ips_badvers++;
378 hlen = IP_VHL_HL(ip->ip_vhl) << 2;
379 /* length checks already done in ip_demux() */
380 KASSERT(hlen >= sizeof(struct ip), ("IP header len too small"));
381 KASSERT(m->m_len >= hlen, ("packet shorter than IP header length"));
383 /* 127/8 must not appear on wire - RFC1122 */
384 if ((ntohl(ip->ip_dst.s_addr) >> IN_CLASSA_NSHIFT) == IN_LOOPBACKNET ||
385 (ntohl(ip->ip_src.s_addr) >> IN_CLASSA_NSHIFT) == IN_LOOPBACKNET) {
386 if ((m->m_pkthdr.rcvif->if_flags & IFF_LOOPBACK) == 0) {
387 ipstat.ips_badaddr++;
392 if (m->m_pkthdr.csum_flags & CSUM_IP_CHECKED) {
393 sum = !(m->m_pkthdr.csum_flags & CSUM_IP_VALID);
395 if (hlen == sizeof(struct ip)) {
396 sum = in_cksum_hdr(ip);
398 sum = in_cksum(m, hlen);
407 * Convert fields to host representation.
409 ip->ip_len = ntohs(ip->ip_len);
410 if (ip->ip_len < hlen) {
414 ip->ip_off = ntohs(ip->ip_off);
417 * Check that the amount of data in the buffers
418 * is as at least much as the IP header would have us expect.
419 * Trim mbufs if longer than we expect.
420 * Drop packet if shorter than we expect.
422 if (m->m_pkthdr.len < ip->ip_len) {
423 ipstat.ips_tooshort++;
426 if (m->m_pkthdr.len > ip->ip_len) {
427 if (m->m_len == m->m_pkthdr.len) {
428 m->m_len = ip->ip_len;
429 m->m_pkthdr.len = ip->ip_len;
431 m_adj(m, ip->ip_len - m->m_pkthdr.len);
433 #if defined(IPSEC) && !defined(IPSEC_FILTERGIF)
435 * Bypass packet filtering for packets from a tunnel (gif).
437 if (ipsec_gethist(m, NULL))
443 * Right now when no processing on packet has done
444 * and it is still fresh out of network we do our black
446 * - Firewall: deny/allow/divert
447 * - Xlate: translate packet's addr/port (NAT).
448 * - Pipe: pass pkt through dummynet.
449 * - Wrap: fake packet's addr/port <unimpl.>
450 * - Encapsulate: put it in another IP and send out. <unimp.>
456 * Run through list of hooks for input packets.
458 * NB: Beware of the destination address changing (e.g.
459 * by NAT rewriting). When this happens, tell
460 * ip_forward to do the right thing.
463 if (pfil_run_hooks(&inet_pfil_hook, &m, m->m_pkthdr.rcvif,
466 if (m == NULL) /* consumed by filter */
468 ip = mtod(m, struct ip *);
469 srcrt = (odst.s_addr != ip->ip_dst.s_addr);
470 #endif /* PFIL_HOOKS */
471 if (fw_enable && IPFW_LOADED) {
473 * If we've been forwarded from the output side, then
474 * skip the firewall a second time
480 i = ip_fw_chk_ptr(&args);
483 if ( (i & IP_FW_PORT_DENY_FLAG) || m == NULL) { /* drop */
488 ip = mtod(m, struct ip *); /* just in case m changed */
489 if (i == 0 && args.next_hop == NULL) /* common case */
491 if (DUMMYNET_LOADED && (i & IP_FW_PORT_DYNT_FLAG) != 0) {
492 /* Send packet to the appropriate pipe */
493 ip_dn_io_ptr(m, i&0xffff, DN_TO_IP_IN, &args);
497 if (i != 0 && (i & IP_FW_PORT_DYNT_FLAG) == 0) {
498 /* Divert or tee packet */
503 if (i == 0 && args.next_hop != NULL)
506 * if we get here, the packet must be dropped
514 * Process options and, if not destined for us,
515 * ship it on. ip_dooptions returns 1 when an
516 * error was detected (causing an icmp message
517 * to be sent and the original packet to be freed).
519 ip_nhops = 0; /* for source routed packets */
520 if (hlen > sizeof (struct ip) && ip_dooptions(m, 0, args.next_hop))
523 /* greedy RSVP, snatches any PATH packet of the RSVP protocol and no
524 * matter if it is destined to another node, or whether it is
525 * a multicast one, RSVP wants it! and prevents it from being forwarded
526 * anywhere else. Also checks if the rsvp daemon is running before
527 * grabbing the packet.
529 if (rsvp_on && ip->ip_p==IPPROTO_RSVP)
533 * Check our list of addresses, to see if the packet is for us.
534 * If we don't have any addresses, assume any unicast packet
535 * we receive might be for us (and let the upper layers deal
538 if (TAILQ_EMPTY(&in_ifaddrhead) &&
539 (m->m_flags & (M_MCAST|M_BCAST)) == 0)
543 * Cache the destination address of the packet; this may be
544 * changed by use of 'ipfw fwd'.
546 pkt_dst = args.next_hop ? args.next_hop->sin_addr : ip->ip_dst;
549 * Enable a consistency check between the destination address
550 * and the arrival interface for a unicast packet (the RFC 1122
551 * strong ES model) if IP forwarding is disabled and the packet
552 * is not locally generated and the packet is not subject to
555 * XXX - Checking also should be disabled if the destination
556 * address is ipnat'ed to a different interface.
558 * XXX - Checking is incompatible with IP aliases added
559 * to the loopback interface instead of the interface where
560 * the packets are received.
562 checkif = ip_checkinterface && (ipforwarding == 0) &&
563 m->m_pkthdr.rcvif != NULL &&
564 ((m->m_pkthdr.rcvif->if_flags & IFF_LOOPBACK) == 0) &&
565 (args.next_hop == NULL);
568 * Check for exact addresses in the hash bucket.
570 LIST_FOREACH(ia, INADDR_HASH(pkt_dst.s_addr), ia_hash) {
572 * If the address matches, verify that the packet
573 * arrived via the correct interface if checking is
576 if (IA_SIN(ia)->sin_addr.s_addr == pkt_dst.s_addr &&
577 (!checkif || ia->ia_ifp == m->m_pkthdr.rcvif))
581 * Check for broadcast addresses.
583 * Only accept broadcast packets that arrive via the matching
584 * interface. Reception of forwarded directed broadcasts would
585 * be handled via ip_forward() and ether_output() with the loopback
586 * into the stack for SIMPLEX interfaces handled by ether_output().
588 if (m->m_pkthdr.rcvif->if_flags & IFF_BROADCAST) {
589 TAILQ_FOREACH(ifa, &m->m_pkthdr.rcvif->if_addrhead, ifa_link) {
590 if (ifa->ifa_addr->sa_family != AF_INET)
593 if (satosin(&ia->ia_broadaddr)->sin_addr.s_addr ==
596 if (ia->ia_netbroadcast.s_addr == pkt_dst.s_addr)
599 if (IA_SIN(ia)->sin_addr.s_addr == INADDR_ANY)
604 if (IN_MULTICAST(ntohl(ip->ip_dst.s_addr))) {
605 struct in_multi *inm;
608 * If we are acting as a multicast router, all
609 * incoming multicast packets are passed to the
610 * kernel-level multicast forwarding function.
611 * The packet is returned (relatively) intact; if
612 * ip_mforward() returns a non-zero value, the packet
613 * must be discarded, else it may be accepted below.
616 ip_mforward(ip, m->m_pkthdr.rcvif, m, 0) != 0) {
617 ipstat.ips_cantforward++;
623 * The process-level routing daemon needs to receive
624 * all multicast IGMP packets, whether or not this
625 * host belongs to their destination groups.
627 if (ip->ip_p == IPPROTO_IGMP)
629 ipstat.ips_forward++;
632 * See if we belong to the destination multicast group on the
635 IN_LOOKUP_MULTI(ip->ip_dst, m->m_pkthdr.rcvif, inm);
637 ipstat.ips_notmember++;
643 if (ip->ip_dst.s_addr == (u_long)INADDR_BROADCAST)
645 if (ip->ip_dst.s_addr == INADDR_ANY)
649 * FAITH(Firewall Aided Internet Translator)
651 if (m->m_pkthdr.rcvif && m->m_pkthdr.rcvif->if_type == IFT_FAITH) {
653 if (ip->ip_p == IPPROTO_TCP || ip->ip_p == IPPROTO_ICMP)
661 * Not for us; forward if possible and desirable.
663 if (ipforwarding == 0) {
664 ipstat.ips_cantforward++;
669 * Enforce inbound IPsec SPD.
671 if (ipsec4_in_reject(m, NULL)) {
672 ipsecstat.in_polvio++;
677 mtag = m_tag_find(m, PACKET_TAG_IPSEC_IN_DONE, NULL);
680 tdbi = (struct tdb_ident *)(mtag + 1);
681 sp = ipsec_getpolicy(tdbi, IPSEC_DIR_INBOUND);
683 sp = ipsec_getpolicybyaddr(m, IPSEC_DIR_INBOUND,
684 IP_FORWARDING, &error);
686 if (sp == NULL) { /* NB: can happen if error */
688 /*XXX error stat???*/
689 DPRINTF(("ip_input: no SP for forwarding\n")); /*XXX*/
694 * Check security policy against packet attributes.
696 error = ipsec_in_reject(sp, m);
700 ipstat.ips_cantforward++;
703 #endif /* FAST_IPSEC */
704 ip_forward(m, srcrt, args.next_hop);
711 * IPSTEALTH: Process non-routing options only
712 * if the packet is destined for us.
714 if (ipstealth && hlen > sizeof (struct ip) &&
715 ip_dooptions(m, 1, args.next_hop))
717 #endif /* IPSTEALTH */
719 /* Count the packet in the ip address stats */
721 ia->ia_ifa.if_ipackets++;
722 ia->ia_ifa.if_ibytes += m->m_pkthdr.len;
726 * If offset or IP_MF are set, must reassemble.
727 * Otherwise, nothing need be done.
728 * (We could look in the reassembly queue to see
729 * if the packet was previously fragmented,
730 * but it's not worth the time; just let them time out.)
732 if (ip->ip_off & (IP_MF | IP_OFFMASK)) {
734 /* If maxnipq is 0, never accept fragments. */
736 ipstat.ips_fragments++;
737 ipstat.ips_fragdropped++;
741 sum = IPREASS_HASH(ip->ip_src.s_addr, ip->ip_id);
743 * Look for queue of fragments
746 for (fp = ipq[sum].next; fp != &ipq[sum]; fp = fp->next)
747 if (ip->ip_id == fp->ipq_id &&
748 ip->ip_src.s_addr == fp->ipq_src.s_addr &&
749 ip->ip_dst.s_addr == fp->ipq_dst.s_addr &&
750 ip->ip_p == fp->ipq_p)
756 * Enforce upper bound on number of fragmented packets
757 * for which we attempt reassembly;
758 * If maxnipq is -1, accept all fragments without limitation.
760 if ((nipq > maxnipq) && (maxnipq > 0)) {
762 * drop something from the tail of the current queue
763 * before proceeding further
765 if (ipq[sum].prev == &ipq[sum]) { /* gak */
766 for (i = 0; i < IPREASS_NHASH; i++) {
767 if (ipq[i].prev != &ipq[i]) {
768 ipstat.ips_fragtimeout +=
769 ipq[i].prev->ipq_nfrags;
770 ip_freef(ipq[i].prev);
775 ipstat.ips_fragtimeout += ipq[sum].prev->ipq_nfrags;
776 ip_freef(ipq[sum].prev);
781 * Adjust ip_len to not reflect header,
782 * convert offset of this to bytes.
785 if (ip->ip_off & IP_MF) {
787 * Make sure that fragments have a data length
788 * that's a non-zero multiple of 8 bytes.
790 if (ip->ip_len == 0 || (ip->ip_len & 0x7) != 0) {
791 ipstat.ips_toosmall++; /* XXX */
794 m->m_flags |= M_FRAG;
796 m->m_flags &= ~M_FRAG;
800 * Attempt reassembly; if it succeeds, proceed.
801 * ip_reass() will return a different mbuf, and update
802 * the divert info in divert_info and args.divert_rule.
804 ipstat.ips_fragments++;
805 m->m_pkthdr.header = ip;
807 fp, &ipq[sum], &divert_info, &args.divert_rule);
810 ipstat.ips_reassembled++;
811 ip = mtod(m, struct ip *);
812 /* Get the header length of the reassembled packet */
813 hlen = IP_VHL_HL(ip->ip_vhl) << 2;
815 /* Restore original checksum before diverting packet */
816 if (divert_info != 0) {
818 ip->ip_len = htons(ip->ip_len);
819 ip->ip_off = htons(ip->ip_off);
821 if (hlen == sizeof(struct ip))
822 ip->ip_sum = in_cksum_hdr(ip);
824 ip->ip_sum = in_cksum(m, hlen);
825 ip->ip_off = ntohs(ip->ip_off);
826 ip->ip_len = ntohs(ip->ip_len);
836 * Divert or tee packet to the divert protocol if required.
838 if (divert_info != 0) {
839 struct mbuf *clone = NULL;
841 /* Clone packet if we're doing a 'tee' */
842 if ((divert_info & IP_FW_PORT_TEE_FLAG) != 0)
843 clone = m_dup(m, M_DONTWAIT);
845 /* Restore packet header fields to original values */
847 ip->ip_len = htons(ip->ip_len);
848 ip->ip_off = htons(ip->ip_off);
850 /* Deliver packet to divert input routine */
851 divert_packet(m, 1, divert_info & 0xffff, args.divert_rule);
852 ipstat.ips_delivered++;
854 /* If 'tee', continue with original packet */
858 ip = mtod(m, struct ip *);
861 * Jump backwards to complete processing of the
862 * packet. But first clear divert_info to avoid
863 * entering this block again.
864 * We do not need to clear args.divert_rule
865 * or args.next_hop as they will not be used.
874 * enforce IPsec policy checking if we are seeing last header.
875 * note that we do not visit this with protocols with pcb layer
876 * code - like udp/tcp/raw ip.
878 if ((inetsw[ip_protox[ip->ip_p]].pr_flags & PR_LASTHDR) != 0 &&
879 ipsec4_in_reject(m, NULL)) {
880 ipsecstat.in_polvio++;
886 * enforce IPsec policy checking if we are seeing last header.
887 * note that we do not visit this with protocols with pcb layer
888 * code - like udp/tcp/raw ip.
890 if ((inetsw[ip_protox[ip->ip_p]].pr_flags & PR_LASTHDR) != 0) {
892 * Check if the packet has already had IPsec processing
893 * done. If so, then just pass it along. This tag gets
894 * set during AH, ESP, etc. input handling, before the
895 * packet is returned to the ip input queue for delivery.
897 mtag = m_tag_find(m, PACKET_TAG_IPSEC_IN_DONE, NULL);
900 tdbi = (struct tdb_ident *)(mtag + 1);
901 sp = ipsec_getpolicy(tdbi, IPSEC_DIR_INBOUND);
903 sp = ipsec_getpolicybyaddr(m, IPSEC_DIR_INBOUND,
904 IP_FORWARDING, &error);
908 * Check security policy against packet attributes.
910 error = ipsec_in_reject(sp, m);
913 /* XXX error stat??? */
915 DPRINTF(("ip_input: no SP, packet discarded\n"));/*XXX*/
922 #endif /* FAST_IPSEC */
925 * Switch out to protocol's input routine.
927 * XXX queue packet to protocol's message port.
929 ipstat.ips_delivered++;
930 if (args.next_hop && ip->ip_p == IPPROTO_TCP) {
931 /* TCP needs IPFORWARD info if available */
934 tag.mh_type = MT_TAG;
935 tag.mh_flags = PACKET_TAG_IPFORWARD;
936 tag.mh_data = (caddr_t)args.next_hop;
939 (*inetsw[ip_protox[ip->ip_p]].pr_input)(
940 (struct mbuf *)&tag, hlen, ip->ip_p);
942 (*inetsw[ip_protox[ip->ip_p]].pr_input)(m, hlen, ip->ip_p);
950 * Take incoming datagram fragment and try to reassemble it into
951 * whole datagram. If a chain for reassembly of this datagram already
952 * exists, then it is given as fp; otherwise have to make a chain.
954 * When IPDIVERT enabled, keep additional state with each packet that
955 * tells us if we need to divert or tee the packet we're building.
956 * In particular, *divinfo includes the port and TEE flag,
957 * *divert_rule is the number of the matching rule.
961 ip_reass(struct mbuf *m, struct ipq *fp, struct ipq *where,
962 u_int32_t *divinfo, u_int16_t *divert_rule)
964 struct ip *ip = mtod(m, struct ip *);
965 struct mbuf *p = 0, *q, *nq;
967 int hlen = IP_VHL_HL(ip->ip_vhl) << 2;
971 * Presence of header sizes in mbufs
972 * would confuse code below.
978 * If first fragment to arrive, create a reassembly queue.
981 if ((t = m_get(M_DONTWAIT, MT_FTABLE)) == NULL)
983 fp = mtod(t, struct ipq *);
987 fp->ipq_ttl = IPFRAGTTL;
988 fp->ipq_p = ip->ip_p;
989 fp->ipq_id = ip->ip_id;
990 fp->ipq_src = ip->ip_src;
991 fp->ipq_dst = ip->ip_dst;
995 fp->ipq_div_info = 0;
996 fp->ipq_div_cookie = 0;
1003 #define GETIP(m) ((struct ip*)((m)->m_pkthdr.header))
1006 * Find a segment which begins after this one does.
1008 for (p = NULL, q = fp->ipq_frags; q; p = q, q = q->m_nextpkt)
1009 if (GETIP(q)->ip_off > ip->ip_off)
1013 * If there is a preceding segment, it may provide some of
1014 * our data already. If so, drop the data from the incoming
1015 * segment. If it provides all of our data, drop us, otherwise
1016 * stick new segment in the proper place.
1018 * If some of the data is dropped from the the preceding
1019 * segment, then it's checksum is invalidated.
1022 i = GETIP(p)->ip_off + GETIP(p)->ip_len - ip->ip_off;
1024 if (i >= ip->ip_len)
1027 m->m_pkthdr.csum_flags = 0;
1031 m->m_nextpkt = p->m_nextpkt;
1034 m->m_nextpkt = fp->ipq_frags;
1039 * While we overlap succeeding segments trim them or,
1040 * if they are completely covered, dequeue them.
1042 for (; q != NULL && ip->ip_off + ip->ip_len > GETIP(q)->ip_off;
1044 i = (ip->ip_off + ip->ip_len) -
1046 if (i < GETIP(q)->ip_len) {
1047 GETIP(q)->ip_len -= i;
1048 GETIP(q)->ip_off += i;
1050 q->m_pkthdr.csum_flags = 0;
1055 ipstat.ips_fragdropped++;
1064 * Transfer firewall instructions to the fragment structure.
1065 * Only trust info in the fragment at offset 0.
1067 if (ip->ip_off == 0) {
1068 fp->ipq_div_info = *divinfo;
1069 fp->ipq_div_cookie = *divert_rule;
1076 * Check for complete reassembly and perform frag per packet
1079 * Frag limiting is performed here so that the nth frag has
1080 * a chance to complete the packet before we drop the packet.
1081 * As a result, n+1 frags are actually allowed per packet, but
1082 * only n will ever be stored. (n = maxfragsperpacket.)
1086 for (p = NULL, q = fp->ipq_frags; q; p = q, q = q->m_nextpkt) {
1087 if (GETIP(q)->ip_off != next) {
1088 if (fp->ipq_nfrags > maxfragsperpacket) {
1089 ipstat.ips_fragdropped += fp->ipq_nfrags;
1094 next += GETIP(q)->ip_len;
1096 /* Make sure the last packet didn't have the IP_MF flag */
1097 if (p->m_flags & M_FRAG) {
1098 if (fp->ipq_nfrags > maxfragsperpacket) {
1099 ipstat.ips_fragdropped += fp->ipq_nfrags;
1106 * Reassembly is complete. Make sure the packet is a sane size.
1110 if (next + (IP_VHL_HL(ip->ip_vhl) << 2) > IP_MAXPACKET) {
1111 ipstat.ips_toolong++;
1112 ipstat.ips_fragdropped += fp->ipq_nfrags;
1118 * Concatenate fragments.
1126 for (q = nq; q != NULL; q = nq) {
1128 q->m_nextpkt = NULL;
1129 m->m_pkthdr.csum_flags &= q->m_pkthdr.csum_flags;
1130 m->m_pkthdr.csum_data += q->m_pkthdr.csum_data;
1136 * Extract firewall instructions from the fragment structure.
1138 *divinfo = fp->ipq_div_info;
1139 *divert_rule = fp->ipq_div_cookie;
1143 * Create header for new ip packet by
1144 * modifying header of first packet;
1145 * dequeue and discard fragment reassembly header.
1146 * Make header visible.
1149 ip->ip_src = fp->ipq_src;
1150 ip->ip_dst = fp->ipq_dst;
1153 (void) m_free(dtom(fp));
1154 m->m_len += (IP_VHL_HL(ip->ip_vhl) << 2);
1155 m->m_data -= (IP_VHL_HL(ip->ip_vhl) << 2);
1156 /* some debugging cruft by sklower, below, will go away soon */
1157 if (m->m_flags & M_PKTHDR) { /* XXX this should be done elsewhere */
1159 for (t = m; t; t = t->m_next)
1161 m->m_pkthdr.len = plen;
1170 ipstat.ips_fragdropped++;
1180 * Free a fragment reassembly header and all
1181 * associated datagrams.
1189 while (fp->ipq_frags) {
1191 fp->ipq_frags = q->m_nextpkt;
1195 (void) m_free(dtom(fp));
1200 * IP timer processing;
1201 * if a timer expires on a reassembly
1202 * queue, discard it.
1211 for (i = 0; i < IPREASS_NHASH; i++) {
1215 while (fp != &ipq[i]) {
1218 if (fp->prev->ipq_ttl == 0) {
1219 ipstat.ips_fragtimeout += fp->prev->ipq_nfrags;
1225 * If we are over the maximum number of fragments
1226 * (due to the limit being lowered), drain off
1227 * enough to get down to the new limit.
1229 if (maxnipq >= 0 && nipq > maxnipq) {
1230 for (i = 0; i < IPREASS_NHASH; i++) {
1231 while (nipq > maxnipq &&
1232 (ipq[i].next != &ipq[i])) {
1233 ipstat.ips_fragdropped +=
1234 ipq[i].next->ipq_nfrags;
1235 ip_freef(ipq[i].next);
1244 * Drain off all datagram fragments.
1251 for (i = 0; i < IPREASS_NHASH; i++) {
1252 while (ipq[i].next != &ipq[i]) {
1253 ipstat.ips_fragdropped += ipq[i].next->ipq_nfrags;
1254 ip_freef(ipq[i].next);
1261 * Do option processing on a datagram,
1262 * possibly discarding it if bad options are encountered,
1263 * or forwarding it if source-routed.
1264 * The pass argument is used when operating in the IPSTEALTH
1265 * mode to tell what options to process:
1266 * [LS]SRR (pass 0) or the others (pass 1).
1267 * The reason for as many as two passes is that when doing IPSTEALTH,
1268 * non-routing options should be processed only if the packet is for us.
1269 * Returns 1 if packet has been forwarded/freed,
1270 * 0 if the packet should be processed further.
1273 ip_dooptions(struct mbuf *m, int pass, struct sockaddr_in *next_hop)
1275 struct ip *ip = mtod(m, struct ip *);
1277 struct in_ifaddr *ia;
1278 int opt, optlen, cnt, off, code, type = ICMP_PARAMPROB, forward = 0;
1279 struct in_addr *sin, dst;
1283 cp = (u_char *)(ip + 1);
1284 cnt = (IP_VHL_HL(ip->ip_vhl) << 2) - sizeof (struct ip);
1285 for (; cnt > 0; cnt -= optlen, cp += optlen) {
1286 opt = cp[IPOPT_OPTVAL];
1287 if (opt == IPOPT_EOL)
1289 if (opt == IPOPT_NOP)
1292 if (cnt < IPOPT_OLEN + sizeof(*cp)) {
1293 code = &cp[IPOPT_OLEN] - (u_char *)ip;
1296 optlen = cp[IPOPT_OLEN];
1297 if (optlen < IPOPT_OLEN + sizeof(*cp) || optlen > cnt) {
1298 code = &cp[IPOPT_OLEN] - (u_char *)ip;
1308 * Source routing with record.
1309 * Find interface with current destination address.
1310 * If none on this machine then drop if strictly routed,
1311 * or do nothing if loosely routed.
1312 * Record interface address and bring up next address
1313 * component. If strictly routed make sure next
1314 * address is on directly accessible net.
1319 if (ipstealth && pass > 0)
1322 if (optlen < IPOPT_OFFSET + sizeof(*cp)) {
1323 code = &cp[IPOPT_OLEN] - (u_char *)ip;
1326 if ((off = cp[IPOPT_OFFSET]) < IPOPT_MINOFF) {
1327 code = &cp[IPOPT_OFFSET] - (u_char *)ip;
1330 ipaddr.sin_addr = ip->ip_dst;
1331 ia = (struct in_ifaddr *)
1332 ifa_ifwithaddr((struct sockaddr *)&ipaddr);
1334 if (opt == IPOPT_SSRR) {
1335 type = ICMP_UNREACH;
1336 code = ICMP_UNREACH_SRCFAIL;
1339 if (!ip_dosourceroute)
1340 goto nosourcerouting;
1342 * Loose routing, and not at next destination
1343 * yet; nothing to do except forward.
1347 off--; /* 0 origin */
1348 if (off > optlen - (int)sizeof(struct in_addr)) {
1350 * End of source route. Should be for us.
1352 if (!ip_acceptsourceroute)
1353 goto nosourcerouting;
1354 save_rte(cp, ip->ip_src);
1361 if (!ip_dosourceroute) {
1363 char buf[16]; /* aaa.bbb.ccc.ddd\0 */
1365 * Acting as a router, so generate ICMP
1368 strcpy(buf, inet_ntoa(ip->ip_dst));
1370 "attempted source route from %s to %s\n",
1371 inet_ntoa(ip->ip_src), buf);
1372 type = ICMP_UNREACH;
1373 code = ICMP_UNREACH_SRCFAIL;
1377 * Not acting as a router, so silently drop.
1382 ipstat.ips_cantforward++;
1389 * locate outgoing interface
1391 (void)memcpy(&ipaddr.sin_addr, cp + off,
1392 sizeof(ipaddr.sin_addr));
1394 if (opt == IPOPT_SSRR) {
1395 #define INA struct in_ifaddr *
1396 #define SA struct sockaddr *
1397 if ((ia = (INA)ifa_ifwithdstaddr((SA)&ipaddr)) == 0)
1398 ia = (INA)ifa_ifwithnet((SA)&ipaddr);
1400 ia = ip_rtaddr(ipaddr.sin_addr, &ipforward_rt);
1402 type = ICMP_UNREACH;
1403 code = ICMP_UNREACH_SRCFAIL;
1406 ip->ip_dst = ipaddr.sin_addr;
1407 (void)memcpy(cp + off, &(IA_SIN(ia)->sin_addr),
1408 sizeof(struct in_addr));
1409 cp[IPOPT_OFFSET] += sizeof(struct in_addr);
1411 * Let ip_intr's mcast routing check handle mcast pkts
1413 forward = !IN_MULTICAST(ntohl(ip->ip_dst.s_addr));
1418 if (ipstealth && pass == 0)
1421 if (optlen < IPOPT_OFFSET + sizeof(*cp)) {
1422 code = &cp[IPOPT_OFFSET] - (u_char *)ip;
1425 if ((off = cp[IPOPT_OFFSET]) < IPOPT_MINOFF) {
1426 code = &cp[IPOPT_OFFSET] - (u_char *)ip;
1430 * If no space remains, ignore.
1432 off--; /* 0 origin */
1433 if (off > optlen - (int)sizeof(struct in_addr))
1435 (void)memcpy(&ipaddr.sin_addr, &ip->ip_dst,
1436 sizeof(ipaddr.sin_addr));
1438 * locate outgoing interface; if we're the destination,
1439 * use the incoming interface (should be same).
1441 if ((ia = (INA)ifa_ifwithaddr((SA)&ipaddr)) == 0 &&
1442 (ia = ip_rtaddr(ipaddr.sin_addr,
1443 &ipforward_rt)) == 0) {
1444 type = ICMP_UNREACH;
1445 code = ICMP_UNREACH_HOST;
1448 (void)memcpy(cp + off, &(IA_SIN(ia)->sin_addr),
1449 sizeof(struct in_addr));
1450 cp[IPOPT_OFFSET] += sizeof(struct in_addr);
1455 if (ipstealth && pass == 0)
1458 code = cp - (u_char *)ip;
1459 if (optlen < 4 || optlen > 40) {
1460 code = &cp[IPOPT_OLEN] - (u_char *)ip;
1463 if ((off = cp[IPOPT_OFFSET]) < 5) {
1464 code = &cp[IPOPT_OLEN] - (u_char *)ip;
1467 if (off > optlen - (int)sizeof(int32_t)) {
1468 cp[IPOPT_OFFSET + 1] += (1 << 4);
1469 if ((cp[IPOPT_OFFSET + 1] & 0xf0) == 0) {
1470 code = &cp[IPOPT_OFFSET] - (u_char *)ip;
1475 off--; /* 0 origin */
1476 sin = (struct in_addr *)(cp + off);
1477 switch (cp[IPOPT_OFFSET + 1] & 0x0f) {
1479 case IPOPT_TS_TSONLY:
1482 case IPOPT_TS_TSANDADDR:
1483 if (off + sizeof(n_time) +
1484 sizeof(struct in_addr) > optlen) {
1485 code = &cp[IPOPT_OFFSET] - (u_char *)ip;
1488 ipaddr.sin_addr = dst;
1489 ia = (INA)ifaof_ifpforaddr((SA)&ipaddr,
1493 (void)memcpy(sin, &IA_SIN(ia)->sin_addr,
1494 sizeof(struct in_addr));
1495 cp[IPOPT_OFFSET] += sizeof(struct in_addr);
1496 off += sizeof(struct in_addr);
1499 case IPOPT_TS_PRESPEC:
1500 if (off + sizeof(n_time) +
1501 sizeof(struct in_addr) > optlen) {
1502 code = &cp[IPOPT_OFFSET] - (u_char *)ip;
1505 (void)memcpy(&ipaddr.sin_addr, sin,
1506 sizeof(struct in_addr));
1507 if (ifa_ifwithaddr((SA)&ipaddr) == 0)
1509 cp[IPOPT_OFFSET] += sizeof(struct in_addr);
1510 off += sizeof(struct in_addr);
1514 code = &cp[IPOPT_OFFSET + 1] - (u_char *)ip;
1518 (void)memcpy(cp + off, &ntime, sizeof(n_time));
1519 cp[IPOPT_OFFSET] += sizeof(n_time);
1522 if (forward && ipforwarding) {
1523 ip_forward(m, 1, next_hop);
1528 icmp_error(m, type, code, 0, 0);
1529 ipstat.ips_badoptions++;
1534 * Given address of next destination (final or next hop),
1535 * return internet address info of interface to be used to get there.
1542 struct sockaddr_in *sin;
1544 sin = (struct sockaddr_in *)&rt->ro_dst;
1546 if (rt->ro_rt == 0 ||
1547 dst.s_addr != sin->sin_addr.s_addr) {
1552 sin->sin_family = AF_INET;
1553 sin->sin_len = sizeof(*sin);
1554 sin->sin_addr = dst;
1556 rtalloc_ign(rt, RTF_PRCLONING);
1559 return ((struct in_ifaddr *)0);
1560 return (ifatoia(rt->ro_rt->rt_ifa));
1564 * Save incoming source route for use in replies,
1565 * to be picked up later by ip_srcroute if the receiver is interested.
1568 save_rte(option, dst)
1574 olen = option[IPOPT_OLEN];
1577 printf("save_rte: olen %d\n", olen);
1579 if (olen > sizeof(ip_srcrt) - (1 + sizeof(dst)))
1581 bcopy(option, ip_srcrt.srcopt, olen);
1582 ip_nhops = (olen - IPOPT_OFFSET - 1) / sizeof(struct in_addr);
1587 * Retrieve incoming source route for use in replies,
1588 * in the same form used by setsockopt.
1589 * The first hop is placed before the options, will be removed later.
1594 struct in_addr *p, *q;
1598 return ((struct mbuf *)0);
1599 m = m_get(M_DONTWAIT, MT_HEADER);
1601 return ((struct mbuf *)0);
1603 #define OPTSIZ (sizeof(ip_srcrt.nop) + sizeof(ip_srcrt.srcopt))
1605 /* length is (nhops+1)*sizeof(addr) + sizeof(nop + srcrt header) */
1606 m->m_len = ip_nhops * sizeof(struct in_addr) + sizeof(struct in_addr) +
1610 printf("ip_srcroute: nhops %d mlen %d", ip_nhops, m->m_len);
1614 * First save first hop for return route
1616 p = &ip_srcrt.route[ip_nhops - 1];
1617 *(mtod(m, struct in_addr *)) = *p--;
1620 printf(" hops %lx", (u_long)ntohl(mtod(m, struct in_addr *)->s_addr));
1624 * Copy option fields and padding (nop) to mbuf.
1626 ip_srcrt.nop = IPOPT_NOP;
1627 ip_srcrt.srcopt[IPOPT_OFFSET] = IPOPT_MINOFF;
1628 (void)memcpy(mtod(m, caddr_t) + sizeof(struct in_addr),
1629 &ip_srcrt.nop, OPTSIZ);
1630 q = (struct in_addr *)(mtod(m, caddr_t) +
1631 sizeof(struct in_addr) + OPTSIZ);
1634 * Record return path as an IP source route,
1635 * reversing the path (pointers are now aligned).
1637 while (p >= ip_srcrt.route) {
1640 printf(" %lx", (u_long)ntohl(q->s_addr));
1645 * Last hop goes to final destination.
1650 printf(" %lx\n", (u_long)ntohl(q->s_addr));
1656 * Strip out IP options.
1659 ip_stripoptions(struct mbuf *m)
1662 struct ip *ip = mtod(m, struct ip *);
1666 optlen = (IP_VHL_HL(ip->ip_vhl) << 2) - sizeof(struct ip);
1667 opts = (caddr_t)(ip + 1);
1668 datalen = m->m_len - (sizeof(struct ip) + optlen);
1669 bcopy(opts + optlen, opts, datalen);
1671 if (m->m_flags & M_PKTHDR)
1672 m->m_pkthdr.len -= optlen;
1673 ip->ip_vhl = IP_MAKE_VHL(IPVERSION, sizeof(struct ip) >> 2);
1676 u_char inetctlerrmap[PRC_NCMDS] = {
1678 0, EMSGSIZE, EHOSTDOWN, EHOSTUNREACH,
1679 EHOSTUNREACH, EHOSTUNREACH, ECONNREFUSED, ECONNREFUSED,
1680 EMSGSIZE, EHOSTUNREACH, 0, 0,
1682 ENOPROTOOPT, ECONNREFUSED
1686 * Forward a packet. If some error occurs return the sender
1687 * an icmp packet. Note we can't always generate a meaningful
1688 * icmp message because icmp doesn't have a large enough repertoire
1689 * of codes and types.
1691 * If not forwarding, just drop the packet. This could be confusing
1692 * if ipforwarding was zero but some routing protocol was advancing
1693 * us as a gateway to somewhere. However, we must let the routing
1694 * protocol deal with that.
1696 * The srcrt parameter indicates whether the packet is being forwarded
1697 * via a source route.
1700 ip_forward(struct mbuf *m, int srcrt, struct sockaddr_in *next_hop)
1702 struct ip *ip = mtod(m, struct ip *);
1703 struct sockaddr_in *sin;
1705 int error, type = 0, code = 0;
1708 struct in_addr pkt_dst;
1709 struct ifnet *destifp;
1710 #if defined(IPSEC) || defined(FAST_IPSEC)
1711 struct ifnet dummyifp;
1716 * Cache the destination address of the packet; this may be
1717 * changed by use of 'ipfw fwd'.
1719 pkt_dst = next_hop ? next_hop->sin_addr : ip->ip_dst;
1723 printf("forward: src %lx dst %lx ttl %x\n",
1724 (u_long)ip->ip_src.s_addr, (u_long)pkt_dst.s_addr,
1729 if (m->m_flags & (M_BCAST|M_MCAST) || in_canforward(pkt_dst) == 0) {
1730 ipstat.ips_cantforward++;
1737 if (ip->ip_ttl <= IPTTLDEC) {
1738 icmp_error(m, ICMP_TIMXCEED, ICMP_TIMXCEED_INTRANS,
1746 sin = (struct sockaddr_in *)&ipforward_rt.ro_dst;
1747 if ((rt = ipforward_rt.ro_rt) == 0 ||
1748 pkt_dst.s_addr != sin->sin_addr.s_addr) {
1749 if (ipforward_rt.ro_rt) {
1750 RTFREE(ipforward_rt.ro_rt);
1751 ipforward_rt.ro_rt = 0;
1753 sin->sin_family = AF_INET;
1754 sin->sin_len = sizeof(*sin);
1755 sin->sin_addr = pkt_dst;
1757 rtalloc_ign(&ipforward_rt, RTF_PRCLONING);
1758 if (ipforward_rt.ro_rt == 0) {
1759 icmp_error(m, ICMP_UNREACH, ICMP_UNREACH_HOST, dest, 0);
1762 rt = ipforward_rt.ro_rt;
1766 * Save the IP header and at most 8 bytes of the payload,
1767 * in case we need to generate an ICMP message to the src.
1769 * XXX this can be optimized a lot by saving the data in a local
1770 * buffer on the stack (72 bytes at most), and only allocating the
1771 * mbuf if really necessary. The vast majority of the packets
1772 * are forwarded without having to send an ICMP back (either
1773 * because unnecessary, or because rate limited), so we are
1774 * really we are wasting a lot of work here.
1776 * We don't use m_copy() because it might return a reference
1777 * to a shared cluster. Both this function and ip_output()
1778 * assume exclusive access to the IP header in `m', so any
1779 * data in a cluster may change before we reach icmp_error().
1781 MGET(mcopy, M_DONTWAIT, m->m_type);
1782 if (mcopy != NULL && !m_dup_pkthdr(mcopy, m, M_DONTWAIT)) {
1784 * It's probably ok if the pkthdr dup fails (because
1785 * the deep copy of the tag chain failed), but for now
1786 * be conservative and just discard the copy since
1787 * code below may some day want the tags.
1792 if (mcopy != NULL) {
1793 mcopy->m_len = imin((IP_VHL_HL(ip->ip_vhl) << 2) + 8,
1795 m_copydata(m, 0, mcopy->m_len, mtod(mcopy, caddr_t));
1801 ip->ip_ttl -= IPTTLDEC;
1807 * If forwarding packet using same interface that it came in on,
1808 * perhaps should send a redirect to sender to shortcut a hop.
1809 * Only send redirect if source is sending directly to us,
1810 * and if packet was not source routed (or has any options).
1811 * Also, don't send redirect if forwarding using a default route
1812 * or a route modified by a redirect.
1814 if (rt->rt_ifp == m->m_pkthdr.rcvif &&
1815 (rt->rt_flags & (RTF_DYNAMIC|RTF_MODIFIED)) == 0 &&
1816 satosin(rt_key(rt))->sin_addr.s_addr != 0 &&
1817 ipsendredirects && !srcrt && !next_hop) {
1818 #define RTA(rt) ((struct in_ifaddr *)(rt->rt_ifa))
1819 u_long src = ntohl(ip->ip_src.s_addr);
1822 (src & RTA(rt)->ia_subnetmask) == RTA(rt)->ia_subnet) {
1823 if (rt->rt_flags & RTF_GATEWAY)
1824 dest = satosin(rt->rt_gateway)->sin_addr.s_addr;
1826 dest = pkt_dst.s_addr;
1827 /* Router requirements says to only send host redirects */
1828 type = ICMP_REDIRECT;
1829 code = ICMP_REDIRECT_HOST;
1832 printf("redirect (%d) to %lx\n", code, (u_long)dest);
1841 /* Pass IPFORWARD info if available */
1843 tag.mh_type = MT_TAG;
1844 tag.mh_flags = PACKET_TAG_IPFORWARD;
1845 tag.mh_data = (caddr_t)next_hop;
1847 m = (struct mbuf *)&tag;
1849 error = ip_output(m, (struct mbuf *)0, &ipforward_rt,
1850 IP_FORWARDING, 0, NULL);
1853 ipstat.ips_cantforward++;
1855 ipstat.ips_forward++;
1857 ipstat.ips_redirectsent++;
1860 ipflow_create(&ipforward_rt, mcopy);
1872 case 0: /* forwarded, but need redirect */
1873 /* type, code set above */
1876 case ENETUNREACH: /* shouldn't happen, checked above */
1881 type = ICMP_UNREACH;
1882 code = ICMP_UNREACH_HOST;
1886 type = ICMP_UNREACH;
1887 code = ICMP_UNREACH_NEEDFRAG;
1890 * If the packet is routed over IPsec tunnel, tell the
1891 * originator the tunnel MTU.
1892 * tunnel MTU = if MTU - sizeof(IP) - ESP/AH hdrsiz
1895 if (ipforward_rt.ro_rt) {
1896 struct secpolicy *sp = NULL;
1901 sp = ipsec4_getpolicybyaddr(mcopy,
1907 destifp = ipforward_rt.ro_rt->rt_ifp;
1909 /* count IPsec header size */
1910 ipsechdr = ipsec4_hdrsiz(mcopy,
1915 * find the correct route for outer IPv4
1916 * header, compute tunnel MTU.
1919 * The "dummyifp" code relies upon the fact
1920 * that icmp_error() touches only ifp->if_mtu.
1925 && sp->req->sav != NULL
1926 && sp->req->sav->sah != NULL) {
1927 ro = &sp->req->sav->sah->sa_route;
1928 if (ro->ro_rt && ro->ro_rt->rt_ifp) {
1930 ro->ro_rt->rt_ifp->if_mtu;
1931 dummyifp.if_mtu -= ipsechdr;
1932 destifp = &dummyifp;
1941 * If the packet is routed over IPsec tunnel, tell the
1942 * originator the tunnel MTU.
1943 * tunnel MTU = if MTU - sizeof(IP) - ESP/AH hdrsiz
1946 if (ipforward_rt.ro_rt) {
1947 struct secpolicy *sp = NULL;
1952 sp = ipsec_getpolicybyaddr(mcopy,
1958 destifp = ipforward_rt.ro_rt->rt_ifp;
1960 /* count IPsec header size */
1961 ipsechdr = ipsec4_hdrsiz(mcopy,
1966 * find the correct route for outer IPv4
1967 * header, compute tunnel MTU.
1970 * The "dummyifp" code relies upon the fact
1971 * that icmp_error() touches only ifp->if_mtu.
1976 && sp->req->sav != NULL
1977 && sp->req->sav->sah != NULL) {
1978 ro = &sp->req->sav->sah->sa_route;
1979 if (ro->ro_rt && ro->ro_rt->rt_ifp) {
1981 ro->ro_rt->rt_ifp->if_mtu;
1982 dummyifp.if_mtu -= ipsechdr;
1983 destifp = &dummyifp;
1990 #else /* !IPSEC && !FAST_IPSEC */
1991 if (ipforward_rt.ro_rt)
1992 destifp = ipforward_rt.ro_rt->rt_ifp;
1994 ipstat.ips_cantfrag++;
1999 * A router should not generate ICMP_SOURCEQUENCH as
2000 * required in RFC1812 Requirements for IP Version 4 Routers.
2001 * Source quench could be a big problem under DoS attacks,
2002 * or if the underlying interface is rate-limited.
2003 * Those who need source quench packets may re-enable them
2004 * via the net.inet.ip.sendsourcequench sysctl.
2006 if (ip_sendsourcequench == 0) {
2010 type = ICMP_SOURCEQUENCH;
2015 case EACCES: /* ipfw denied packet */
2019 icmp_error(mcopy, type, code, dest, destifp);
2023 ip_savecontrol(inp, mp, ip, m)
2029 if (inp->inp_socket->so_options & SO_TIMESTAMP) {
2033 *mp = sbcreatecontrol((caddr_t) &tv, sizeof(tv),
2034 SCM_TIMESTAMP, SOL_SOCKET);
2036 mp = &(*mp)->m_next;
2038 if (inp->inp_flags & INP_RECVDSTADDR) {
2039 *mp = sbcreatecontrol((caddr_t) &ip->ip_dst,
2040 sizeof(struct in_addr), IP_RECVDSTADDR, IPPROTO_IP);
2042 mp = &(*mp)->m_next;
2046 * Moving these out of udp_input() made them even more broken
2047 * than they already were.
2049 /* options were tossed already */
2050 if (inp->inp_flags & INP_RECVOPTS) {
2051 *mp = sbcreatecontrol((caddr_t) opts_deleted_above,
2052 sizeof(struct in_addr), IP_RECVOPTS, IPPROTO_IP);
2054 mp = &(*mp)->m_next;
2056 /* ip_srcroute doesn't do what we want here, need to fix */
2057 if (inp->inp_flags & INP_RECVRETOPTS) {
2058 *mp = sbcreatecontrol((caddr_t) ip_srcroute(),
2059 sizeof(struct in_addr), IP_RECVRETOPTS, IPPROTO_IP);
2061 mp = &(*mp)->m_next;
2064 if (inp->inp_flags & INP_RECVIF) {
2067 struct sockaddr_dl sdl;
2070 struct sockaddr_dl *sdp;
2071 struct sockaddr_dl *sdl2 = &sdlbuf.sdl;
2073 if (((ifp = m->m_pkthdr.rcvif))
2074 && ( ifp->if_index && (ifp->if_index <= if_index))) {
2075 sdp = (struct sockaddr_dl *)(ifnet_addrs
2076 [ifp->if_index - 1]->ifa_addr);
2078 * Change our mind and don't try copy.
2080 if ((sdp->sdl_family != AF_LINK)
2081 || (sdp->sdl_len > sizeof(sdlbuf))) {
2084 bcopy(sdp, sdl2, sdp->sdl_len);
2088 = offsetof(struct sockaddr_dl, sdl_data[0]);
2089 sdl2->sdl_family = AF_LINK;
2090 sdl2->sdl_index = 0;
2091 sdl2->sdl_nlen = sdl2->sdl_alen = sdl2->sdl_slen = 0;
2093 *mp = sbcreatecontrol((caddr_t) sdl2, sdl2->sdl_len,
2094 IP_RECVIF, IPPROTO_IP);
2096 mp = &(*mp)->m_next;
2101 * XXX these routines are called from the upper part of the kernel.
2103 * They could also be moved to ip_mroute.c, since all the RSVP
2104 * handling is done there already.
2107 ip_rsvp_init(struct socket *so)
2109 if (so->so_type != SOCK_RAW ||
2110 so->so_proto->pr_protocol != IPPROTO_RSVP)
2113 if (ip_rsvpd != NULL)
2118 * This may seem silly, but we need to be sure we don't over-increment
2119 * the RSVP counter, in case something slips up.
2134 * This may seem silly, but we need to be sure we don't over-decrement
2135 * the RSVP counter, in case something slips up.
2145 rsvp_input(struct mbuf *m, int off, int proto) /* XXX must fixup manually */
2147 if (rsvp_input_p) { /* call the real one if loaded */
2148 rsvp_input_p(m, off, proto);
2152 /* Can still get packets with rsvp_on = 0 if there is a local member
2153 * of the group to which the RSVP packet is addressed. But in this
2154 * case we want to throw the packet away.
2162 if (ip_rsvpd != NULL) {
2163 rip_input(m, off, proto);
2166 /* Drop the packet */