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.30 2004/06/04 03:57:41 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_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/mpipe.h>
55 #include <sys/domain.h>
56 #include <sys/protosw.h>
57 #include <sys/socket.h>
59 #include <sys/globaldata.h>
60 #include <sys/thread.h>
61 #include <sys/kernel.h>
62 #include <sys/syslog.h>
63 #include <sys/sysctl.h>
64 #include <sys/in_cksum.h>
66 #include <sys/thread2.h>
67 #include <sys/msgport2.h>
69 #include <machine/stdarg.h>
72 #include <net/if_types.h>
73 #include <net/if_var.h>
74 #include <net/if_dl.h>
78 #include <net/route.h>
79 #include <net/netisr.h>
80 #include <net/intrq.h>
82 #include <netinet/in.h>
83 #include <netinet/in_systm.h>
84 #include <netinet/in_var.h>
85 #include <netinet/ip.h>
86 #include <netinet/in_pcb.h>
87 #include <netinet/ip_var.h>
88 #include <netinet/ip_icmp.h>
90 #include <netinet/ipprotosw.h>
92 #include <sys/socketvar.h>
94 #include <net/ipfw/ip_fw.h>
95 #include <net/dummynet/ip_dummynet.h>
98 #include <netinet6/ipsec.h>
99 #include <netproto/key/key.h>
103 #include <netipsec/ipsec.h>
104 #include <netipsec/key.h>
108 static int ip_rsvp_on;
109 struct socket *ip_rsvpd;
111 int ipforwarding = 0;
112 SYSCTL_INT(_net_inet_ip, IPCTL_FORWARDING, forwarding, CTLFLAG_RW,
113 &ipforwarding, 0, "Enable IP forwarding between interfaces");
115 static int ipsendredirects = 1; /* XXX */
116 SYSCTL_INT(_net_inet_ip, IPCTL_SENDREDIRECTS, redirect, CTLFLAG_RW,
117 &ipsendredirects, 0, "Enable sending IP redirects");
119 int ip_defttl = IPDEFTTL;
120 SYSCTL_INT(_net_inet_ip, IPCTL_DEFTTL, ttl, CTLFLAG_RW,
121 &ip_defttl, 0, "Maximum TTL on IP packets");
123 static int ip_dosourceroute = 0;
124 SYSCTL_INT(_net_inet_ip, IPCTL_SOURCEROUTE, sourceroute, CTLFLAG_RW,
125 &ip_dosourceroute, 0, "Enable forwarding source routed IP packets");
127 static int ip_acceptsourceroute = 0;
128 SYSCTL_INT(_net_inet_ip, IPCTL_ACCEPTSOURCEROUTE, accept_sourceroute,
129 CTLFLAG_RW, &ip_acceptsourceroute, 0,
130 "Enable accepting source routed IP packets");
132 static int ip_keepfaith = 0;
133 SYSCTL_INT(_net_inet_ip, IPCTL_KEEPFAITH, keepfaith, CTLFLAG_RW,
135 "Enable packet capture for FAITH IPv4->IPv6 translater daemon");
137 static int nipq = 0; /* total # of reass queues */
139 SYSCTL_INT(_net_inet_ip, OID_AUTO, maxfragpackets, CTLFLAG_RW,
141 "Maximum number of IPv4 fragment reassembly queue entries");
143 static int maxfragsperpacket;
144 SYSCTL_INT(_net_inet_ip, OID_AUTO, maxfragsperpacket, CTLFLAG_RW,
145 &maxfragsperpacket, 0,
146 "Maximum number of IPv4 fragments allowed per packet");
148 static int ip_sendsourcequench = 0;
149 SYSCTL_INT(_net_inet_ip, OID_AUTO, sendsourcequench, CTLFLAG_RW,
150 &ip_sendsourcequench, 0,
151 "Enable the transmission of source quench packets");
154 * XXX - Setting ip_checkinterface mostly implements the receive side of
155 * the Strong ES model described in RFC 1122, but since the routing table
156 * and transmit implementation do not implement the Strong ES model,
157 * setting this to 1 results in an odd hybrid.
159 * XXX - ip_checkinterface currently must be disabled if you use ipnat
160 * to translate the destination address to another local interface.
162 * XXX - ip_checkinterface must be disabled if you add IP aliases
163 * to the loopback interface instead of the interface where the
164 * packets for those addresses are received.
166 static int ip_checkinterface = 0;
167 SYSCTL_INT(_net_inet_ip, OID_AUTO, check_interface, CTLFLAG_RW,
168 &ip_checkinterface, 0, "Verify packet arrives on correct interface");
171 static int ipprintfs = 0;
174 static struct ifqueue ipintrq;
175 static int ipqmaxlen = IFQ_MAXLEN;
177 extern struct domain inetdomain;
178 extern struct ipprotosw inetsw[];
179 u_char ip_protox[IPPROTO_MAX];
180 struct in_ifaddrhead in_ifaddrhead; /* first inet address */
181 struct in_ifaddrhashhead *in_ifaddrhashtbl; /* inet addr hash table */
182 u_long in_ifaddrhmask; /* mask for hash table */
184 SYSCTL_INT(_net_inet_ip, IPCTL_INTRQMAXLEN, intr_queue_maxlen, CTLFLAG_RW,
185 &ipintrq.ifq_maxlen, 0, "Maximum size of the IP input queue");
186 SYSCTL_INT(_net_inet_ip, IPCTL_INTRQDROPS, intr_queue_drops, CTLFLAG_RD,
187 &ipintrq.ifq_drops, 0, "Number of packets dropped from the IP input queue");
189 struct ip_stats ipstats_ary[MAXCPU];
192 sysctl_ipstats(SYSCTL_HANDLER_ARGS)
196 for (cpu = 0; cpu < ncpus; ++cpu) {
197 if ((error = SYSCTL_OUT(req, (void *)&ipstats_ary[cpu],
198 sizeof(struct ip_stats))))
200 if ((error = SYSCTL_IN(req, (void *)&ipstats_ary[cpu],
201 sizeof(struct ip_stats))))
207 SYSCTL_PROC(_net_inet_ip, IPCTL_STATS, stats, (CTLTYPE_OPAQUE | CTLFLAG_RW),
208 0, 0, sysctl_ipstats, "S,ip_stats", "IP statistics");
210 SYSCTL_STRUCT(_net_inet_ip, IPCTL_STATS, stats, CTLFLAG_RW,
211 &ipstat, ip_stats, "IP statistics");
214 /* Packet reassembly stuff */
215 #define IPREASS_NHASH_LOG2 6
216 #define IPREASS_NHASH (1 << IPREASS_NHASH_LOG2)
217 #define IPREASS_HMASK (IPREASS_NHASH - 1)
218 #define IPREASS_HASH(x,y) \
219 (((((x) & 0xF) | ((((x) >> 8) & 0xF) << 4)) ^ (y)) & IPREASS_HMASK)
221 static struct ipq ipq[IPREASS_NHASH];
222 const int ipintrq_present = 1;
225 SYSCTL_INT(_net_inet_ip, IPCTL_DEFMTU, mtu, CTLFLAG_RW,
226 &ip_mtu, 0, "Default MTU");
230 static int ipstealth = 0;
231 SYSCTL_INT(_net_inet_ip, OID_AUTO, stealth, CTLFLAG_RW, &ipstealth, 0, "");
233 static const int ipstealth = 0;
238 ip_fw_chk_t *ip_fw_chk_ptr;
243 ip_dn_io_t *ip_dn_io_ptr;
246 struct pfil_head inet_pfil_hook;
250 * XXX this is ugly -- the following two global variables are
251 * used to store packet state while it travels through the stack.
252 * Note that the code even makes assumptions on the size and
253 * alignment of fields inside struct ip_srcrt so e.g. adding some
254 * fields will break the code. This needs to be fixed.
256 * We need to save the IP options in case a protocol wants to respond
257 * to an incoming packet over the same route if the packet got here
258 * using IP source routing. This allows connection establishment and
259 * maintenance when the remote end is on a network that is not known
262 static int ip_nhops = 0;
264 static struct ip_srcrt {
265 struct in_addr dst; /* final destination */
266 char nop; /* one NOP to align */
267 char srcopt[IPOPT_OFFSET + 1]; /* OPTVAL, OLEN and OFFSET */
268 struct in_addr route[MAX_IPOPTLEN/sizeof(struct in_addr)];
271 static MALLOC_DEFINE(M_IPQ, "ipq", "IP Fragment Management");
272 static struct malloc_pipe ipq_mpipe;
274 static void save_rte (u_char *, struct in_addr);
275 static int ip_dooptions (struct mbuf *m, int,
276 struct sockaddr_in *next_hop);
277 static void ip_forward (struct mbuf *m, int srcrt,
278 struct sockaddr_in *next_hop);
279 static void ip_freef (struct ipq *);
280 static int ip_input_handler (struct netmsg *);
281 static struct mbuf *ip_reass (struct mbuf *, struct ipq *,
282 struct ipq *, u_int32_t *, u_int16_t *);
285 * IP initialization: fill in IP protocol switch table.
286 * All protocols not implemented in kernel go to raw IP protocol handler.
291 struct ipprotosw *pr;
298 * Make sure we can handle a reasonable number of fragments but
299 * cap it at 4000 (XXX).
301 mpipe_init(&ipq_mpipe, M_IPQ, sizeof(struct ipq),
302 IFQ_MAXLEN, 4000, 0, NULL);
303 TAILQ_INIT(&in_ifaddrhead);
304 in_ifaddrhashtbl = hashinit(INADDR_NHASH, M_IFADDR, &in_ifaddrhmask);
305 pr = (struct ipprotosw *)pffindproto(PF_INET, IPPROTO_RAW, SOCK_RAW);
308 for (i = 0; i < IPPROTO_MAX; i++)
309 ip_protox[i] = pr - inetsw;
310 for (pr = (struct ipprotosw *)inetdomain.dom_protosw;
311 pr < (struct ipprotosw *)inetdomain.dom_protoswNPROTOSW; pr++)
312 if (pr->pr_domain->dom_family == PF_INET &&
313 pr->pr_protocol && pr->pr_protocol != IPPROTO_RAW)
314 ip_protox[pr->pr_protocol] = pr - inetsw;
317 inet_pfil_hook.ph_type = PFIL_TYPE_AF;
318 inet_pfil_hook.ph_af = AF_INET;
319 if ((i = pfil_head_register(&inet_pfil_hook)) != 0)
320 printf("%s: WARNING: unable to register pfil hook, "
321 "error %d\n", __func__, i);
324 for (i = 0; i < IPREASS_NHASH; i++)
325 ipq[i].next = ipq[i].prev = &ipq[i];
327 maxnipq = nmbclusters / 32;
328 maxfragsperpacket = 16;
331 ip_id = time_second & 0xffff;
333 ipintrq.ifq_maxlen = ipqmaxlen;
336 * Initialize IP statistics.
338 * It is layed out as an array which is has one element for UP,
339 * and SMP_MAXCPU elements for SMP. This allows us to retain
340 * the access mechanism from userland for both UP and SMP.
343 for (cpu = 0; cpu < ncpus; ++cpu) {
344 bzero(&ipstats_ary[cpu], sizeof(struct ip_stats));
347 bzero(&ipstat, sizeof(struct ip_stats));
350 netisr_register(NETISR_IP, ip_mport, ip_input_handler);
354 * XXX watch out this one. It is perhaps used as a cache for
355 * the most recently used route ? it is cleared in in_addroute()
356 * when a new route is successfully created.
358 struct route ipforward_rt;
359 static struct sockaddr_in ipaddr = { sizeof(ipaddr), AF_INET };
361 /* Do transport protocol processing. */
363 transport_processing_oncpu(struct mbuf *m, int hlen, struct ip *ip,
364 struct sockaddr_in *nexthop)
367 * Switch out to protocol's input routine.
369 if (nexthop && ip->ip_p == IPPROTO_TCP) {
370 /* TCP needs IPFORWARD info if available */
373 tag.mh_type = MT_TAG;
374 tag.mh_flags = PACKET_TAG_IPFORWARD;
375 tag.mh_data = (caddr_t)nexthop;
378 (*inetsw[ip_protox[ip->ip_p]].pr_input)
379 ((struct mbuf *)&tag, hlen, ip->ip_p);
381 (*inetsw[ip_protox[ip->ip_p]].pr_input)(m, hlen, ip->ip_p);
385 struct netmsg_transport_packet {
386 struct lwkt_msg nm_lmsg;
387 struct mbuf *nm_mbuf;
389 boolean_t nm_hasnexthop;
390 struct sockaddr_in nm_nexthop;
394 transport_processing_handler(lwkt_msg_t lmsg)
396 struct netmsg_transport_packet *msg = (void *)lmsg;
397 struct sockaddr_in *nexthop;
400 ip = mtod(msg->nm_mbuf, struct ip *);
401 nexthop = msg->nm_hasnexthop ? &msg->nm_nexthop : NULL;
402 transport_processing_oncpu(msg->nm_mbuf, msg->nm_hlen, ip, nexthop);
403 lwkt_replymsg(lmsg, 0);
408 ip_input_handler(struct netmsg *msg0)
410 struct mbuf *m = ((struct netmsg_packet *)msg0)->nm_packet;
413 lwkt_replymsg(&msg0->nm_lmsg, 0);
418 * Ip input routine. Checksum and byte swap header. If fragmented
419 * try to reassemble. Process options. Pass to next level.
422 ip_input(struct mbuf *m)
426 struct in_ifaddr *ia = NULL;
428 int i, hlen, checkif;
430 struct in_addr pkt_dst;
431 u_int32_t divert_info = 0; /* packet divert/tee info */
432 struct ip_fw_args args;
433 boolean_t using_srcrt = FALSE; /* forward (by PFIL_HOOKS) */
434 boolean_t needredispatch = FALSE;
436 struct in_addr odst; /* original dst address(NAT) */
440 struct tdb_ident *tdbi;
441 struct secpolicy *sp;
448 args.divert_rule = 0; /* divert cookie */
449 args.next_hop = NULL;
451 /* Grab info from MT_TAG mbufs prepended to the chain. */
452 for (; m && m->m_type == MT_TAG; m = m->m_next) {
453 switch(m->_m_tag_id) {
455 printf("ip_input: unrecognised MT_TAG tag %d\n",
459 case PACKET_TAG_DUMMYNET:
460 args.rule = ((struct dn_pkt *)m)->rule;
463 case PACKET_TAG_DIVERT:
464 args.divert_rule = (int)m->m_hdr.mh_data & 0xffff;
467 case PACKET_TAG_IPFORWARD:
468 args.next_hop = (struct sockaddr_in *)m->m_hdr.mh_data;
473 KASSERT(m != NULL && (m->m_flags & M_PKTHDR) != 0,
474 ("ip_input: no HDR"));
476 if (args.rule) { /* dummynet already filtered us */
477 ip = mtod(m, struct ip *);
478 hlen = IP_VHL_HL(ip->ip_vhl) << 2;
484 /* length checks already done in ip_demux() */
485 KASSERT(m->m_len >= sizeof(ip), ("IP header not in one mbuf"));
487 ip = mtod(m, struct ip *);
489 if (IP_VHL_V(ip->ip_vhl) != IPVERSION) {
490 ipstat.ips_badvers++;
494 hlen = IP_VHL_HL(ip->ip_vhl) << 2;
495 /* length checks already done in ip_demux() */
496 KASSERT(hlen >= sizeof(struct ip), ("IP header len too small"));
497 KASSERT(m->m_len >= hlen, ("packet shorter than IP header length"));
499 /* 127/8 must not appear on wire - RFC1122 */
500 if ((ntohl(ip->ip_dst.s_addr) >> IN_CLASSA_NSHIFT) == IN_LOOPBACKNET ||
501 (ntohl(ip->ip_src.s_addr) >> IN_CLASSA_NSHIFT) == IN_LOOPBACKNET) {
502 if (!(m->m_pkthdr.rcvif->if_flags & IFF_LOOPBACK)) {
503 ipstat.ips_badaddr++;
508 if (m->m_pkthdr.csum_flags & CSUM_IP_CHECKED) {
509 sum = !(m->m_pkthdr.csum_flags & CSUM_IP_VALID);
511 if (hlen == sizeof(struct ip)) {
512 sum = in_cksum_hdr(ip);
514 sum = in_cksum(m, hlen);
523 * Convert fields to host representation.
525 ip->ip_len = ntohs(ip->ip_len);
526 if (ip->ip_len < hlen) {
530 ip->ip_off = ntohs(ip->ip_off);
533 * Check that the amount of data in the buffers
534 * is as at least much as the IP header would have us expect.
535 * Trim mbufs if longer than we expect.
536 * Drop packet if shorter than we expect.
538 if (m->m_pkthdr.len < ip->ip_len) {
539 ipstat.ips_tooshort++;
542 if (m->m_pkthdr.len > ip->ip_len) {
543 if (m->m_len == m->m_pkthdr.len) {
544 m->m_len = ip->ip_len;
545 m->m_pkthdr.len = ip->ip_len;
547 m_adj(m, ip->ip_len - m->m_pkthdr.len);
549 #if defined(IPSEC) && !defined(IPSEC_FILTERGIF)
551 * Bypass packet filtering for packets from a tunnel (gif).
553 if (ipsec_gethist(m, NULL))
559 * Right now when no processing on packet has done
560 * and it is still fresh out of network we do our black
562 * - Firewall: deny/allow/divert
563 * - Xlate: translate packet's addr/port (NAT).
564 * - Pipe: pass pkt through dummynet.
565 * - Wrap: fake packet's addr/port <unimpl.>
566 * - Encapsulate: put it in another IP and send out. <unimp.>
573 * Run through list of hooks for input packets.
575 * NB: Beware of the destination address changing (e.g.
576 * by NAT rewriting). When this happens, tell
577 * ip_forward to do the right thing.
579 if (pfil_has_hooks(&inet_pfil_hook)) {
581 if (pfil_run_hooks(&inet_pfil_hook, &m,
582 m->m_pkthdr.rcvif, PFIL_IN)) {
585 if (m == NULL) /* consumed by filter */
587 ip = mtod(m, struct ip *);
588 using_srcrt = (odst.s_addr != ip->ip_dst.s_addr);
592 if (fw_enable && IPFW_LOADED) {
594 * If we've been forwarded from the output side, then
595 * skip the firewall a second time
601 i = ip_fw_chk_ptr(&args);
604 if ( (i & IP_FW_PORT_DENY_FLAG) || m == NULL) { /* drop */
609 ip = mtod(m, struct ip *); /* just in case m changed */
610 if (i == 0 && args.next_hop == NULL) /* common case */
612 if (DUMMYNET_LOADED && (i & IP_FW_PORT_DYNT_FLAG)) {
613 /* Send packet to the appropriate pipe */
614 ip_dn_io_ptr(m, i&0xffff, DN_TO_IP_IN, &args);
618 if (i != 0 && !(i & IP_FW_PORT_DYNT_FLAG)) {
619 /* Divert or tee packet */
624 if (i == 0 && args.next_hop != NULL)
627 * if we get here, the packet must be dropped
635 * Process options and, if not destined for us,
636 * ship it on. ip_dooptions returns 1 when an
637 * error was detected (causing an icmp message
638 * to be sent and the original packet to be freed).
640 ip_nhops = 0; /* for source routed packets */
641 if (hlen > sizeof(struct ip) && ip_dooptions(m, 0, args.next_hop))
644 /* greedy RSVP, snatches any PATH packet of the RSVP protocol and no
645 * matter if it is destined to another node, or whether it is
646 * a multicast one, RSVP wants it! and prevents it from being forwarded
647 * anywhere else. Also checks if the rsvp daemon is running before
648 * grabbing the packet.
650 if (rsvp_on && ip->ip_p == IPPROTO_RSVP)
654 * Check our list of addresses, to see if the packet is for us.
655 * If we don't have any addresses, assume any unicast packet
656 * we receive might be for us (and let the upper layers deal
659 if (TAILQ_EMPTY(&in_ifaddrhead) && !(m->m_flags & (M_MCAST | M_BCAST)))
663 * Cache the destination address of the packet; this may be
664 * changed by use of 'ipfw fwd'.
666 pkt_dst = args.next_hop ? args.next_hop->sin_addr : ip->ip_dst;
669 * Enable a consistency check between the destination address
670 * and the arrival interface for a unicast packet (the RFC 1122
671 * strong ES model) if IP forwarding is disabled and the packet
672 * is not locally generated and the packet is not subject to
675 * XXX - Checking also should be disabled if the destination
676 * address is ipnat'ed to a different interface.
678 * XXX - Checking is incompatible with IP aliases added
679 * to the loopback interface instead of the interface where
680 * the packets are received.
682 checkif = ip_checkinterface &&
684 m->m_pkthdr.rcvif != NULL &&
685 !(m->m_pkthdr.rcvif->if_flags & IFF_LOOPBACK) &&
686 (args.next_hop == NULL);
689 * Check for exact addresses in the hash bucket.
691 LIST_FOREACH(ia, INADDR_HASH(pkt_dst.s_addr), ia_hash) {
693 * If the address matches, verify that the packet
694 * arrived via the correct interface if checking is
697 if (IA_SIN(ia)->sin_addr.s_addr == pkt_dst.s_addr &&
698 (!checkif || ia->ia_ifp == m->m_pkthdr.rcvif))
702 * Check for broadcast addresses.
704 * Only accept broadcast packets that arrive via the matching
705 * interface. Reception of forwarded directed broadcasts would
706 * be handled via ip_forward() and ether_output() with the loopback
707 * into the stack for SIMPLEX interfaces handled by ether_output().
709 if (m->m_pkthdr.rcvif->if_flags & IFF_BROADCAST) {
710 TAILQ_FOREACH(ifa, &m->m_pkthdr.rcvif->if_addrhead, ifa_link) {
711 if (ifa->ifa_addr->sa_family != AF_INET)
714 if (satosin(&ia->ia_broadaddr)->sin_addr.s_addr ==
717 if (ia->ia_netbroadcast.s_addr == pkt_dst.s_addr)
720 if (IA_SIN(ia)->sin_addr.s_addr == INADDR_ANY)
725 if (IN_MULTICAST(ntohl(ip->ip_dst.s_addr))) {
726 struct in_multi *inm;
729 * If we are acting as a multicast router, all
730 * incoming multicast packets are passed to the
731 * kernel-level multicast forwarding function.
732 * The packet is returned (relatively) intact; if
733 * ip_mforward() returns a non-zero value, the packet
734 * must be discarded, else it may be accepted below.
737 ip_mforward(ip, m->m_pkthdr.rcvif, m, NULL) != 0) {
738 ipstat.ips_cantforward++;
744 * The process-level routing daemon needs to receive
745 * all multicast IGMP packets, whether or not this
746 * host belongs to their destination groups.
748 if (ip->ip_p == IPPROTO_IGMP)
750 ipstat.ips_forward++;
753 * See if we belong to the destination multicast group on the
756 IN_LOOKUP_MULTI(ip->ip_dst, m->m_pkthdr.rcvif, inm);
758 ipstat.ips_notmember++;
764 if (ip->ip_dst.s_addr == INADDR_BROADCAST)
766 if (ip->ip_dst.s_addr == INADDR_ANY)
770 * FAITH(Firewall Aided Internet Translator)
772 if (m->m_pkthdr.rcvif && m->m_pkthdr.rcvif->if_type == IFT_FAITH) {
774 if (ip->ip_p == IPPROTO_TCP || ip->ip_p == IPPROTO_ICMP)
782 * Not for us; forward if possible and desirable.
785 ipstat.ips_cantforward++;
790 * Enforce inbound IPsec SPD.
792 if (ipsec4_in_reject(m, NULL)) {
793 ipsecstat.in_polvio++;
798 mtag = m_tag_find(m, PACKET_TAG_IPSEC_IN_DONE, NULL);
801 tdbi = (struct tdb_ident *)(mtag + 1);
802 sp = ipsec_getpolicy(tdbi, IPSEC_DIR_INBOUND);
804 sp = ipsec_getpolicybyaddr(m, IPSEC_DIR_INBOUND,
805 IP_FORWARDING, &error);
807 if (sp == NULL) { /* NB: can happen if error */
809 /*XXX error stat???*/
810 DPRINTF(("ip_input: no SP for forwarding\n")); /*XXX*/
815 * Check security policy against packet attributes.
817 error = ipsec_in_reject(sp, m);
821 ipstat.ips_cantforward++;
825 ip_forward(m, using_srcrt, args.next_hop);
832 * IPSTEALTH: Process non-routing options only
833 * if the packet is destined for us.
836 hlen > sizeof(struct ip) &&
837 ip_dooptions(m, 1, args.next_hop))
840 /* Count the packet in the ip address stats */
842 ia->ia_ifa.if_ipackets++;
843 ia->ia_ifa.if_ibytes += m->m_pkthdr.len;
847 * If offset or IP_MF are set, must reassemble.
848 * Otherwise, nothing need be done.
849 * (We could look in the reassembly queue to see
850 * if the packet was previously fragmented,
851 * but it's not worth the time; just let them time out.)
853 if (ip->ip_off & (IP_MF | IP_OFFMASK)) {
855 /* If maxnipq is 0, never accept fragments. */
857 ipstat.ips_fragments++;
858 ipstat.ips_fragdropped++;
862 sum = IPREASS_HASH(ip->ip_src.s_addr, ip->ip_id);
864 * Look for queue of fragments
867 for (fp = ipq[sum].next; fp != &ipq[sum]; fp = fp->next)
868 if (ip->ip_id == fp->ipq_id &&
869 ip->ip_src.s_addr == fp->ipq_src.s_addr &&
870 ip->ip_dst.s_addr == fp->ipq_dst.s_addr &&
871 ip->ip_p == fp->ipq_p)
877 * Enforce upper bound on number of fragmented packets
878 * for which we attempt reassembly;
879 * If maxnipq is -1, accept all fragments without limitation.
881 if ((nipq > maxnipq) && (maxnipq > 0)) {
883 * drop something from the tail of the current queue
884 * before proceeding further
886 if (ipq[sum].prev == &ipq[sum]) { /* gak */
887 for (i = 0; i < IPREASS_NHASH; i++) {
888 if (ipq[i].prev != &ipq[i]) {
889 ipstat.ips_fragtimeout +=
890 ipq[i].prev->ipq_nfrags;
891 ip_freef(ipq[i].prev);
896 ipstat.ips_fragtimeout +=
897 ipq[sum].prev->ipq_nfrags;
898 ip_freef(ipq[sum].prev);
903 * Adjust ip_len to not reflect header,
904 * convert offset of this to bytes.
907 if (ip->ip_off & IP_MF) {
909 * Make sure that fragments have a data length
910 * that's a non-zero multiple of 8 bytes.
912 if (ip->ip_len == 0 || (ip->ip_len & 0x7) != 0) {
913 ipstat.ips_toosmall++; /* XXX */
916 m->m_flags |= M_FRAG;
918 m->m_flags &= ~M_FRAG;
922 * Attempt reassembly; if it succeeds, proceed.
923 * ip_reass() will return a different mbuf, and update
924 * the divert info in divert_info and args.divert_rule.
926 ipstat.ips_fragments++;
927 m->m_pkthdr.header = ip;
928 m = ip_reass(m, fp, &ipq[sum], &divert_info, &args.divert_rule);
931 ipstat.ips_reassembled++;
932 needredispatch = TRUE;
933 ip = mtod(m, struct ip *);
934 /* Get the header length of the reassembled packet */
935 hlen = IP_VHL_HL(ip->ip_vhl) << 2;
937 /* Restore original checksum before diverting packet */
938 if (divert_info != 0) {
940 ip->ip_len = htons(ip->ip_len);
941 ip->ip_off = htons(ip->ip_off);
943 if (hlen == sizeof(struct ip))
944 ip->ip_sum = in_cksum_hdr(ip);
946 ip->ip_sum = in_cksum(m, hlen);
947 ip->ip_off = ntohs(ip->ip_off);
948 ip->ip_len = ntohs(ip->ip_len);
958 * Divert or tee packet to the divert protocol if required.
960 if (divert_info != 0) {
961 struct mbuf *clone = NULL;
963 /* Clone packet if we're doing a 'tee' */
964 if ((divert_info & IP_FW_PORT_TEE_FLAG) != 0)
965 clone = m_dup(m, MB_DONTWAIT);
967 /* Restore packet header fields to original values */
969 ip->ip_len = htons(ip->ip_len);
970 ip->ip_off = htons(ip->ip_off);
972 /* Deliver packet to divert input routine */
973 divert_packet(m, 1, divert_info & 0xffff, args.divert_rule);
974 ipstat.ips_delivered++;
976 /* If 'tee', continue with original packet */
980 ip = mtod(m, struct ip *);
983 * Jump backwards to complete processing of the
984 * packet. But first clear divert_info to avoid
985 * entering this block again.
986 * We do not need to clear args.divert_rule
987 * or args.next_hop as they will not be used.
996 * enforce IPsec policy checking if we are seeing last header.
997 * note that we do not visit this with protocols with pcb layer
998 * code - like udp/tcp/raw ip.
1000 if ((inetsw[ip_protox[ip->ip_p]].pr_flags & PR_LASTHDR) &&
1001 ipsec4_in_reject(m, NULL)) {
1002 ipsecstat.in_polvio++;
1008 * enforce IPsec policy checking if we are seeing last header.
1009 * note that we do not visit this with protocols with pcb layer
1010 * code - like udp/tcp/raw ip.
1012 if (inetsw[ip_protox[ip->ip_p]].pr_flags & PR_LASTHDR) {
1014 * Check if the packet has already had IPsec processing
1015 * done. If so, then just pass it along. This tag gets
1016 * set during AH, ESP, etc. input handling, before the
1017 * packet is returned to the ip input queue for delivery.
1019 mtag = m_tag_find(m, PACKET_TAG_IPSEC_IN_DONE, NULL);
1022 tdbi = (struct tdb_ident *)(mtag + 1);
1023 sp = ipsec_getpolicy(tdbi, IPSEC_DIR_INBOUND);
1025 sp = ipsec_getpolicybyaddr(m, IPSEC_DIR_INBOUND,
1026 IP_FORWARDING, &error);
1030 * Check security policy against packet attributes.
1032 error = ipsec_in_reject(sp, m);
1035 /* XXX error stat??? */
1037 DPRINTF(("ip_input: no SP, packet discarded\n"));/*XXX*/
1044 #endif /* FAST_IPSEC */
1046 ipstat.ips_delivered++;
1047 if (needredispatch) {
1048 struct netmsg_transport_packet *msg;
1051 msg = malloc(sizeof(struct netmsg_transport_packet),
1052 M_LWKTMSG, M_INTWAIT | M_NULLOK);
1056 lwkt_initmsg(&msg->nm_lmsg, &netisr_afree_rport, 0,
1057 lwkt_cmd_func(transport_processing_handler),
1060 msg->nm_hlen = hlen;
1061 msg->nm_hasnexthop = (args.next_hop != NULL);
1062 if (msg->nm_hasnexthop)
1063 msg->nm_nexthop = *args.next_hop; /* structure copy */
1065 ip->ip_off = htons(ip->ip_off);
1066 ip->ip_len = htons(ip->ip_len);
1070 ip->ip_len = ntohs(ip->ip_len);
1071 ip->ip_off = ntohs(ip->ip_off);
1073 lwkt_sendmsg(port, &msg->nm_lmsg);
1075 transport_processing_oncpu(m, hlen, ip, args.next_hop);
1084 * Take incoming datagram fragment and try to reassemble it into
1085 * whole datagram. If a chain for reassembly of this datagram already
1086 * exists, then it is given as fp; otherwise have to make a chain.
1088 * When IPDIVERT enabled, keep additional state with each packet that
1089 * tells us if we need to divert or tee the packet we're building.
1090 * In particular, *divinfo includes the port and TEE flag,
1091 * *divert_rule is the number of the matching rule.
1094 static struct mbuf *
1095 ip_reass(struct mbuf *m, struct ipq *fp, struct ipq *where,
1096 u_int32_t *divinfo, u_int16_t *divert_rule)
1098 struct ip *ip = mtod(m, struct ip *);
1099 struct mbuf *p = NULL, *q, *nq;
1101 int hlen = IP_VHL_HL(ip->ip_vhl) << 2;
1105 * Presence of header sizes in mbufs
1106 * would confuse code below.
1112 * If first fragment to arrive, create a reassembly queue.
1115 if ((fp = mpipe_alloc_nowait(&ipq_mpipe)) == NULL)
1120 fp->ipq_ttl = IPFRAGTTL;
1121 fp->ipq_p = ip->ip_p;
1122 fp->ipq_id = ip->ip_id;
1123 fp->ipq_src = ip->ip_src;
1124 fp->ipq_dst = ip->ip_dst;
1126 m->m_nextpkt = NULL;
1128 fp->ipq_div_info = 0;
1129 fp->ipq_div_cookie = 0;
1136 #define GETIP(m) ((struct ip*)((m)->m_pkthdr.header))
1139 * Find a segment which begins after this one does.
1141 for (p = NULL, q = fp->ipq_frags; q; p = q, q = q->m_nextpkt)
1142 if (GETIP(q)->ip_off > ip->ip_off)
1146 * If there is a preceding segment, it may provide some of
1147 * our data already. If so, drop the data from the incoming
1148 * segment. If it provides all of our data, drop us, otherwise
1149 * stick new segment in the proper place.
1151 * If some of the data is dropped from the the preceding
1152 * segment, then it's checksum is invalidated.
1155 i = GETIP(p)->ip_off + GETIP(p)->ip_len - ip->ip_off;
1157 if (i >= ip->ip_len)
1160 m->m_pkthdr.csum_flags = 0;
1164 m->m_nextpkt = p->m_nextpkt;
1167 m->m_nextpkt = fp->ipq_frags;
1172 * While we overlap succeeding segments trim them or,
1173 * if they are completely covered, dequeue them.
1175 for (; q != NULL && ip->ip_off + ip->ip_len > GETIP(q)->ip_off;
1177 i = (ip->ip_off + ip->ip_len) - GETIP(q)->ip_off;
1178 if (i < GETIP(q)->ip_len) {
1179 GETIP(q)->ip_len -= i;
1180 GETIP(q)->ip_off += i;
1182 q->m_pkthdr.csum_flags = 0;
1187 ipstat.ips_fragdropped++;
1196 * Transfer firewall instructions to the fragment structure.
1197 * Only trust info in the fragment at offset 0.
1199 if (ip->ip_off == 0) {
1200 fp->ipq_div_info = *divinfo;
1201 fp->ipq_div_cookie = *divert_rule;
1208 * Check for complete reassembly and perform frag per packet
1211 * Frag limiting is performed here so that the nth frag has
1212 * a chance to complete the packet before we drop the packet.
1213 * As a result, n+1 frags are actually allowed per packet, but
1214 * only n will ever be stored. (n = maxfragsperpacket.)
1218 for (p = NULL, q = fp->ipq_frags; q; p = q, q = q->m_nextpkt) {
1219 if (GETIP(q)->ip_off != next) {
1220 if (fp->ipq_nfrags > maxfragsperpacket) {
1221 ipstat.ips_fragdropped += fp->ipq_nfrags;
1226 next += GETIP(q)->ip_len;
1228 /* Make sure the last packet didn't have the IP_MF flag */
1229 if (p->m_flags & M_FRAG) {
1230 if (fp->ipq_nfrags > maxfragsperpacket) {
1231 ipstat.ips_fragdropped += fp->ipq_nfrags;
1238 * Reassembly is complete. Make sure the packet is a sane size.
1242 if (next + (IP_VHL_HL(ip->ip_vhl) << 2) > IP_MAXPACKET) {
1243 ipstat.ips_toolong++;
1244 ipstat.ips_fragdropped += fp->ipq_nfrags;
1250 * Concatenate fragments.
1257 q->m_nextpkt = NULL;
1258 for (q = nq; q != NULL; q = nq) {
1260 q->m_nextpkt = NULL;
1261 m->m_pkthdr.csum_flags &= q->m_pkthdr.csum_flags;
1262 m->m_pkthdr.csum_data += q->m_pkthdr.csum_data;
1268 * Extract firewall instructions from the fragment structure.
1270 *divinfo = fp->ipq_div_info;
1271 *divert_rule = fp->ipq_div_cookie;
1275 * Create header for new ip packet by
1276 * modifying header of first packet;
1277 * dequeue and discard fragment reassembly header.
1278 * Make header visible.
1281 ip->ip_src = fp->ipq_src;
1282 ip->ip_dst = fp->ipq_dst;
1285 mpipe_free(&ipq_mpipe, fp);
1286 m->m_len += (IP_VHL_HL(ip->ip_vhl) << 2);
1287 m->m_data -= (IP_VHL_HL(ip->ip_vhl) << 2);
1288 /* some debugging cruft by sklower, below, will go away soon */
1289 if (m->m_flags & M_PKTHDR) { /* XXX this should be done elsewhere */
1292 for (n = m; n; n = n->m_next)
1294 m->m_pkthdr.len = plen;
1303 ipstat.ips_fragdropped++;
1313 * Free a fragment reassembly header and all
1314 * associated datagrams.
1317 ip_freef(struct ipq *fp)
1321 while (fp->ipq_frags) {
1323 fp->ipq_frags = q->m_nextpkt;
1327 mpipe_free(&ipq_mpipe, fp);
1332 * IP timer processing;
1333 * if a timer expires on a reassembly
1334 * queue, discard it.
1343 for (i = 0; i < IPREASS_NHASH; i++) {
1347 while (fp != &ipq[i]) {
1350 if (fp->prev->ipq_ttl == 0) {
1351 ipstat.ips_fragtimeout += fp->prev->ipq_nfrags;
1357 * If we are over the maximum number of fragments
1358 * (due to the limit being lowered), drain off
1359 * enough to get down to the new limit.
1361 if (maxnipq >= 0 && nipq > maxnipq) {
1362 for (i = 0; i < IPREASS_NHASH; i++) {
1363 while (nipq > maxnipq &&
1364 (ipq[i].next != &ipq[i])) {
1365 ipstat.ips_fragdropped +=
1366 ipq[i].next->ipq_nfrags;
1367 ip_freef(ipq[i].next);
1376 * Drain off all datagram fragments.
1383 for (i = 0; i < IPREASS_NHASH; i++) {
1384 while (ipq[i].next != &ipq[i]) {
1385 ipstat.ips_fragdropped += ipq[i].next->ipq_nfrags;
1386 ip_freef(ipq[i].next);
1393 * Do option processing on a datagram,
1394 * possibly discarding it if bad options are encountered,
1395 * or forwarding it if source-routed.
1396 * The pass argument is used when operating in the IPSTEALTH
1397 * mode to tell what options to process:
1398 * [LS]SRR (pass 0) or the others (pass 1).
1399 * The reason for as many as two passes is that when doing IPSTEALTH,
1400 * non-routing options should be processed only if the packet is for us.
1401 * Returns 1 if packet has been forwarded/freed,
1402 * 0 if the packet should be processed further.
1405 ip_dooptions(struct mbuf *m, int pass, struct sockaddr_in *next_hop)
1407 struct ip *ip = mtod(m, struct ip *);
1409 struct in_ifaddr *ia;
1410 int opt, optlen, cnt, off, code, type = ICMP_PARAMPROB;
1411 boolean_t forward = FALSE;
1412 struct in_addr *sin, dst;
1416 cp = (u_char *)(ip + 1);
1417 cnt = (IP_VHL_HL(ip->ip_vhl) << 2) - sizeof(struct ip);
1418 for (; cnt > 0; cnt -= optlen, cp += optlen) {
1419 opt = cp[IPOPT_OPTVAL];
1420 if (opt == IPOPT_EOL)
1422 if (opt == IPOPT_NOP)
1425 if (cnt < IPOPT_OLEN + sizeof(*cp)) {
1426 code = &cp[IPOPT_OLEN] - (u_char *)ip;
1429 optlen = cp[IPOPT_OLEN];
1430 if (optlen < IPOPT_OLEN + sizeof(*cp) || optlen > cnt) {
1431 code = &cp[IPOPT_OLEN] - (u_char *)ip;
1441 * Source routing with record.
1442 * Find interface with current destination address.
1443 * If none on this machine then drop if strictly routed,
1444 * or do nothing if loosely routed.
1445 * Record interface address and bring up next address
1446 * component. If strictly routed make sure next
1447 * address is on directly accessible net.
1451 if (ipstealth && pass > 0)
1453 if (optlen < IPOPT_OFFSET + sizeof(*cp)) {
1454 code = &cp[IPOPT_OLEN] - (u_char *)ip;
1457 if ((off = cp[IPOPT_OFFSET]) < IPOPT_MINOFF) {
1458 code = &cp[IPOPT_OFFSET] - (u_char *)ip;
1461 ipaddr.sin_addr = ip->ip_dst;
1462 ia = (struct in_ifaddr *)
1463 ifa_ifwithaddr((struct sockaddr *)&ipaddr);
1465 if (opt == IPOPT_SSRR) {
1466 type = ICMP_UNREACH;
1467 code = ICMP_UNREACH_SRCFAIL;
1470 if (!ip_dosourceroute)
1471 goto nosourcerouting;
1473 * Loose routing, and not at next destination
1474 * yet; nothing to do except forward.
1478 off--; /* 0 origin */
1479 if (off > optlen - (int)sizeof(struct in_addr)) {
1481 * End of source route. Should be for us.
1483 if (!ip_acceptsourceroute)
1484 goto nosourcerouting;
1485 save_rte(cp, ip->ip_src);
1490 if (!ip_dosourceroute) {
1492 char buf[16]; /* aaa.bbb.ccc.ddd\0 */
1494 * Acting as a router, so generate ICMP
1497 strcpy(buf, inet_ntoa(ip->ip_dst));
1499 "attempted source route from %s to %s\n",
1500 inet_ntoa(ip->ip_src), buf);
1501 type = ICMP_UNREACH;
1502 code = ICMP_UNREACH_SRCFAIL;
1506 * Not acting as a router,
1510 ipstat.ips_cantforward++;
1517 * locate outgoing interface
1519 (void)memcpy(&ipaddr.sin_addr, cp + off,
1520 sizeof(ipaddr.sin_addr));
1522 if (opt == IPOPT_SSRR) {
1523 #define INA struct in_ifaddr *
1524 #define SA struct sockaddr *
1525 if ((ia = (INA)ifa_ifwithdstaddr((SA)&ipaddr))
1527 ia = (INA)ifa_ifwithnet((SA)&ipaddr);
1529 ia = ip_rtaddr(ipaddr.sin_addr, &ipforward_rt);
1531 type = ICMP_UNREACH;
1532 code = ICMP_UNREACH_SRCFAIL;
1535 ip->ip_dst = ipaddr.sin_addr;
1536 (void)memcpy(cp + off, &(IA_SIN(ia)->sin_addr),
1537 sizeof(struct in_addr));
1538 cp[IPOPT_OFFSET] += sizeof(struct in_addr);
1540 * Let ip_intr's mcast routing check handle mcast pkts
1542 forward = !IN_MULTICAST(ntohl(ip->ip_dst.s_addr));
1546 if (ipstealth && pass == 0)
1548 if (optlen < IPOPT_OFFSET + sizeof(*cp)) {
1549 code = &cp[IPOPT_OFFSET] - (u_char *)ip;
1552 if ((off = cp[IPOPT_OFFSET]) < IPOPT_MINOFF) {
1553 code = &cp[IPOPT_OFFSET] - (u_char *)ip;
1557 * If no space remains, ignore.
1559 off--; /* 0 origin */
1560 if (off > optlen - (int)sizeof(struct in_addr))
1562 (void)memcpy(&ipaddr.sin_addr, &ip->ip_dst,
1563 sizeof(ipaddr.sin_addr));
1565 * locate outgoing interface; if we're the destination,
1566 * use the incoming interface (should be same).
1568 if ((ia = (INA)ifa_ifwithaddr((SA)&ipaddr)) == NULL &&
1569 (ia = ip_rtaddr(ipaddr.sin_addr, &ipforward_rt))
1571 type = ICMP_UNREACH;
1572 code = ICMP_UNREACH_HOST;
1575 (void)memcpy(cp + off, &(IA_SIN(ia)->sin_addr),
1576 sizeof(struct in_addr));
1577 cp[IPOPT_OFFSET] += sizeof(struct in_addr);
1581 if (ipstealth && pass == 0)
1583 code = cp - (u_char *)ip;
1584 if (optlen < 4 || optlen > 40) {
1585 code = &cp[IPOPT_OLEN] - (u_char *)ip;
1588 if ((off = cp[IPOPT_OFFSET]) < 5) {
1589 code = &cp[IPOPT_OLEN] - (u_char *)ip;
1592 if (off > optlen - (int)sizeof(int32_t)) {
1593 cp[IPOPT_OFFSET + 1] += (1 << 4);
1594 if ((cp[IPOPT_OFFSET + 1] & 0xf0) == 0) {
1595 code = &cp[IPOPT_OFFSET] - (u_char *)ip;
1600 off--; /* 0 origin */
1601 sin = (struct in_addr *)(cp + off);
1602 switch (cp[IPOPT_OFFSET + 1] & 0x0f) {
1604 case IPOPT_TS_TSONLY:
1607 case IPOPT_TS_TSANDADDR:
1608 if (off + sizeof(n_time) +
1609 sizeof(struct in_addr) > optlen) {
1610 code = &cp[IPOPT_OFFSET] - (u_char *)ip;
1613 ipaddr.sin_addr = dst;
1614 ia = (INA)ifaof_ifpforaddr((SA)&ipaddr,
1618 (void)memcpy(sin, &IA_SIN(ia)->sin_addr,
1619 sizeof(struct in_addr));
1620 cp[IPOPT_OFFSET] += sizeof(struct in_addr);
1621 off += sizeof(struct in_addr);
1624 case IPOPT_TS_PRESPEC:
1625 if (off + sizeof(n_time) +
1626 sizeof(struct in_addr) > optlen) {
1627 code = &cp[IPOPT_OFFSET] - (u_char *)ip;
1630 (void)memcpy(&ipaddr.sin_addr, sin,
1631 sizeof(struct in_addr));
1632 if (ifa_ifwithaddr((SA)&ipaddr) == NULL)
1634 cp[IPOPT_OFFSET] += sizeof(struct in_addr);
1635 off += sizeof(struct in_addr);
1639 code = &cp[IPOPT_OFFSET + 1] - (u_char *)ip;
1643 (void)memcpy(cp + off, &ntime, sizeof(n_time));
1644 cp[IPOPT_OFFSET] += sizeof(n_time);
1647 if (forward && ipforwarding) {
1648 ip_forward(m, 1, next_hop);
1653 icmp_error(m, type, code, 0, NULL);
1654 ipstat.ips_badoptions++;
1659 * Given address of next destination (final or next hop),
1660 * return internet address info of interface to be used to get there.
1663 ip_rtaddr(struct in_addr dst, struct route *rt)
1665 struct sockaddr_in *sin;
1667 sin = (struct sockaddr_in *)&rt->ro_dst;
1669 if (rt->ro_rt == NULL || dst.s_addr != sin->sin_addr.s_addr) {
1670 if (rt->ro_rt != NULL) {
1674 sin->sin_family = AF_INET;
1675 sin->sin_len = sizeof(*sin);
1676 sin->sin_addr = dst;
1677 rtalloc_ign(rt, RTF_PRCLONING);
1680 if (rt->ro_rt == NULL)
1683 return (ifatoia(rt->ro_rt->rt_ifa));
1687 * Save incoming source route for use in replies,
1688 * to be picked up later by ip_srcroute if the receiver is interested.
1691 save_rte(u_char *option, struct in_addr dst)
1695 olen = option[IPOPT_OLEN];
1698 printf("save_rte: olen %d\n", olen);
1700 if (olen > sizeof(ip_srcrt) - (1 + sizeof(dst)))
1702 bcopy(option, ip_srcrt.srcopt, olen);
1703 ip_nhops = (olen - IPOPT_OFFSET - 1) / sizeof(struct in_addr);
1708 * Retrieve incoming source route for use in replies,
1709 * in the same form used by setsockopt.
1710 * The first hop is placed before the options, will be removed later.
1715 struct in_addr *p, *q;
1720 m = m_get(MB_DONTWAIT, MT_HEADER);
1724 #define OPTSIZ (sizeof(ip_srcrt.nop) + sizeof(ip_srcrt.srcopt))
1726 /* length is (nhops+1)*sizeof(addr) + sizeof(nop + srcrt header) */
1727 m->m_len = ip_nhops * sizeof(struct in_addr) + sizeof(struct in_addr) +
1731 printf("ip_srcroute: nhops %d mlen %d", ip_nhops, m->m_len);
1735 * First save first hop for return route
1737 p = &ip_srcrt.route[ip_nhops - 1];
1738 *(mtod(m, struct in_addr *)) = *p--;
1741 printf(" hops %lx", ntohl(mtod(m, struct in_addr *)->s_addr));
1745 * Copy option fields and padding (nop) to mbuf.
1747 ip_srcrt.nop = IPOPT_NOP;
1748 ip_srcrt.srcopt[IPOPT_OFFSET] = IPOPT_MINOFF;
1749 (void)memcpy(mtod(m, caddr_t) + sizeof(struct in_addr), &ip_srcrt.nop,
1751 q = (struct in_addr *)(mtod(m, caddr_t) +
1752 sizeof(struct in_addr) + OPTSIZ);
1755 * Record return path as an IP source route,
1756 * reversing the path (pointers are now aligned).
1758 while (p >= ip_srcrt.route) {
1761 printf(" %lx", ntohl(q->s_addr));
1766 * Last hop goes to final destination.
1771 printf(" %lx\n", ntohl(q->s_addr));
1777 * Strip out IP options.
1780 ip_stripoptions(struct mbuf *m)
1783 struct ip *ip = mtod(m, struct ip *);
1787 optlen = (IP_VHL_HL(ip->ip_vhl) << 2) - sizeof(struct ip);
1788 opts = (caddr_t)(ip + 1);
1789 datalen = m->m_len - (sizeof(struct ip) + optlen);
1790 bcopy(opts + optlen, opts, datalen);
1792 if (m->m_flags & M_PKTHDR)
1793 m->m_pkthdr.len -= optlen;
1794 ip->ip_vhl = IP_MAKE_VHL(IPVERSION, sizeof(struct ip) >> 2);
1797 u_char inetctlerrmap[PRC_NCMDS] = {
1799 0, EMSGSIZE, EHOSTDOWN, EHOSTUNREACH,
1800 EHOSTUNREACH, EHOSTUNREACH, ECONNREFUSED, ECONNREFUSED,
1801 EMSGSIZE, EHOSTUNREACH, 0, 0,
1803 ENOPROTOOPT, ECONNREFUSED
1807 * Forward a packet. If some error occurs return the sender
1808 * an icmp packet. Note we can't always generate a meaningful
1809 * icmp message because icmp doesn't have a large enough repertoire
1810 * of codes and types.
1812 * If not forwarding, just drop the packet. This could be confusing
1813 * if ipforwarding was zero but some routing protocol was advancing
1814 * us as a gateway to somewhere. However, we must let the routing
1815 * protocol deal with that.
1817 * The using_srcrt parameter indicates whether the packet is being forwarded
1818 * via a source route.
1821 ip_forward(struct mbuf *m, int using_srcrt, struct sockaddr_in *next_hop)
1823 struct ip *ip = mtod(m, struct ip *);
1824 struct sockaddr_in *sin;
1826 int error, type = 0, code = 0;
1829 struct in_addr pkt_dst;
1830 struct ifnet *destifp;
1832 #if defined(IPSEC) || defined(FAST_IPSEC)
1833 struct ifnet dummyifp;
1838 * Cache the destination address of the packet; this may be
1839 * changed by use of 'ipfw fwd'.
1841 pkt_dst = next_hop ? next_hop->sin_addr : ip->ip_dst;
1845 printf("forward: src %x dst %x ttl %x\n",
1846 ip->ip_src.s_addr, pkt_dst.s_addr, ip->ip_ttl);
1849 if (m->m_flags & (M_BCAST | M_MCAST) || !in_canforward(pkt_dst)) {
1850 ipstat.ips_cantforward++;
1854 if (!ipstealth && ip->ip_ttl <= IPTTLDEC) {
1855 icmp_error(m, ICMP_TIMXCEED, ICMP_TIMXCEED_INTRANS, dest, NULL);
1859 sin = (struct sockaddr_in *)&ipforward_rt.ro_dst;
1860 if ((rt = ipforward_rt.ro_rt) == NULL ||
1861 pkt_dst.s_addr != sin->sin_addr.s_addr) {
1862 if (ipforward_rt.ro_rt != NULL) {
1863 RTFREE(ipforward_rt.ro_rt);
1864 ipforward_rt.ro_rt = NULL;
1866 sin->sin_family = AF_INET;
1867 sin->sin_len = sizeof(*sin);
1868 sin->sin_addr = pkt_dst;
1870 rtalloc_ign(&ipforward_rt, RTF_PRCLONING);
1871 if (ipforward_rt.ro_rt == NULL) {
1872 icmp_error(m, ICMP_UNREACH, ICMP_UNREACH_HOST, dest,
1876 rt = ipforward_rt.ro_rt;
1880 * Save the IP header and at most 8 bytes of the payload,
1881 * in case we need to generate an ICMP message to the src.
1883 * XXX this can be optimized a lot by saving the data in a local
1884 * buffer on the stack (72 bytes at most), and only allocating the
1885 * mbuf if really necessary. The vast majority of the packets
1886 * are forwarded without having to send an ICMP back (either
1887 * because unnecessary, or because rate limited), so we are
1888 * really we are wasting a lot of work here.
1890 * We don't use m_copy() because it might return a reference
1891 * to a shared cluster. Both this function and ip_output()
1892 * assume exclusive access to the IP header in `m', so any
1893 * data in a cluster may change before we reach icmp_error().
1895 MGET(mcopy, MB_DONTWAIT, m->m_type);
1896 if (mcopy != NULL && !m_dup_pkthdr(mcopy, m, MB_DONTWAIT)) {
1898 * It's probably ok if the pkthdr dup fails (because
1899 * the deep copy of the tag chain failed), but for now
1900 * be conservative and just discard the copy since
1901 * code below may some day want the tags.
1906 if (mcopy != NULL) {
1907 mcopy->m_len = imin((IP_VHL_HL(ip->ip_vhl) << 2) + 8,
1909 m_copydata(m, 0, mcopy->m_len, mtod(mcopy, caddr_t));
1913 ip->ip_ttl -= IPTTLDEC;
1916 * If forwarding packet using same interface that it came in on,
1917 * perhaps should send a redirect to sender to shortcut a hop.
1918 * Only send redirect if source is sending directly to us,
1919 * and if packet was not source routed (or has any options).
1920 * Also, don't send redirect if forwarding using a default route
1921 * or a route modified by a redirect.
1923 if (rt->rt_ifp == m->m_pkthdr.rcvif &&
1924 !(rt->rt_flags & (RTF_DYNAMIC | RTF_MODIFIED)) &&
1925 satosin(rt_key(rt))->sin_addr.s_addr != INADDR_ANY &&
1926 ipsendredirects && !using_srcrt && next_hop != NULL) {
1927 u_long src = ntohl(ip->ip_src.s_addr);
1929 #define RTA(rt) ((struct in_ifaddr *)(rt->rt_ifa))
1930 if (RTA(rt) != NULL &&
1931 (src & RTA(rt)->ia_subnetmask) == RTA(rt)->ia_subnet) {
1932 if (rt->rt_flags & RTF_GATEWAY)
1933 dest = satosin(rt->rt_gateway)->sin_addr.s_addr;
1935 dest = pkt_dst.s_addr;
1937 * Router requirements says to only send
1940 type = ICMP_REDIRECT;
1941 code = ICMP_REDIRECT_HOST;
1944 printf("redirect (%d) to %x\n", code, dest);
1950 /* Pass IPFORWARD info if available */
1951 tag.mh_type = MT_TAG;
1952 tag.mh_flags = PACKET_TAG_IPFORWARD;
1953 tag.mh_data = (caddr_t)next_hop;
1955 m = (struct mbuf *)&tag;
1958 error = ip_output(m, NULL, &ipforward_rt, IP_FORWARDING, NULL, NULL);
1961 ipstat.ips_cantforward++;
1963 ipstat.ips_forward++;
1965 ipstat.ips_redirectsent++;
1968 ipflow_create(&ipforward_rt, mcopy);
1980 case 0: /* forwarded, but need redirect */
1981 /* type, code set above */
1984 case ENETUNREACH: /* shouldn't happen, checked above */
1989 type = ICMP_UNREACH;
1990 code = ICMP_UNREACH_HOST;
1994 type = ICMP_UNREACH;
1995 code = ICMP_UNREACH_NEEDFRAG;
1998 * If the packet is routed over IPsec tunnel, tell the
1999 * originator the tunnel MTU.
2000 * tunnel MTU = if MTU - sizeof(IP) - ESP/AH hdrsiz
2003 if (ipforward_rt.ro_rt != NULL) {
2004 struct secpolicy *sp = NULL;
2009 sp = ipsec4_getpolicybyaddr(mcopy,
2015 destifp = ipforward_rt.ro_rt->rt_ifp;
2017 /* count IPsec header size */
2018 ipsechdr = ipsec4_hdrsiz(mcopy,
2023 * find the correct route for outer IPv4
2024 * header, compute tunnel MTU.
2027 * The "dummyifp" code relies upon the fact
2028 * that icmp_error() touches only ifp->if_mtu.
2032 if (sp->req != NULL && sp->req->sav != NULL &&
2033 sp->req->sav->sah != NULL) {
2034 ro = &sp->req->sav->sah->sa_route;
2035 if (ro->ro_rt != NULL &&
2036 ro->ro_rt->rt_ifp != NULL) {
2038 ro->ro_rt->rt_ifp->if_mtu;
2039 dummyifp.if_mtu -= ipsechdr;
2040 destifp = &dummyifp;
2049 * If the packet is routed over IPsec tunnel, tell the
2050 * originator the tunnel MTU.
2051 * tunnel MTU = if MTU - sizeof(IP) - ESP/AH hdrsiz
2054 if (ipforward_rt.ro_rt != NULL) {
2055 struct secpolicy *sp = NULL;
2060 sp = ipsec_getpolicybyaddr(mcopy,
2066 destifp = ipforward_rt.ro_rt->rt_ifp;
2068 /* count IPsec header size */
2069 ipsechdr = ipsec4_hdrsiz(mcopy,
2074 * find the correct route for outer IPv4
2075 * header, compute tunnel MTU.
2078 * The "dummyifp" code relies upon the fact
2079 * that icmp_error() touches only ifp->if_mtu.
2083 if (sp->req != NULL &&
2084 sp->req->sav != NULL &&
2085 sp->req->sav->sah != NULL) {
2086 ro = &sp->req->sav->sah->sa_route;
2087 if (ro->ro_rt != NULL &&
2088 ro->ro_rt->rt_ifp != NULL) {
2090 ro->ro_rt->rt_ifp->if_mtu;
2091 dummyifp.if_mtu -= ipsechdr;
2092 destifp = &dummyifp;
2099 #else /* !IPSEC && !FAST_IPSEC */
2100 if (ipforward_rt.ro_rt != NULL)
2101 destifp = ipforward_rt.ro_rt->rt_ifp;
2103 ipstat.ips_cantfrag++;
2108 * A router should not generate ICMP_SOURCEQUENCH as
2109 * required in RFC1812 Requirements for IP Version 4 Routers.
2110 * Source quench could be a big problem under DoS attacks,
2111 * or if the underlying interface is rate-limited.
2112 * Those who need source quench packets may re-enable them
2113 * via the net.inet.ip.sendsourcequench sysctl.
2115 if (!ip_sendsourcequench) {
2119 type = ICMP_SOURCEQUENCH;
2124 case EACCES: /* ipfw denied packet */
2128 icmp_error(mcopy, type, code, dest, destifp);
2132 ip_savecontrol(struct inpcb *inp, struct mbuf **mp, struct ip *ip,
2135 if (inp->inp_socket->so_options & SO_TIMESTAMP) {
2139 *mp = sbcreatecontrol((caddr_t) &tv, sizeof(tv),
2140 SCM_TIMESTAMP, SOL_SOCKET);
2142 mp = &(*mp)->m_next;
2144 if (inp->inp_flags & INP_RECVDSTADDR) {
2145 *mp = sbcreatecontrol((caddr_t) &ip->ip_dst,
2146 sizeof(struct in_addr), IP_RECVDSTADDR, IPPROTO_IP);
2148 mp = &(*mp)->m_next;
2152 * Moving these out of udp_input() made them even more broken
2153 * than they already were.
2155 /* options were tossed already */
2156 if (inp->inp_flags & INP_RECVOPTS) {
2157 *mp = sbcreatecontrol((caddr_t) opts_deleted_above,
2158 sizeof(struct in_addr), IP_RECVOPTS, IPPROTO_IP);
2160 mp = &(*mp)->m_next;
2162 /* ip_srcroute doesn't do what we want here, need to fix */
2163 if (inp->inp_flags & INP_RECVRETOPTS) {
2164 *mp = sbcreatecontrol((caddr_t) ip_srcroute(),
2165 sizeof(struct in_addr), IP_RECVRETOPTS, IPPROTO_IP);
2167 mp = &(*mp)->m_next;
2170 if (inp->inp_flags & INP_RECVIF) {
2173 struct sockaddr_dl sdl;
2176 struct sockaddr_dl *sdp;
2177 struct sockaddr_dl *sdl2 = &sdlbuf.sdl;
2179 if (((ifp = m->m_pkthdr.rcvif)) &&
2180 ((ifp->if_index != 0) && (ifp->if_index <= if_index))) {
2181 sdp = (struct sockaddr_dl *)
2182 ifnet_addrs[ifp->if_index - 1]->ifa_addr;
2184 * Change our mind and don't try copy.
2186 if ((sdp->sdl_family != AF_LINK) ||
2187 (sdp->sdl_len > sizeof(sdlbuf))) {
2190 bcopy(sdp, sdl2, sdp->sdl_len);
2194 offsetof(struct sockaddr_dl, sdl_data[0]);
2195 sdl2->sdl_family = AF_LINK;
2196 sdl2->sdl_index = 0;
2197 sdl2->sdl_nlen = sdl2->sdl_alen = sdl2->sdl_slen = 0;
2199 *mp = sbcreatecontrol((caddr_t) sdl2, sdl2->sdl_len,
2200 IP_RECVIF, IPPROTO_IP);
2202 mp = &(*mp)->m_next;
2207 * XXX these routines are called from the upper part of the kernel.
2209 * They could also be moved to ip_mroute.c, since all the RSVP
2210 * handling is done there already.
2213 ip_rsvp_init(struct socket *so)
2215 if (so->so_type != SOCK_RAW ||
2216 so->so_proto->pr_protocol != IPPROTO_RSVP)
2219 if (ip_rsvpd != NULL)
2224 * This may seem silly, but we need to be sure we don't over-increment
2225 * the RSVP counter, in case something slips up.
2240 * This may seem silly, but we need to be sure we don't over-decrement
2241 * the RSVP counter, in case something slips up.
2251 rsvp_input(struct mbuf *m, ...) /* XXX must fixup manually */
2257 off = __va_arg(ap, int);
2258 proto = __va_arg(ap, int);
2261 if (rsvp_input_p) { /* call the real one if loaded */
2262 rsvp_input_p(m, off, proto);
2266 /* Can still get packets with rsvp_on = 0 if there is a local member
2267 * of the group to which the RSVP packet is addressed. But in this
2268 * case we want to throw the packet away.
2276 if (ip_rsvpd != NULL) {
2277 rip_input(m, off, proto);
2280 /* Drop the packet */