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.31 2004/06/24 08:15:17 dillon 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_random_ip_id.h"
49 #include <sys/param.h>
50 #include <sys/systm.h>
52 #include <sys/malloc.h>
53 #include <sys/mpipe.h>
54 #include <sys/domain.h>
55 #include <sys/protosw.h>
56 #include <sys/socket.h>
58 #include <sys/globaldata.h>
59 #include <sys/thread.h>
60 #include <sys/kernel.h>
61 #include <sys/syslog.h>
62 #include <sys/sysctl.h>
63 #include <sys/in_cksum.h>
65 #include <sys/thread2.h>
66 #include <sys/msgport2.h>
68 #include <machine/stdarg.h>
71 #include <net/if_types.h>
72 #include <net/if_var.h>
73 #include <net/if_dl.h>
75 #include <net/route.h>
76 #include <net/netisr.h>
77 #include <net/intrq.h>
79 #include <netinet/in.h>
80 #include <netinet/in_systm.h>
81 #include <netinet/in_var.h>
82 #include <netinet/ip.h>
83 #include <netinet/in_pcb.h>
84 #include <netinet/ip_var.h>
85 #include <netinet/ip_icmp.h>
87 #include <netinet/ipprotosw.h>
89 #include <sys/socketvar.h>
91 #include <net/ipfw/ip_fw.h>
92 #include <net/dummynet/ip_dummynet.h>
95 #include <netinet6/ipsec.h>
96 #include <netproto/key/key.h>
100 #include <netipsec/ipsec.h>
101 #include <netipsec/key.h>
105 static int ip_rsvp_on;
106 struct socket *ip_rsvpd;
108 int ipforwarding = 0;
109 SYSCTL_INT(_net_inet_ip, IPCTL_FORWARDING, forwarding, CTLFLAG_RW,
110 &ipforwarding, 0, "Enable IP forwarding between interfaces");
112 static int ipsendredirects = 1; /* XXX */
113 SYSCTL_INT(_net_inet_ip, IPCTL_SENDREDIRECTS, redirect, CTLFLAG_RW,
114 &ipsendredirects, 0, "Enable sending IP redirects");
116 int ip_defttl = IPDEFTTL;
117 SYSCTL_INT(_net_inet_ip, IPCTL_DEFTTL, ttl, CTLFLAG_RW,
118 &ip_defttl, 0, "Maximum TTL on IP packets");
120 static int ip_dosourceroute = 0;
121 SYSCTL_INT(_net_inet_ip, IPCTL_SOURCEROUTE, sourceroute, CTLFLAG_RW,
122 &ip_dosourceroute, 0, "Enable forwarding source routed IP packets");
124 static int ip_acceptsourceroute = 0;
125 SYSCTL_INT(_net_inet_ip, IPCTL_ACCEPTSOURCEROUTE, accept_sourceroute,
126 CTLFLAG_RW, &ip_acceptsourceroute, 0,
127 "Enable accepting source routed IP packets");
129 static int ip_keepfaith = 0;
130 SYSCTL_INT(_net_inet_ip, IPCTL_KEEPFAITH, keepfaith, CTLFLAG_RW,
132 "Enable packet capture for FAITH IPv4->IPv6 translater daemon");
134 static int nipq = 0; /* total # of reass queues */
136 SYSCTL_INT(_net_inet_ip, OID_AUTO, maxfragpackets, CTLFLAG_RW,
138 "Maximum number of IPv4 fragment reassembly queue entries");
140 static int maxfragsperpacket;
141 SYSCTL_INT(_net_inet_ip, OID_AUTO, maxfragsperpacket, CTLFLAG_RW,
142 &maxfragsperpacket, 0,
143 "Maximum number of IPv4 fragments allowed per packet");
145 static int ip_sendsourcequench = 0;
146 SYSCTL_INT(_net_inet_ip, OID_AUTO, sendsourcequench, CTLFLAG_RW,
147 &ip_sendsourcequench, 0,
148 "Enable the transmission of source quench packets");
151 * XXX - Setting ip_checkinterface mostly implements the receive side of
152 * the Strong ES model described in RFC 1122, but since the routing table
153 * and transmit implementation do not implement the Strong ES model,
154 * setting this to 1 results in an odd hybrid.
156 * XXX - ip_checkinterface currently must be disabled if you use ipnat
157 * to translate the destination address to another local interface.
159 * XXX - ip_checkinterface must be disabled if you add IP aliases
160 * to the loopback interface instead of the interface where the
161 * packets for those addresses are received.
163 static int ip_checkinterface = 0;
164 SYSCTL_INT(_net_inet_ip, OID_AUTO, check_interface, CTLFLAG_RW,
165 &ip_checkinterface, 0, "Verify packet arrives on correct interface");
168 static int ipprintfs = 0;
171 static struct ifqueue ipintrq;
172 static int ipqmaxlen = IFQ_MAXLEN;
174 extern struct domain inetdomain;
175 extern struct ipprotosw inetsw[];
176 u_char ip_protox[IPPROTO_MAX];
177 struct in_ifaddrhead in_ifaddrhead; /* first inet address */
178 struct in_ifaddrhashhead *in_ifaddrhashtbl; /* inet addr hash table */
179 u_long in_ifaddrhmask; /* mask for hash table */
181 SYSCTL_INT(_net_inet_ip, IPCTL_INTRQMAXLEN, intr_queue_maxlen, CTLFLAG_RW,
182 &ipintrq.ifq_maxlen, 0, "Maximum size of the IP input queue");
183 SYSCTL_INT(_net_inet_ip, IPCTL_INTRQDROPS, intr_queue_drops, CTLFLAG_RD,
184 &ipintrq.ifq_drops, 0, "Number of packets dropped from the IP input queue");
186 struct ip_stats ipstats_ary[MAXCPU];
189 sysctl_ipstats(SYSCTL_HANDLER_ARGS)
193 for (cpu = 0; cpu < ncpus; ++cpu) {
194 if ((error = SYSCTL_OUT(req, (void *)&ipstats_ary[cpu],
195 sizeof(struct ip_stats))))
197 if ((error = SYSCTL_IN(req, (void *)&ipstats_ary[cpu],
198 sizeof(struct ip_stats))))
204 SYSCTL_PROC(_net_inet_ip, IPCTL_STATS, stats, (CTLTYPE_OPAQUE | CTLFLAG_RW),
205 0, 0, sysctl_ipstats, "S,ip_stats", "IP statistics");
207 SYSCTL_STRUCT(_net_inet_ip, IPCTL_STATS, stats, CTLFLAG_RW,
208 &ipstat, ip_stats, "IP statistics");
211 /* Packet reassembly stuff */
212 #define IPREASS_NHASH_LOG2 6
213 #define IPREASS_NHASH (1 << IPREASS_NHASH_LOG2)
214 #define IPREASS_HMASK (IPREASS_NHASH - 1)
215 #define IPREASS_HASH(x,y) \
216 (((((x) & 0xF) | ((((x) >> 8) & 0xF) << 4)) ^ (y)) & IPREASS_HMASK)
218 static struct ipq ipq[IPREASS_NHASH];
219 const int ipintrq_present = 1;
222 SYSCTL_INT(_net_inet_ip, IPCTL_DEFMTU, mtu, CTLFLAG_RW,
223 &ip_mtu, 0, "Default MTU");
227 static int ipstealth = 0;
228 SYSCTL_INT(_net_inet_ip, OID_AUTO, stealth, CTLFLAG_RW, &ipstealth, 0, "");
230 static const int ipstealth = 0;
235 ip_fw_chk_t *ip_fw_chk_ptr;
240 ip_dn_io_t *ip_dn_io_ptr;
242 struct pfil_head inet_pfil_hook;
245 * XXX this is ugly -- the following two global variables are
246 * used to store packet state while it travels through the stack.
247 * Note that the code even makes assumptions on the size and
248 * alignment of fields inside struct ip_srcrt so e.g. adding some
249 * fields will break the code. This needs to be fixed.
251 * We need to save the IP options in case a protocol wants to respond
252 * to an incoming packet over the same route if the packet got here
253 * using IP source routing. This allows connection establishment and
254 * maintenance when the remote end is on a network that is not known
257 static int ip_nhops = 0;
259 static struct ip_srcrt {
260 struct in_addr dst; /* final destination */
261 char nop; /* one NOP to align */
262 char srcopt[IPOPT_OFFSET + 1]; /* OPTVAL, OLEN and OFFSET */
263 struct in_addr route[MAX_IPOPTLEN/sizeof(struct in_addr)];
266 static MALLOC_DEFINE(M_IPQ, "ipq", "IP Fragment Management");
267 static struct malloc_pipe ipq_mpipe;
269 static void save_rte (u_char *, struct in_addr);
270 static int ip_dooptions (struct mbuf *m, int,
271 struct sockaddr_in *next_hop);
272 static void ip_forward (struct mbuf *m, int srcrt,
273 struct sockaddr_in *next_hop);
274 static void ip_freef (struct ipq *);
275 static int ip_input_handler (struct netmsg *);
276 static struct mbuf *ip_reass (struct mbuf *, struct ipq *,
277 struct ipq *, u_int32_t *, u_int16_t *);
280 * IP initialization: fill in IP protocol switch table.
281 * All protocols not implemented in kernel go to raw IP protocol handler.
286 struct ipprotosw *pr;
293 * Make sure we can handle a reasonable number of fragments but
294 * cap it at 4000 (XXX).
296 mpipe_init(&ipq_mpipe, M_IPQ, sizeof(struct ipq),
297 IFQ_MAXLEN, 4000, 0, NULL);
298 TAILQ_INIT(&in_ifaddrhead);
299 in_ifaddrhashtbl = hashinit(INADDR_NHASH, M_IFADDR, &in_ifaddrhmask);
300 pr = (struct ipprotosw *)pffindproto(PF_INET, IPPROTO_RAW, SOCK_RAW);
303 for (i = 0; i < IPPROTO_MAX; i++)
304 ip_protox[i] = pr - inetsw;
305 for (pr = (struct ipprotosw *)inetdomain.dom_protosw;
306 pr < (struct ipprotosw *)inetdomain.dom_protoswNPROTOSW; pr++)
307 if (pr->pr_domain->dom_family == PF_INET &&
308 pr->pr_protocol && pr->pr_protocol != IPPROTO_RAW)
309 ip_protox[pr->pr_protocol] = pr - inetsw;
311 inet_pfil_hook.ph_type = PFIL_TYPE_AF;
312 inet_pfil_hook.ph_af = AF_INET;
313 if ((i = pfil_head_register(&inet_pfil_hook)) != 0) {
314 printf("%s: WARNING: unable to register pfil hook, "
315 "error %d\n", __func__, i);
318 for (i = 0; i < IPREASS_NHASH; i++)
319 ipq[i].next = ipq[i].prev = &ipq[i];
321 maxnipq = nmbclusters / 32;
322 maxfragsperpacket = 16;
325 ip_id = time_second & 0xffff;
327 ipintrq.ifq_maxlen = ipqmaxlen;
330 * Initialize IP statistics.
332 * It is layed out as an array which is has one element for UP,
333 * and SMP_MAXCPU elements for SMP. This allows us to retain
334 * the access mechanism from userland for both UP and SMP.
337 for (cpu = 0; cpu < ncpus; ++cpu) {
338 bzero(&ipstats_ary[cpu], sizeof(struct ip_stats));
341 bzero(&ipstat, sizeof(struct ip_stats));
344 netisr_register(NETISR_IP, ip_mport, ip_input_handler);
348 * XXX watch out this one. It is perhaps used as a cache for
349 * the most recently used route ? it is cleared in in_addroute()
350 * when a new route is successfully created.
352 struct route ipforward_rt;
353 static struct sockaddr_in ipaddr = { sizeof(ipaddr), AF_INET };
355 /* Do transport protocol processing. */
357 transport_processing_oncpu(struct mbuf *m, int hlen, struct ip *ip,
358 struct sockaddr_in *nexthop)
361 * Switch out to protocol's input routine.
363 if (nexthop && ip->ip_p == IPPROTO_TCP) {
364 /* TCP needs IPFORWARD info if available */
367 tag.mh_type = MT_TAG;
368 tag.mh_flags = PACKET_TAG_IPFORWARD;
369 tag.mh_data = (caddr_t)nexthop;
372 (*inetsw[ip_protox[ip->ip_p]].pr_input)
373 ((struct mbuf *)&tag, hlen, ip->ip_p);
375 (*inetsw[ip_protox[ip->ip_p]].pr_input)(m, hlen, ip->ip_p);
379 struct netmsg_transport_packet {
380 struct lwkt_msg nm_lmsg;
381 struct mbuf *nm_mbuf;
383 boolean_t nm_hasnexthop;
384 struct sockaddr_in nm_nexthop;
388 transport_processing_handler(lwkt_msg_t lmsg)
390 struct netmsg_transport_packet *msg = (void *)lmsg;
391 struct sockaddr_in *nexthop;
394 ip = mtod(msg->nm_mbuf, struct ip *);
395 nexthop = msg->nm_hasnexthop ? &msg->nm_nexthop : NULL;
396 transport_processing_oncpu(msg->nm_mbuf, msg->nm_hlen, ip, nexthop);
397 lwkt_replymsg(lmsg, 0);
402 ip_input_handler(struct netmsg *msg0)
404 struct mbuf *m = ((struct netmsg_packet *)msg0)->nm_packet;
407 lwkt_replymsg(&msg0->nm_lmsg, 0);
412 * Ip input routine. Checksum and byte swap header. If fragmented
413 * try to reassemble. Process options. Pass to next level.
416 ip_input(struct mbuf *m)
420 struct in_ifaddr *ia = NULL;
422 int i, hlen, checkif;
424 struct in_addr pkt_dst;
425 u_int32_t divert_info = 0; /* packet divert/tee info */
426 struct ip_fw_args args;
427 boolean_t using_srcrt = FALSE; /* forward (by PFIL_HOOKS) */
428 boolean_t needredispatch = FALSE;
429 struct in_addr odst; /* original dst address(NAT) */
432 struct tdb_ident *tdbi;
433 struct secpolicy *sp;
440 args.divert_rule = 0; /* divert cookie */
441 args.next_hop = NULL;
443 /* Grab info from MT_TAG mbufs prepended to the chain. */
444 for (; m && m->m_type == MT_TAG; m = m->m_next) {
445 switch(m->_m_tag_id) {
447 printf("ip_input: unrecognised MT_TAG tag %d\n",
451 case PACKET_TAG_DUMMYNET:
452 args.rule = ((struct dn_pkt *)m)->rule;
455 case PACKET_TAG_DIVERT:
456 args.divert_rule = (int)m->m_hdr.mh_data & 0xffff;
459 case PACKET_TAG_IPFORWARD:
460 args.next_hop = (struct sockaddr_in *)m->m_hdr.mh_data;
465 KASSERT(m != NULL && (m->m_flags & M_PKTHDR) != 0,
466 ("ip_input: no HDR"));
468 if (args.rule) { /* dummynet already filtered us */
469 ip = mtod(m, struct ip *);
470 hlen = IP_VHL_HL(ip->ip_vhl) << 2;
476 /* length checks already done in ip_demux() */
477 KASSERT(m->m_len >= sizeof(ip), ("IP header not in one mbuf"));
479 ip = mtod(m, struct ip *);
481 if (IP_VHL_V(ip->ip_vhl) != IPVERSION) {
482 ipstat.ips_badvers++;
486 hlen = IP_VHL_HL(ip->ip_vhl) << 2;
487 /* length checks already done in ip_demux() */
488 KASSERT(hlen >= sizeof(struct ip), ("IP header len too small"));
489 KASSERT(m->m_len >= hlen, ("packet shorter than IP header length"));
491 /* 127/8 must not appear on wire - RFC1122 */
492 if ((ntohl(ip->ip_dst.s_addr) >> IN_CLASSA_NSHIFT) == IN_LOOPBACKNET ||
493 (ntohl(ip->ip_src.s_addr) >> IN_CLASSA_NSHIFT) == IN_LOOPBACKNET) {
494 if (!(m->m_pkthdr.rcvif->if_flags & IFF_LOOPBACK)) {
495 ipstat.ips_badaddr++;
500 if (m->m_pkthdr.csum_flags & CSUM_IP_CHECKED) {
501 sum = !(m->m_pkthdr.csum_flags & CSUM_IP_VALID);
503 if (hlen == sizeof(struct ip)) {
504 sum = in_cksum_hdr(ip);
506 sum = in_cksum(m, hlen);
515 * Convert fields to host representation.
517 ip->ip_len = ntohs(ip->ip_len);
518 if (ip->ip_len < hlen) {
522 ip->ip_off = ntohs(ip->ip_off);
525 * Check that the amount of data in the buffers
526 * is as at least much as the IP header would have us expect.
527 * Trim mbufs if longer than we expect.
528 * Drop packet if shorter than we expect.
530 if (m->m_pkthdr.len < ip->ip_len) {
531 ipstat.ips_tooshort++;
534 if (m->m_pkthdr.len > ip->ip_len) {
535 if (m->m_len == m->m_pkthdr.len) {
536 m->m_len = ip->ip_len;
537 m->m_pkthdr.len = ip->ip_len;
539 m_adj(m, ip->ip_len - m->m_pkthdr.len);
541 #if defined(IPSEC) && !defined(IPSEC_FILTERGIF)
543 * Bypass packet filtering for packets from a tunnel (gif).
545 if (ipsec_gethist(m, NULL))
551 * Right now when no processing on packet has done
552 * and it is still fresh out of network we do our black
554 * - Firewall: deny/allow/divert
555 * - Xlate: translate packet's addr/port (NAT).
556 * - Pipe: pass pkt through dummynet.
557 * - Wrap: fake packet's addr/port <unimpl.>
558 * - Encapsulate: put it in another IP and send out. <unimp.>
564 * Run through list of hooks for input packets.
566 * NB: Beware of the destination address changing (e.g.
567 * by NAT rewriting). When this happens, tell
568 * ip_forward to do the right thing.
570 if (pfil_has_hooks(&inet_pfil_hook)) {
572 if (pfil_run_hooks(&inet_pfil_hook, &m,
573 m->m_pkthdr.rcvif, PFIL_IN)) {
576 if (m == NULL) /* consumed by filter */
578 ip = mtod(m, struct ip *);
579 using_srcrt = (odst.s_addr != ip->ip_dst.s_addr);
582 if (fw_enable && IPFW_LOADED) {
584 * If we've been forwarded from the output side, then
585 * skip the firewall a second time
591 i = ip_fw_chk_ptr(&args);
594 if ( (i & IP_FW_PORT_DENY_FLAG) || m == NULL) { /* drop */
599 ip = mtod(m, struct ip *); /* just in case m changed */
600 if (i == 0 && args.next_hop == NULL) /* common case */
602 if (DUMMYNET_LOADED && (i & IP_FW_PORT_DYNT_FLAG)) {
603 /* Send packet to the appropriate pipe */
604 ip_dn_io_ptr(m, i&0xffff, DN_TO_IP_IN, &args);
608 if (i != 0 && !(i & IP_FW_PORT_DYNT_FLAG)) {
609 /* Divert or tee packet */
614 if (i == 0 && args.next_hop != NULL)
617 * if we get here, the packet must be dropped
625 * Process options and, if not destined for us,
626 * ship it on. ip_dooptions returns 1 when an
627 * error was detected (causing an icmp message
628 * to be sent and the original packet to be freed).
630 ip_nhops = 0; /* for source routed packets */
631 if (hlen > sizeof(struct ip) && ip_dooptions(m, 0, args.next_hop))
634 /* greedy RSVP, snatches any PATH packet of the RSVP protocol and no
635 * matter if it is destined to another node, or whether it is
636 * a multicast one, RSVP wants it! and prevents it from being forwarded
637 * anywhere else. Also checks if the rsvp daemon is running before
638 * grabbing the packet.
640 if (rsvp_on && ip->ip_p == IPPROTO_RSVP)
644 * Check our list of addresses, to see if the packet is for us.
645 * If we don't have any addresses, assume any unicast packet
646 * we receive might be for us (and let the upper layers deal
649 if (TAILQ_EMPTY(&in_ifaddrhead) && !(m->m_flags & (M_MCAST | M_BCAST)))
653 * Cache the destination address of the packet; this may be
654 * changed by use of 'ipfw fwd'.
656 pkt_dst = args.next_hop ? args.next_hop->sin_addr : ip->ip_dst;
659 * Enable a consistency check between the destination address
660 * and the arrival interface for a unicast packet (the RFC 1122
661 * strong ES model) if IP forwarding is disabled and the packet
662 * is not locally generated and the packet is not subject to
665 * XXX - Checking also should be disabled if the destination
666 * address is ipnat'ed to a different interface.
668 * XXX - Checking is incompatible with IP aliases added
669 * to the loopback interface instead of the interface where
670 * the packets are received.
672 checkif = ip_checkinterface &&
674 m->m_pkthdr.rcvif != NULL &&
675 !(m->m_pkthdr.rcvif->if_flags & IFF_LOOPBACK) &&
676 (args.next_hop == NULL);
679 * Check for exact addresses in the hash bucket.
681 LIST_FOREACH(ia, INADDR_HASH(pkt_dst.s_addr), ia_hash) {
683 * If the address matches, verify that the packet
684 * arrived via the correct interface if checking is
687 if (IA_SIN(ia)->sin_addr.s_addr == pkt_dst.s_addr &&
688 (!checkif || ia->ia_ifp == m->m_pkthdr.rcvif))
692 * Check for broadcast addresses.
694 * Only accept broadcast packets that arrive via the matching
695 * interface. Reception of forwarded directed broadcasts would
696 * be handled via ip_forward() and ether_output() with the loopback
697 * into the stack for SIMPLEX interfaces handled by ether_output().
699 if (m->m_pkthdr.rcvif->if_flags & IFF_BROADCAST) {
700 TAILQ_FOREACH(ifa, &m->m_pkthdr.rcvif->if_addrhead, ifa_link) {
701 if (ifa->ifa_addr->sa_family != AF_INET)
704 if (satosin(&ia->ia_broadaddr)->sin_addr.s_addr ==
707 if (ia->ia_netbroadcast.s_addr == pkt_dst.s_addr)
710 if (IA_SIN(ia)->sin_addr.s_addr == INADDR_ANY)
715 if (IN_MULTICAST(ntohl(ip->ip_dst.s_addr))) {
716 struct in_multi *inm;
719 * If we are acting as a multicast router, all
720 * incoming multicast packets are passed to the
721 * kernel-level multicast forwarding function.
722 * The packet is returned (relatively) intact; if
723 * ip_mforward() returns a non-zero value, the packet
724 * must be discarded, else it may be accepted below.
727 ip_mforward(ip, m->m_pkthdr.rcvif, m, NULL) != 0) {
728 ipstat.ips_cantforward++;
734 * The process-level routing daemon needs to receive
735 * all multicast IGMP packets, whether or not this
736 * host belongs to their destination groups.
738 if (ip->ip_p == IPPROTO_IGMP)
740 ipstat.ips_forward++;
743 * See if we belong to the destination multicast group on the
746 IN_LOOKUP_MULTI(ip->ip_dst, m->m_pkthdr.rcvif, inm);
748 ipstat.ips_notmember++;
754 if (ip->ip_dst.s_addr == INADDR_BROADCAST)
756 if (ip->ip_dst.s_addr == INADDR_ANY)
760 * FAITH(Firewall Aided Internet Translator)
762 if (m->m_pkthdr.rcvif && m->m_pkthdr.rcvif->if_type == IFT_FAITH) {
764 if (ip->ip_p == IPPROTO_TCP || ip->ip_p == IPPROTO_ICMP)
772 * Not for us; forward if possible and desirable.
775 ipstat.ips_cantforward++;
780 * Enforce inbound IPsec SPD.
782 if (ipsec4_in_reject(m, NULL)) {
783 ipsecstat.in_polvio++;
788 mtag = m_tag_find(m, PACKET_TAG_IPSEC_IN_DONE, NULL);
791 tdbi = (struct tdb_ident *)(mtag + 1);
792 sp = ipsec_getpolicy(tdbi, IPSEC_DIR_INBOUND);
794 sp = ipsec_getpolicybyaddr(m, IPSEC_DIR_INBOUND,
795 IP_FORWARDING, &error);
797 if (sp == NULL) { /* NB: can happen if error */
799 /*XXX error stat???*/
800 DPRINTF(("ip_input: no SP for forwarding\n")); /*XXX*/
805 * Check security policy against packet attributes.
807 error = ipsec_in_reject(sp, m);
811 ipstat.ips_cantforward++;
815 ip_forward(m, using_srcrt, args.next_hop);
822 * IPSTEALTH: Process non-routing options only
823 * if the packet is destined for us.
826 hlen > sizeof(struct ip) &&
827 ip_dooptions(m, 1, args.next_hop))
830 /* Count the packet in the ip address stats */
832 ia->ia_ifa.if_ipackets++;
833 ia->ia_ifa.if_ibytes += m->m_pkthdr.len;
837 * If offset or IP_MF are set, must reassemble.
838 * Otherwise, nothing need be done.
839 * (We could look in the reassembly queue to see
840 * if the packet was previously fragmented,
841 * but it's not worth the time; just let them time out.)
843 if (ip->ip_off & (IP_MF | IP_OFFMASK)) {
845 /* If maxnipq is 0, never accept fragments. */
847 ipstat.ips_fragments++;
848 ipstat.ips_fragdropped++;
852 sum = IPREASS_HASH(ip->ip_src.s_addr, ip->ip_id);
854 * Look for queue of fragments
857 for (fp = ipq[sum].next; fp != &ipq[sum]; fp = fp->next)
858 if (ip->ip_id == fp->ipq_id &&
859 ip->ip_src.s_addr == fp->ipq_src.s_addr &&
860 ip->ip_dst.s_addr == fp->ipq_dst.s_addr &&
861 ip->ip_p == fp->ipq_p)
867 * Enforce upper bound on number of fragmented packets
868 * for which we attempt reassembly;
869 * If maxnipq is -1, accept all fragments without limitation.
871 if ((nipq > maxnipq) && (maxnipq > 0)) {
873 * drop something from the tail of the current queue
874 * before proceeding further
876 if (ipq[sum].prev == &ipq[sum]) { /* gak */
877 for (i = 0; i < IPREASS_NHASH; i++) {
878 if (ipq[i].prev != &ipq[i]) {
879 ipstat.ips_fragtimeout +=
880 ipq[i].prev->ipq_nfrags;
881 ip_freef(ipq[i].prev);
886 ipstat.ips_fragtimeout +=
887 ipq[sum].prev->ipq_nfrags;
888 ip_freef(ipq[sum].prev);
893 * Adjust ip_len to not reflect header,
894 * convert offset of this to bytes.
897 if (ip->ip_off & IP_MF) {
899 * Make sure that fragments have a data length
900 * that's a non-zero multiple of 8 bytes.
902 if (ip->ip_len == 0 || (ip->ip_len & 0x7) != 0) {
903 ipstat.ips_toosmall++; /* XXX */
906 m->m_flags |= M_FRAG;
908 m->m_flags &= ~M_FRAG;
912 * Attempt reassembly; if it succeeds, proceed.
913 * ip_reass() will return a different mbuf, and update
914 * the divert info in divert_info and args.divert_rule.
916 ipstat.ips_fragments++;
917 m->m_pkthdr.header = ip;
918 m = ip_reass(m, fp, &ipq[sum], &divert_info, &args.divert_rule);
921 ipstat.ips_reassembled++;
922 needredispatch = TRUE;
923 ip = mtod(m, struct ip *);
924 /* Get the header length of the reassembled packet */
925 hlen = IP_VHL_HL(ip->ip_vhl) << 2;
927 /* Restore original checksum before diverting packet */
928 if (divert_info != 0) {
930 ip->ip_len = htons(ip->ip_len);
931 ip->ip_off = htons(ip->ip_off);
933 if (hlen == sizeof(struct ip))
934 ip->ip_sum = in_cksum_hdr(ip);
936 ip->ip_sum = in_cksum(m, hlen);
937 ip->ip_off = ntohs(ip->ip_off);
938 ip->ip_len = ntohs(ip->ip_len);
948 * Divert or tee packet to the divert protocol if required.
950 if (divert_info != 0) {
951 struct mbuf *clone = NULL;
953 /* Clone packet if we're doing a 'tee' */
954 if ((divert_info & IP_FW_PORT_TEE_FLAG) != 0)
955 clone = m_dup(m, MB_DONTWAIT);
957 /* Restore packet header fields to original values */
959 ip->ip_len = htons(ip->ip_len);
960 ip->ip_off = htons(ip->ip_off);
962 /* Deliver packet to divert input routine */
963 divert_packet(m, 1, divert_info & 0xffff, args.divert_rule);
964 ipstat.ips_delivered++;
966 /* If 'tee', continue with original packet */
970 ip = mtod(m, struct ip *);
973 * Jump backwards to complete processing of the
974 * packet. But first clear divert_info to avoid
975 * entering this block again.
976 * We do not need to clear args.divert_rule
977 * or args.next_hop as they will not be used.
986 * enforce IPsec policy checking if we are seeing last header.
987 * note that we do not visit this with protocols with pcb layer
988 * code - like udp/tcp/raw ip.
990 if ((inetsw[ip_protox[ip->ip_p]].pr_flags & PR_LASTHDR) &&
991 ipsec4_in_reject(m, NULL)) {
992 ipsecstat.in_polvio++;
998 * enforce IPsec policy checking if we are seeing last header.
999 * note that we do not visit this with protocols with pcb layer
1000 * code - like udp/tcp/raw ip.
1002 if (inetsw[ip_protox[ip->ip_p]].pr_flags & PR_LASTHDR) {
1004 * Check if the packet has already had IPsec processing
1005 * done. If so, then just pass it along. This tag gets
1006 * set during AH, ESP, etc. input handling, before the
1007 * packet is returned to the ip input queue for delivery.
1009 mtag = m_tag_find(m, PACKET_TAG_IPSEC_IN_DONE, NULL);
1012 tdbi = (struct tdb_ident *)(mtag + 1);
1013 sp = ipsec_getpolicy(tdbi, IPSEC_DIR_INBOUND);
1015 sp = ipsec_getpolicybyaddr(m, IPSEC_DIR_INBOUND,
1016 IP_FORWARDING, &error);
1020 * Check security policy against packet attributes.
1022 error = ipsec_in_reject(sp, m);
1025 /* XXX error stat??? */
1027 DPRINTF(("ip_input: no SP, packet discarded\n"));/*XXX*/
1034 #endif /* FAST_IPSEC */
1036 ipstat.ips_delivered++;
1037 if (needredispatch) {
1038 struct netmsg_transport_packet *msg;
1041 msg = malloc(sizeof(struct netmsg_transport_packet),
1042 M_LWKTMSG, M_INTWAIT | M_NULLOK);
1046 lwkt_initmsg(&msg->nm_lmsg, &netisr_afree_rport, 0,
1047 lwkt_cmd_func(transport_processing_handler),
1050 msg->nm_hlen = hlen;
1051 msg->nm_hasnexthop = (args.next_hop != NULL);
1052 if (msg->nm_hasnexthop)
1053 msg->nm_nexthop = *args.next_hop; /* structure copy */
1055 ip->ip_off = htons(ip->ip_off);
1056 ip->ip_len = htons(ip->ip_len);
1060 ip->ip_len = ntohs(ip->ip_len);
1061 ip->ip_off = ntohs(ip->ip_off);
1063 lwkt_sendmsg(port, &msg->nm_lmsg);
1065 transport_processing_oncpu(m, hlen, ip, args.next_hop);
1074 * Take incoming datagram fragment and try to reassemble it into
1075 * whole datagram. If a chain for reassembly of this datagram already
1076 * exists, then it is given as fp; otherwise have to make a chain.
1078 * When IPDIVERT enabled, keep additional state with each packet that
1079 * tells us if we need to divert or tee the packet we're building.
1080 * In particular, *divinfo includes the port and TEE flag,
1081 * *divert_rule is the number of the matching rule.
1084 static struct mbuf *
1085 ip_reass(struct mbuf *m, struct ipq *fp, struct ipq *where,
1086 u_int32_t *divinfo, u_int16_t *divert_rule)
1088 struct ip *ip = mtod(m, struct ip *);
1089 struct mbuf *p = NULL, *q, *nq;
1091 int hlen = IP_VHL_HL(ip->ip_vhl) << 2;
1095 * Presence of header sizes in mbufs
1096 * would confuse code below.
1102 * If first fragment to arrive, create a reassembly queue.
1105 if ((fp = mpipe_alloc_nowait(&ipq_mpipe)) == NULL)
1110 fp->ipq_ttl = IPFRAGTTL;
1111 fp->ipq_p = ip->ip_p;
1112 fp->ipq_id = ip->ip_id;
1113 fp->ipq_src = ip->ip_src;
1114 fp->ipq_dst = ip->ip_dst;
1116 m->m_nextpkt = NULL;
1118 fp->ipq_div_info = 0;
1119 fp->ipq_div_cookie = 0;
1126 #define GETIP(m) ((struct ip*)((m)->m_pkthdr.header))
1129 * Find a segment which begins after this one does.
1131 for (p = NULL, q = fp->ipq_frags; q; p = q, q = q->m_nextpkt)
1132 if (GETIP(q)->ip_off > ip->ip_off)
1136 * If there is a preceding segment, it may provide some of
1137 * our data already. If so, drop the data from the incoming
1138 * segment. If it provides all of our data, drop us, otherwise
1139 * stick new segment in the proper place.
1141 * If some of the data is dropped from the the preceding
1142 * segment, then it's checksum is invalidated.
1145 i = GETIP(p)->ip_off + GETIP(p)->ip_len - ip->ip_off;
1147 if (i >= ip->ip_len)
1150 m->m_pkthdr.csum_flags = 0;
1154 m->m_nextpkt = p->m_nextpkt;
1157 m->m_nextpkt = fp->ipq_frags;
1162 * While we overlap succeeding segments trim them or,
1163 * if they are completely covered, dequeue them.
1165 for (; q != NULL && ip->ip_off + ip->ip_len > GETIP(q)->ip_off;
1167 i = (ip->ip_off + ip->ip_len) - GETIP(q)->ip_off;
1168 if (i < GETIP(q)->ip_len) {
1169 GETIP(q)->ip_len -= i;
1170 GETIP(q)->ip_off += i;
1172 q->m_pkthdr.csum_flags = 0;
1177 ipstat.ips_fragdropped++;
1186 * Transfer firewall instructions to the fragment structure.
1187 * Only trust info in the fragment at offset 0.
1189 if (ip->ip_off == 0) {
1190 fp->ipq_div_info = *divinfo;
1191 fp->ipq_div_cookie = *divert_rule;
1198 * Check for complete reassembly and perform frag per packet
1201 * Frag limiting is performed here so that the nth frag has
1202 * a chance to complete the packet before we drop the packet.
1203 * As a result, n+1 frags are actually allowed per packet, but
1204 * only n will ever be stored. (n = maxfragsperpacket.)
1208 for (p = NULL, q = fp->ipq_frags; q; p = q, q = q->m_nextpkt) {
1209 if (GETIP(q)->ip_off != next) {
1210 if (fp->ipq_nfrags > maxfragsperpacket) {
1211 ipstat.ips_fragdropped += fp->ipq_nfrags;
1216 next += GETIP(q)->ip_len;
1218 /* Make sure the last packet didn't have the IP_MF flag */
1219 if (p->m_flags & M_FRAG) {
1220 if (fp->ipq_nfrags > maxfragsperpacket) {
1221 ipstat.ips_fragdropped += fp->ipq_nfrags;
1228 * Reassembly is complete. Make sure the packet is a sane size.
1232 if (next + (IP_VHL_HL(ip->ip_vhl) << 2) > IP_MAXPACKET) {
1233 ipstat.ips_toolong++;
1234 ipstat.ips_fragdropped += fp->ipq_nfrags;
1240 * Concatenate fragments.
1247 q->m_nextpkt = NULL;
1248 for (q = nq; q != NULL; q = nq) {
1250 q->m_nextpkt = NULL;
1251 m->m_pkthdr.csum_flags &= q->m_pkthdr.csum_flags;
1252 m->m_pkthdr.csum_data += q->m_pkthdr.csum_data;
1258 * Extract firewall instructions from the fragment structure.
1260 *divinfo = fp->ipq_div_info;
1261 *divert_rule = fp->ipq_div_cookie;
1265 * Create header for new ip packet by
1266 * modifying header of first packet;
1267 * dequeue and discard fragment reassembly header.
1268 * Make header visible.
1271 ip->ip_src = fp->ipq_src;
1272 ip->ip_dst = fp->ipq_dst;
1275 mpipe_free(&ipq_mpipe, fp);
1276 m->m_len += (IP_VHL_HL(ip->ip_vhl) << 2);
1277 m->m_data -= (IP_VHL_HL(ip->ip_vhl) << 2);
1278 /* some debugging cruft by sklower, below, will go away soon */
1279 if (m->m_flags & M_PKTHDR) { /* XXX this should be done elsewhere */
1282 for (n = m; n; n = n->m_next)
1284 m->m_pkthdr.len = plen;
1293 ipstat.ips_fragdropped++;
1303 * Free a fragment reassembly header and all
1304 * associated datagrams.
1307 ip_freef(struct ipq *fp)
1311 while (fp->ipq_frags) {
1313 fp->ipq_frags = q->m_nextpkt;
1317 mpipe_free(&ipq_mpipe, fp);
1322 * IP timer processing;
1323 * if a timer expires on a reassembly
1324 * queue, discard it.
1333 for (i = 0; i < IPREASS_NHASH; i++) {
1337 while (fp != &ipq[i]) {
1340 if (fp->prev->ipq_ttl == 0) {
1341 ipstat.ips_fragtimeout += fp->prev->ipq_nfrags;
1347 * If we are over the maximum number of fragments
1348 * (due to the limit being lowered), drain off
1349 * enough to get down to the new limit.
1351 if (maxnipq >= 0 && nipq > maxnipq) {
1352 for (i = 0; i < IPREASS_NHASH; i++) {
1353 while (nipq > maxnipq &&
1354 (ipq[i].next != &ipq[i])) {
1355 ipstat.ips_fragdropped +=
1356 ipq[i].next->ipq_nfrags;
1357 ip_freef(ipq[i].next);
1366 * Drain off all datagram fragments.
1373 for (i = 0; i < IPREASS_NHASH; i++) {
1374 while (ipq[i].next != &ipq[i]) {
1375 ipstat.ips_fragdropped += ipq[i].next->ipq_nfrags;
1376 ip_freef(ipq[i].next);
1383 * Do option processing on a datagram,
1384 * possibly discarding it if bad options are encountered,
1385 * or forwarding it if source-routed.
1386 * The pass argument is used when operating in the IPSTEALTH
1387 * mode to tell what options to process:
1388 * [LS]SRR (pass 0) or the others (pass 1).
1389 * The reason for as many as two passes is that when doing IPSTEALTH,
1390 * non-routing options should be processed only if the packet is for us.
1391 * Returns 1 if packet has been forwarded/freed,
1392 * 0 if the packet should be processed further.
1395 ip_dooptions(struct mbuf *m, int pass, struct sockaddr_in *next_hop)
1397 struct ip *ip = mtod(m, struct ip *);
1399 struct in_ifaddr *ia;
1400 int opt, optlen, cnt, off, code, type = ICMP_PARAMPROB;
1401 boolean_t forward = FALSE;
1402 struct in_addr *sin, dst;
1406 cp = (u_char *)(ip + 1);
1407 cnt = (IP_VHL_HL(ip->ip_vhl) << 2) - sizeof(struct ip);
1408 for (; cnt > 0; cnt -= optlen, cp += optlen) {
1409 opt = cp[IPOPT_OPTVAL];
1410 if (opt == IPOPT_EOL)
1412 if (opt == IPOPT_NOP)
1415 if (cnt < IPOPT_OLEN + sizeof(*cp)) {
1416 code = &cp[IPOPT_OLEN] - (u_char *)ip;
1419 optlen = cp[IPOPT_OLEN];
1420 if (optlen < IPOPT_OLEN + sizeof(*cp) || optlen > cnt) {
1421 code = &cp[IPOPT_OLEN] - (u_char *)ip;
1431 * Source routing with record.
1432 * Find interface with current destination address.
1433 * If none on this machine then drop if strictly routed,
1434 * or do nothing if loosely routed.
1435 * Record interface address and bring up next address
1436 * component. If strictly routed make sure next
1437 * address is on directly accessible net.
1441 if (ipstealth && pass > 0)
1443 if (optlen < IPOPT_OFFSET + sizeof(*cp)) {
1444 code = &cp[IPOPT_OLEN] - (u_char *)ip;
1447 if ((off = cp[IPOPT_OFFSET]) < IPOPT_MINOFF) {
1448 code = &cp[IPOPT_OFFSET] - (u_char *)ip;
1451 ipaddr.sin_addr = ip->ip_dst;
1452 ia = (struct in_ifaddr *)
1453 ifa_ifwithaddr((struct sockaddr *)&ipaddr);
1455 if (opt == IPOPT_SSRR) {
1456 type = ICMP_UNREACH;
1457 code = ICMP_UNREACH_SRCFAIL;
1460 if (!ip_dosourceroute)
1461 goto nosourcerouting;
1463 * Loose routing, and not at next destination
1464 * yet; nothing to do except forward.
1468 off--; /* 0 origin */
1469 if (off > optlen - (int)sizeof(struct in_addr)) {
1471 * End of source route. Should be for us.
1473 if (!ip_acceptsourceroute)
1474 goto nosourcerouting;
1475 save_rte(cp, ip->ip_src);
1480 if (!ip_dosourceroute) {
1482 char buf[16]; /* aaa.bbb.ccc.ddd\0 */
1484 * Acting as a router, so generate ICMP
1487 strcpy(buf, inet_ntoa(ip->ip_dst));
1489 "attempted source route from %s to %s\n",
1490 inet_ntoa(ip->ip_src), buf);
1491 type = ICMP_UNREACH;
1492 code = ICMP_UNREACH_SRCFAIL;
1496 * Not acting as a router,
1500 ipstat.ips_cantforward++;
1507 * locate outgoing interface
1509 (void)memcpy(&ipaddr.sin_addr, cp + off,
1510 sizeof(ipaddr.sin_addr));
1512 if (opt == IPOPT_SSRR) {
1513 #define INA struct in_ifaddr *
1514 #define SA struct sockaddr *
1515 if ((ia = (INA)ifa_ifwithdstaddr((SA)&ipaddr))
1517 ia = (INA)ifa_ifwithnet((SA)&ipaddr);
1519 ia = ip_rtaddr(ipaddr.sin_addr, &ipforward_rt);
1521 type = ICMP_UNREACH;
1522 code = ICMP_UNREACH_SRCFAIL;
1525 ip->ip_dst = ipaddr.sin_addr;
1526 (void)memcpy(cp + off, &(IA_SIN(ia)->sin_addr),
1527 sizeof(struct in_addr));
1528 cp[IPOPT_OFFSET] += sizeof(struct in_addr);
1530 * Let ip_intr's mcast routing check handle mcast pkts
1532 forward = !IN_MULTICAST(ntohl(ip->ip_dst.s_addr));
1536 if (ipstealth && pass == 0)
1538 if (optlen < IPOPT_OFFSET + sizeof(*cp)) {
1539 code = &cp[IPOPT_OFFSET] - (u_char *)ip;
1542 if ((off = cp[IPOPT_OFFSET]) < IPOPT_MINOFF) {
1543 code = &cp[IPOPT_OFFSET] - (u_char *)ip;
1547 * If no space remains, ignore.
1549 off--; /* 0 origin */
1550 if (off > optlen - (int)sizeof(struct in_addr))
1552 (void)memcpy(&ipaddr.sin_addr, &ip->ip_dst,
1553 sizeof(ipaddr.sin_addr));
1555 * locate outgoing interface; if we're the destination,
1556 * use the incoming interface (should be same).
1558 if ((ia = (INA)ifa_ifwithaddr((SA)&ipaddr)) == NULL &&
1559 (ia = ip_rtaddr(ipaddr.sin_addr, &ipforward_rt))
1561 type = ICMP_UNREACH;
1562 code = ICMP_UNREACH_HOST;
1565 (void)memcpy(cp + off, &(IA_SIN(ia)->sin_addr),
1566 sizeof(struct in_addr));
1567 cp[IPOPT_OFFSET] += sizeof(struct in_addr);
1571 if (ipstealth && pass == 0)
1573 code = cp - (u_char *)ip;
1574 if (optlen < 4 || optlen > 40) {
1575 code = &cp[IPOPT_OLEN] - (u_char *)ip;
1578 if ((off = cp[IPOPT_OFFSET]) < 5) {
1579 code = &cp[IPOPT_OLEN] - (u_char *)ip;
1582 if (off > optlen - (int)sizeof(int32_t)) {
1583 cp[IPOPT_OFFSET + 1] += (1 << 4);
1584 if ((cp[IPOPT_OFFSET + 1] & 0xf0) == 0) {
1585 code = &cp[IPOPT_OFFSET] - (u_char *)ip;
1590 off--; /* 0 origin */
1591 sin = (struct in_addr *)(cp + off);
1592 switch (cp[IPOPT_OFFSET + 1] & 0x0f) {
1594 case IPOPT_TS_TSONLY:
1597 case IPOPT_TS_TSANDADDR:
1598 if (off + sizeof(n_time) +
1599 sizeof(struct in_addr) > optlen) {
1600 code = &cp[IPOPT_OFFSET] - (u_char *)ip;
1603 ipaddr.sin_addr = dst;
1604 ia = (INA)ifaof_ifpforaddr((SA)&ipaddr,
1608 (void)memcpy(sin, &IA_SIN(ia)->sin_addr,
1609 sizeof(struct in_addr));
1610 cp[IPOPT_OFFSET] += sizeof(struct in_addr);
1611 off += sizeof(struct in_addr);
1614 case IPOPT_TS_PRESPEC:
1615 if (off + sizeof(n_time) +
1616 sizeof(struct in_addr) > optlen) {
1617 code = &cp[IPOPT_OFFSET] - (u_char *)ip;
1620 (void)memcpy(&ipaddr.sin_addr, sin,
1621 sizeof(struct in_addr));
1622 if (ifa_ifwithaddr((SA)&ipaddr) == NULL)
1624 cp[IPOPT_OFFSET] += sizeof(struct in_addr);
1625 off += sizeof(struct in_addr);
1629 code = &cp[IPOPT_OFFSET + 1] - (u_char *)ip;
1633 (void)memcpy(cp + off, &ntime, sizeof(n_time));
1634 cp[IPOPT_OFFSET] += sizeof(n_time);
1637 if (forward && ipforwarding) {
1638 ip_forward(m, 1, next_hop);
1643 icmp_error(m, type, code, 0, NULL);
1644 ipstat.ips_badoptions++;
1649 * Given address of next destination (final or next hop),
1650 * return internet address info of interface to be used to get there.
1653 ip_rtaddr(struct in_addr dst, struct route *rt)
1655 struct sockaddr_in *sin;
1657 sin = (struct sockaddr_in *)&rt->ro_dst;
1659 if (rt->ro_rt == NULL || dst.s_addr != sin->sin_addr.s_addr) {
1660 if (rt->ro_rt != NULL) {
1664 sin->sin_family = AF_INET;
1665 sin->sin_len = sizeof(*sin);
1666 sin->sin_addr = dst;
1667 rtalloc_ign(rt, RTF_PRCLONING);
1670 if (rt->ro_rt == NULL)
1673 return (ifatoia(rt->ro_rt->rt_ifa));
1677 * Save incoming source route for use in replies,
1678 * to be picked up later by ip_srcroute if the receiver is interested.
1681 save_rte(u_char *option, struct in_addr dst)
1685 olen = option[IPOPT_OLEN];
1688 printf("save_rte: olen %d\n", olen);
1690 if (olen > sizeof(ip_srcrt) - (1 + sizeof(dst)))
1692 bcopy(option, ip_srcrt.srcopt, olen);
1693 ip_nhops = (olen - IPOPT_OFFSET - 1) / sizeof(struct in_addr);
1698 * Retrieve incoming source route for use in replies,
1699 * in the same form used by setsockopt.
1700 * The first hop is placed before the options, will be removed later.
1705 struct in_addr *p, *q;
1710 m = m_get(MB_DONTWAIT, MT_HEADER);
1714 #define OPTSIZ (sizeof(ip_srcrt.nop) + sizeof(ip_srcrt.srcopt))
1716 /* length is (nhops+1)*sizeof(addr) + sizeof(nop + srcrt header) */
1717 m->m_len = ip_nhops * sizeof(struct in_addr) + sizeof(struct in_addr) +
1721 printf("ip_srcroute: nhops %d mlen %d", ip_nhops, m->m_len);
1725 * First save first hop for return route
1727 p = &ip_srcrt.route[ip_nhops - 1];
1728 *(mtod(m, struct in_addr *)) = *p--;
1731 printf(" hops %lx", ntohl(mtod(m, struct in_addr *)->s_addr));
1735 * Copy option fields and padding (nop) to mbuf.
1737 ip_srcrt.nop = IPOPT_NOP;
1738 ip_srcrt.srcopt[IPOPT_OFFSET] = IPOPT_MINOFF;
1739 (void)memcpy(mtod(m, caddr_t) + sizeof(struct in_addr), &ip_srcrt.nop,
1741 q = (struct in_addr *)(mtod(m, caddr_t) +
1742 sizeof(struct in_addr) + OPTSIZ);
1745 * Record return path as an IP source route,
1746 * reversing the path (pointers are now aligned).
1748 while (p >= ip_srcrt.route) {
1751 printf(" %lx", ntohl(q->s_addr));
1756 * Last hop goes to final destination.
1761 printf(" %lx\n", ntohl(q->s_addr));
1767 * Strip out IP options.
1770 ip_stripoptions(struct mbuf *m)
1773 struct ip *ip = mtod(m, struct ip *);
1777 optlen = (IP_VHL_HL(ip->ip_vhl) << 2) - sizeof(struct ip);
1778 opts = (caddr_t)(ip + 1);
1779 datalen = m->m_len - (sizeof(struct ip) + optlen);
1780 bcopy(opts + optlen, opts, datalen);
1782 if (m->m_flags & M_PKTHDR)
1783 m->m_pkthdr.len -= optlen;
1784 ip->ip_vhl = IP_MAKE_VHL(IPVERSION, sizeof(struct ip) >> 2);
1787 u_char inetctlerrmap[PRC_NCMDS] = {
1789 0, EMSGSIZE, EHOSTDOWN, EHOSTUNREACH,
1790 EHOSTUNREACH, EHOSTUNREACH, ECONNREFUSED, ECONNREFUSED,
1791 EMSGSIZE, EHOSTUNREACH, 0, 0,
1793 ENOPROTOOPT, ECONNREFUSED
1797 * Forward a packet. If some error occurs return the sender
1798 * an icmp packet. Note we can't always generate a meaningful
1799 * icmp message because icmp doesn't have a large enough repertoire
1800 * of codes and types.
1802 * If not forwarding, just drop the packet. This could be confusing
1803 * if ipforwarding was zero but some routing protocol was advancing
1804 * us as a gateway to somewhere. However, we must let the routing
1805 * protocol deal with that.
1807 * The using_srcrt parameter indicates whether the packet is being forwarded
1808 * via a source route.
1811 ip_forward(struct mbuf *m, int using_srcrt, struct sockaddr_in *next_hop)
1813 struct ip *ip = mtod(m, struct ip *);
1814 struct sockaddr_in *sin;
1816 int error, type = 0, code = 0;
1819 struct in_addr pkt_dst;
1820 struct ifnet *destifp;
1822 #if defined(IPSEC) || defined(FAST_IPSEC)
1823 struct ifnet dummyifp;
1828 * Cache the destination address of the packet; this may be
1829 * changed by use of 'ipfw fwd'.
1831 pkt_dst = next_hop ? next_hop->sin_addr : ip->ip_dst;
1835 printf("forward: src %x dst %x ttl %x\n",
1836 ip->ip_src.s_addr, pkt_dst.s_addr, ip->ip_ttl);
1839 if (m->m_flags & (M_BCAST | M_MCAST) || !in_canforward(pkt_dst)) {
1840 ipstat.ips_cantforward++;
1844 if (!ipstealth && ip->ip_ttl <= IPTTLDEC) {
1845 icmp_error(m, ICMP_TIMXCEED, ICMP_TIMXCEED_INTRANS, dest, NULL);
1849 sin = (struct sockaddr_in *)&ipforward_rt.ro_dst;
1850 if ((rt = ipforward_rt.ro_rt) == NULL ||
1851 pkt_dst.s_addr != sin->sin_addr.s_addr) {
1852 if (ipforward_rt.ro_rt != NULL) {
1853 RTFREE(ipforward_rt.ro_rt);
1854 ipforward_rt.ro_rt = NULL;
1856 sin->sin_family = AF_INET;
1857 sin->sin_len = sizeof(*sin);
1858 sin->sin_addr = pkt_dst;
1860 rtalloc_ign(&ipforward_rt, RTF_PRCLONING);
1861 if (ipforward_rt.ro_rt == NULL) {
1862 icmp_error(m, ICMP_UNREACH, ICMP_UNREACH_HOST, dest,
1866 rt = ipforward_rt.ro_rt;
1870 * Save the IP header and at most 8 bytes of the payload,
1871 * in case we need to generate an ICMP message to the src.
1873 * XXX this can be optimized a lot by saving the data in a local
1874 * buffer on the stack (72 bytes at most), and only allocating the
1875 * mbuf if really necessary. The vast majority of the packets
1876 * are forwarded without having to send an ICMP back (either
1877 * because unnecessary, or because rate limited), so we are
1878 * really we are wasting a lot of work here.
1880 * We don't use m_copy() because it might return a reference
1881 * to a shared cluster. Both this function and ip_output()
1882 * assume exclusive access to the IP header in `m', so any
1883 * data in a cluster may change before we reach icmp_error().
1885 MGET(mcopy, MB_DONTWAIT, m->m_type);
1886 if (mcopy != NULL && !m_dup_pkthdr(mcopy, m, MB_DONTWAIT)) {
1888 * It's probably ok if the pkthdr dup fails (because
1889 * the deep copy of the tag chain failed), but for now
1890 * be conservative and just discard the copy since
1891 * code below may some day want the tags.
1896 if (mcopy != NULL) {
1897 mcopy->m_len = imin((IP_VHL_HL(ip->ip_vhl) << 2) + 8,
1899 m_copydata(m, 0, mcopy->m_len, mtod(mcopy, caddr_t));
1903 ip->ip_ttl -= IPTTLDEC;
1906 * If forwarding packet using same interface that it came in on,
1907 * perhaps should send a redirect to sender to shortcut a hop.
1908 * Only send redirect if source is sending directly to us,
1909 * and if packet was not source routed (or has any options).
1910 * Also, don't send redirect if forwarding using a default route
1911 * or a route modified by a redirect.
1913 if (rt->rt_ifp == m->m_pkthdr.rcvif &&
1914 !(rt->rt_flags & (RTF_DYNAMIC | RTF_MODIFIED)) &&
1915 satosin(rt_key(rt))->sin_addr.s_addr != INADDR_ANY &&
1916 ipsendredirects && !using_srcrt && next_hop != NULL) {
1917 u_long src = ntohl(ip->ip_src.s_addr);
1919 #define RTA(rt) ((struct in_ifaddr *)(rt->rt_ifa))
1920 if (RTA(rt) != NULL &&
1921 (src & RTA(rt)->ia_subnetmask) == RTA(rt)->ia_subnet) {
1922 if (rt->rt_flags & RTF_GATEWAY)
1923 dest = satosin(rt->rt_gateway)->sin_addr.s_addr;
1925 dest = pkt_dst.s_addr;
1927 * Router requirements says to only send
1930 type = ICMP_REDIRECT;
1931 code = ICMP_REDIRECT_HOST;
1934 printf("redirect (%d) to %x\n", code, dest);
1940 /* Pass IPFORWARD info if available */
1941 tag.mh_type = MT_TAG;
1942 tag.mh_flags = PACKET_TAG_IPFORWARD;
1943 tag.mh_data = (caddr_t)next_hop;
1945 m = (struct mbuf *)&tag;
1948 error = ip_output(m, NULL, &ipforward_rt, IP_FORWARDING, NULL, NULL);
1951 ipstat.ips_cantforward++;
1953 ipstat.ips_forward++;
1955 ipstat.ips_redirectsent++;
1958 ipflow_create(&ipforward_rt, mcopy);
1970 case 0: /* forwarded, but need redirect */
1971 /* type, code set above */
1974 case ENETUNREACH: /* shouldn't happen, checked above */
1979 type = ICMP_UNREACH;
1980 code = ICMP_UNREACH_HOST;
1984 type = ICMP_UNREACH;
1985 code = ICMP_UNREACH_NEEDFRAG;
1988 * If the packet is routed over IPsec tunnel, tell the
1989 * originator the tunnel MTU.
1990 * tunnel MTU = if MTU - sizeof(IP) - ESP/AH hdrsiz
1993 if (ipforward_rt.ro_rt != NULL) {
1994 struct secpolicy *sp = NULL;
1999 sp = ipsec4_getpolicybyaddr(mcopy,
2005 destifp = ipforward_rt.ro_rt->rt_ifp;
2007 /* count IPsec header size */
2008 ipsechdr = ipsec4_hdrsiz(mcopy,
2013 * find the correct route for outer IPv4
2014 * header, compute tunnel MTU.
2017 * The "dummyifp" code relies upon the fact
2018 * that icmp_error() touches only ifp->if_mtu.
2022 if (sp->req != NULL && sp->req->sav != NULL &&
2023 sp->req->sav->sah != NULL) {
2024 ro = &sp->req->sav->sah->sa_route;
2025 if (ro->ro_rt != NULL &&
2026 ro->ro_rt->rt_ifp != NULL) {
2028 ro->ro_rt->rt_ifp->if_mtu;
2029 dummyifp.if_mtu -= ipsechdr;
2030 destifp = &dummyifp;
2039 * If the packet is routed over IPsec tunnel, tell the
2040 * originator the tunnel MTU.
2041 * tunnel MTU = if MTU - sizeof(IP) - ESP/AH hdrsiz
2044 if (ipforward_rt.ro_rt != NULL) {
2045 struct secpolicy *sp = NULL;
2050 sp = ipsec_getpolicybyaddr(mcopy,
2056 destifp = ipforward_rt.ro_rt->rt_ifp;
2058 /* count IPsec header size */
2059 ipsechdr = ipsec4_hdrsiz(mcopy,
2064 * find the correct route for outer IPv4
2065 * header, compute tunnel MTU.
2068 * The "dummyifp" code relies upon the fact
2069 * that icmp_error() touches only ifp->if_mtu.
2073 if (sp->req != NULL &&
2074 sp->req->sav != NULL &&
2075 sp->req->sav->sah != NULL) {
2076 ro = &sp->req->sav->sah->sa_route;
2077 if (ro->ro_rt != NULL &&
2078 ro->ro_rt->rt_ifp != NULL) {
2080 ro->ro_rt->rt_ifp->if_mtu;
2081 dummyifp.if_mtu -= ipsechdr;
2082 destifp = &dummyifp;
2089 #else /* !IPSEC && !FAST_IPSEC */
2090 if (ipforward_rt.ro_rt != NULL)
2091 destifp = ipforward_rt.ro_rt->rt_ifp;
2093 ipstat.ips_cantfrag++;
2098 * A router should not generate ICMP_SOURCEQUENCH as
2099 * required in RFC1812 Requirements for IP Version 4 Routers.
2100 * Source quench could be a big problem under DoS attacks,
2101 * or if the underlying interface is rate-limited.
2102 * Those who need source quench packets may re-enable them
2103 * via the net.inet.ip.sendsourcequench sysctl.
2105 if (!ip_sendsourcequench) {
2109 type = ICMP_SOURCEQUENCH;
2114 case EACCES: /* ipfw denied packet */
2118 icmp_error(mcopy, type, code, dest, destifp);
2122 ip_savecontrol(struct inpcb *inp, struct mbuf **mp, struct ip *ip,
2125 if (inp->inp_socket->so_options & SO_TIMESTAMP) {
2129 *mp = sbcreatecontrol((caddr_t) &tv, sizeof(tv),
2130 SCM_TIMESTAMP, SOL_SOCKET);
2132 mp = &(*mp)->m_next;
2134 if (inp->inp_flags & INP_RECVDSTADDR) {
2135 *mp = sbcreatecontrol((caddr_t) &ip->ip_dst,
2136 sizeof(struct in_addr), IP_RECVDSTADDR, IPPROTO_IP);
2138 mp = &(*mp)->m_next;
2142 * Moving these out of udp_input() made them even more broken
2143 * than they already were.
2145 /* options were tossed already */
2146 if (inp->inp_flags & INP_RECVOPTS) {
2147 *mp = sbcreatecontrol((caddr_t) opts_deleted_above,
2148 sizeof(struct in_addr), IP_RECVOPTS, IPPROTO_IP);
2150 mp = &(*mp)->m_next;
2152 /* ip_srcroute doesn't do what we want here, need to fix */
2153 if (inp->inp_flags & INP_RECVRETOPTS) {
2154 *mp = sbcreatecontrol((caddr_t) ip_srcroute(),
2155 sizeof(struct in_addr), IP_RECVRETOPTS, IPPROTO_IP);
2157 mp = &(*mp)->m_next;
2160 if (inp->inp_flags & INP_RECVIF) {
2163 struct sockaddr_dl sdl;
2166 struct sockaddr_dl *sdp;
2167 struct sockaddr_dl *sdl2 = &sdlbuf.sdl;
2169 if (((ifp = m->m_pkthdr.rcvif)) &&
2170 ((ifp->if_index != 0) && (ifp->if_index <= if_index))) {
2171 sdp = (struct sockaddr_dl *)
2172 ifnet_addrs[ifp->if_index - 1]->ifa_addr;
2174 * Change our mind and don't try copy.
2176 if ((sdp->sdl_family != AF_LINK) ||
2177 (sdp->sdl_len > sizeof(sdlbuf))) {
2180 bcopy(sdp, sdl2, sdp->sdl_len);
2184 offsetof(struct sockaddr_dl, sdl_data[0]);
2185 sdl2->sdl_family = AF_LINK;
2186 sdl2->sdl_index = 0;
2187 sdl2->sdl_nlen = sdl2->sdl_alen = sdl2->sdl_slen = 0;
2189 *mp = sbcreatecontrol((caddr_t) sdl2, sdl2->sdl_len,
2190 IP_RECVIF, IPPROTO_IP);
2192 mp = &(*mp)->m_next;
2197 * XXX these routines are called from the upper part of the kernel.
2199 * They could also be moved to ip_mroute.c, since all the RSVP
2200 * handling is done there already.
2203 ip_rsvp_init(struct socket *so)
2205 if (so->so_type != SOCK_RAW ||
2206 so->so_proto->pr_protocol != IPPROTO_RSVP)
2209 if (ip_rsvpd != NULL)
2214 * This may seem silly, but we need to be sure we don't over-increment
2215 * the RSVP counter, in case something slips up.
2230 * This may seem silly, but we need to be sure we don't over-decrement
2231 * the RSVP counter, in case something slips up.
2241 rsvp_input(struct mbuf *m, ...) /* XXX must fixup manually */
2247 off = __va_arg(ap, int);
2248 proto = __va_arg(ap, int);
2251 if (rsvp_input_p) { /* call the real one if loaded */
2252 rsvp_input_p(m, off, proto);
2256 /* Can still get packets with rsvp_on = 0 if there is a local member
2257 * of the group to which the RSVP packet is addressed. But in this
2258 * case we want to throw the packet away.
2266 if (ip_rsvpd != NULL) {
2267 rip_input(m, off, proto);
2270 /* Drop the packet */