2 * Copyright (c) 2003, 2004 Jeffrey M. Hsu. All rights reserved.
3 * Copyright (c) 2003, 2004 The DragonFly Project. All rights reserved.
5 * This code is derived from software contributed to The DragonFly Project
8 * Redistribution and use in source and binary forms, with or without
9 * modification, are permitted provided that the following conditions
11 * 1. Redistributions of source code must retain the above copyright
12 * notice, this list of conditions and the following disclaimer.
13 * 2. Redistributions in binary form must reproduce the above copyright
14 * notice, this list of conditions and the following disclaimer in the
15 * documentation and/or other materials provided with the distribution.
16 * 3. Neither the name of The DragonFly Project nor the names of its
17 * contributors may be used to endorse or promote products derived
18 * from this software without specific, prior written permission.
20 * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS
21 * ``AS IS'' AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT
22 * LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS
23 * FOR A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE
24 * COPYRIGHT HOLDERS OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT,
25 * INCIDENTAL, SPECIAL, EXEMPLARY OR CONSEQUENTIAL DAMAGES (INCLUDING,
26 * BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES;
27 * LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED
28 * AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY,
29 * OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT
30 * OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF
35 * Copyright (c) 2003, 2004 Jeffrey M. Hsu. All rights reserved.
37 * License terms: all terms for the DragonFly license above plus the following:
39 * 4. All advertising materials mentioning features or use of this software
40 * must display the following acknowledgement:
42 * This product includes software developed by Jeffrey M. Hsu
43 * for the DragonFly Project.
45 * This requirement may be waived with permission from Jeffrey Hsu.
46 * This requirement will sunset and may be removed on July 8 2005,
47 * after which the standard DragonFly license (as shown above) will
52 * Copyright (c) 1982, 1986, 1988, 1993
53 * The Regents of the University of California. All rights reserved.
55 * Redistribution and use in source and binary forms, with or without
56 * modification, are permitted provided that the following conditions
58 * 1. Redistributions of source code must retain the above copyright
59 * notice, this list of conditions and the following disclaimer.
60 * 2. Redistributions in binary form must reproduce the above copyright
61 * notice, this list of conditions and the following disclaimer in the
62 * documentation and/or other materials provided with the distribution.
63 * 3. All advertising materials mentioning features or use of this software
64 * must display the following acknowledgement:
65 * This product includes software developed by the University of
66 * California, Berkeley and its contributors.
67 * 4. Neither the name of the University nor the names of its contributors
68 * may be used to endorse or promote products derived from this software
69 * without specific prior written permission.
71 * THIS SOFTWARE IS PROVIDED BY THE REGENTS AND CONTRIBUTORS ``AS IS'' AND
72 * ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
73 * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE
74 * ARE DISCLAIMED. IN NO EVENT SHALL THE REGENTS OR CONTRIBUTORS BE LIABLE
75 * FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL
76 * DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS
77 * OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION)
78 * HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT
79 * LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY
80 * OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF
83 * @(#)ip_input.c 8.2 (Berkeley) 1/4/94
84 * $FreeBSD: src/sys/netinet/ip_input.c,v 1.130.2.52 2003/03/07 07:01:28 silby Exp $
85 * $DragonFly: src/sys/netinet/ip_input.c,v 1.40 2004/12/21 02:54:15 hsu Exp $
90 #include "opt_bootp.h"
93 #include "opt_ipdivert.h"
94 #include "opt_ipfilter.h"
95 #include "opt_ipstealth.h"
96 #include "opt_ipsec.h"
97 #include "opt_random_ip_id.h"
99 #include <sys/param.h>
100 #include <sys/systm.h>
101 #include <sys/mbuf.h>
102 #include <sys/malloc.h>
103 #include <sys/mpipe.h>
104 #include <sys/domain.h>
105 #include <sys/protosw.h>
106 #include <sys/socket.h>
107 #include <sys/time.h>
108 #include <sys/globaldata.h>
109 #include <sys/thread.h>
110 #include <sys/kernel.h>
111 #include <sys/syslog.h>
112 #include <sys/sysctl.h>
113 #include <sys/in_cksum.h>
115 #include <sys/thread2.h>
116 #include <sys/msgport2.h>
118 #include <machine/stdarg.h>
121 #include <net/if_types.h>
122 #include <net/if_var.h>
123 #include <net/if_dl.h>
124 #include <net/pfil.h>
125 #include <net/route.h>
126 #include <net/netisr.h>
127 #include <net/intrq.h>
129 #include <netinet/in.h>
130 #include <netinet/in_systm.h>
131 #include <netinet/in_var.h>
132 #include <netinet/ip.h>
133 #include <netinet/in_pcb.h>
134 #include <netinet/ip_var.h>
135 #include <netinet/ip_icmp.h>
138 #include <sys/socketvar.h>
140 #include <net/ipfw/ip_fw.h>
141 #include <net/dummynet/ip_dummynet.h>
144 #include <netinet6/ipsec.h>
145 #include <netproto/key/key.h>
149 #include <netproto/ipsec/ipsec.h>
150 #include <netproto/ipsec/key.h>
154 static int ip_rsvp_on;
155 struct socket *ip_rsvpd;
157 int ipforwarding = 0;
158 SYSCTL_INT(_net_inet_ip, IPCTL_FORWARDING, forwarding, CTLFLAG_RW,
159 &ipforwarding, 0, "Enable IP forwarding between interfaces");
161 static int ipsendredirects = 1; /* XXX */
162 SYSCTL_INT(_net_inet_ip, IPCTL_SENDREDIRECTS, redirect, CTLFLAG_RW,
163 &ipsendredirects, 0, "Enable sending IP redirects");
165 int ip_defttl = IPDEFTTL;
166 SYSCTL_INT(_net_inet_ip, IPCTL_DEFTTL, ttl, CTLFLAG_RW,
167 &ip_defttl, 0, "Maximum TTL on IP packets");
169 static int ip_dosourceroute = 0;
170 SYSCTL_INT(_net_inet_ip, IPCTL_SOURCEROUTE, sourceroute, CTLFLAG_RW,
171 &ip_dosourceroute, 0, "Enable forwarding source routed IP packets");
173 static int ip_acceptsourceroute = 0;
174 SYSCTL_INT(_net_inet_ip, IPCTL_ACCEPTSOURCEROUTE, accept_sourceroute,
175 CTLFLAG_RW, &ip_acceptsourceroute, 0,
176 "Enable accepting source routed IP packets");
178 static int ip_keepfaith = 0;
179 SYSCTL_INT(_net_inet_ip, IPCTL_KEEPFAITH, keepfaith, CTLFLAG_RW,
181 "Enable packet capture for FAITH IPv4->IPv6 translater daemon");
183 static int nipq = 0; /* total # of reass queues */
185 SYSCTL_INT(_net_inet_ip, OID_AUTO, maxfragpackets, CTLFLAG_RW,
187 "Maximum number of IPv4 fragment reassembly queue entries");
189 static int maxfragsperpacket;
190 SYSCTL_INT(_net_inet_ip, OID_AUTO, maxfragsperpacket, CTLFLAG_RW,
191 &maxfragsperpacket, 0,
192 "Maximum number of IPv4 fragments allowed per packet");
194 static int ip_sendsourcequench = 0;
195 SYSCTL_INT(_net_inet_ip, OID_AUTO, sendsourcequench, CTLFLAG_RW,
196 &ip_sendsourcequench, 0,
197 "Enable the transmission of source quench packets");
200 * XXX - Setting ip_checkinterface mostly implements the receive side of
201 * the Strong ES model described in RFC 1122, but since the routing table
202 * and transmit implementation do not implement the Strong ES model,
203 * setting this to 1 results in an odd hybrid.
205 * XXX - ip_checkinterface currently must be disabled if you use ipnat
206 * to translate the destination address to another local interface.
208 * XXX - ip_checkinterface must be disabled if you add IP aliases
209 * to the loopback interface instead of the interface where the
210 * packets for those addresses are received.
212 static int ip_checkinterface = 0;
213 SYSCTL_INT(_net_inet_ip, OID_AUTO, check_interface, CTLFLAG_RW,
214 &ip_checkinterface, 0, "Verify packet arrives on correct interface");
217 static int ipprintfs = 0;
220 static struct ifqueue ipintrq;
221 static int ipqmaxlen = IFQ_MAXLEN;
223 extern struct domain inetdomain;
224 extern struct protosw inetsw[];
225 u_char ip_protox[IPPROTO_MAX];
226 struct in_ifaddrhead in_ifaddrhead; /* first inet address */
227 struct in_ifaddrhashhead *in_ifaddrhashtbl; /* inet addr hash table */
228 u_long in_ifaddrhmask; /* mask for hash table */
230 SYSCTL_INT(_net_inet_ip, IPCTL_INTRQMAXLEN, intr_queue_maxlen, CTLFLAG_RW,
231 &ipintrq.ifq_maxlen, 0, "Maximum size of the IP input queue");
232 SYSCTL_INT(_net_inet_ip, IPCTL_INTRQDROPS, intr_queue_drops, CTLFLAG_RD,
233 &ipintrq.ifq_drops, 0, "Number of packets dropped from the IP input queue");
235 struct ip_stats ipstats_ary[MAXCPU];
238 sysctl_ipstats(SYSCTL_HANDLER_ARGS)
242 for (cpu = 0; cpu < ncpus; ++cpu) {
243 if ((error = SYSCTL_OUT(req, &ipstats_ary[cpu],
244 sizeof(struct ip_stats))))
246 if ((error = SYSCTL_IN(req, &ipstats_ary[cpu],
247 sizeof(struct ip_stats))))
253 SYSCTL_PROC(_net_inet_ip, IPCTL_STATS, stats, (CTLTYPE_OPAQUE | CTLFLAG_RW),
254 0, 0, sysctl_ipstats, "S,ip_stats", "IP statistics");
256 SYSCTL_STRUCT(_net_inet_ip, IPCTL_STATS, stats, CTLFLAG_RW,
257 &ipstat, ip_stats, "IP statistics");
260 /* Packet reassembly stuff */
261 #define IPREASS_NHASH_LOG2 6
262 #define IPREASS_NHASH (1 << IPREASS_NHASH_LOG2)
263 #define IPREASS_HMASK (IPREASS_NHASH - 1)
264 #define IPREASS_HASH(x,y) \
265 (((((x) & 0xF) | ((((x) >> 8) & 0xF) << 4)) ^ (y)) & IPREASS_HMASK)
267 static struct ipq ipq[IPREASS_NHASH];
268 const int ipintrq_present = 1;
271 SYSCTL_INT(_net_inet_ip, IPCTL_DEFMTU, mtu, CTLFLAG_RW,
272 &ip_mtu, 0, "Default MTU");
276 static int ipstealth = 0;
277 SYSCTL_INT(_net_inet_ip, OID_AUTO, stealth, CTLFLAG_RW, &ipstealth, 0, "");
279 static const int ipstealth = 0;
284 ip_fw_chk_t *ip_fw_chk_ptr;
289 ip_dn_io_t *ip_dn_io_ptr;
291 struct pfil_head inet_pfil_hook;
294 * XXX this is ugly -- the following two global variables are
295 * used to store packet state while it travels through the stack.
296 * Note that the code even makes assumptions on the size and
297 * alignment of fields inside struct ip_srcrt so e.g. adding some
298 * fields will break the code. This needs to be fixed.
300 * We need to save the IP options in case a protocol wants to respond
301 * to an incoming packet over the same route if the packet got here
302 * using IP source routing. This allows connection establishment and
303 * maintenance when the remote end is on a network that is not known
306 static int ip_nhops = 0;
308 static struct ip_srcrt {
309 struct in_addr dst; /* final destination */
310 char nop; /* one NOP to align */
311 char srcopt[IPOPT_OFFSET + 1]; /* OPTVAL, OLEN and OFFSET */
312 struct in_addr route[MAX_IPOPTLEN/sizeof(struct in_addr)];
315 static MALLOC_DEFINE(M_IPQ, "ipq", "IP Fragment Management");
316 static struct malloc_pipe ipq_mpipe;
318 static void save_rte (u_char *, struct in_addr);
319 static int ip_dooptions (struct mbuf *m, int,
320 struct sockaddr_in *next_hop);
321 static void ip_forward (struct mbuf *m, int srcrt,
322 struct sockaddr_in *next_hop);
323 static void ip_freef (struct ipq *);
324 static int ip_input_handler (struct netmsg *);
325 static struct mbuf *ip_reass (struct mbuf *, struct ipq *,
326 struct ipq *, u_int32_t *, u_int16_t *);
329 * IP initialization: fill in IP protocol switch table.
330 * All protocols not implemented in kernel go to raw IP protocol handler.
342 * Make sure we can handle a reasonable number of fragments but
343 * cap it at 4000 (XXX).
345 mpipe_init(&ipq_mpipe, M_IPQ, sizeof(struct ipq),
346 IFQ_MAXLEN, 4000, 0, NULL);
347 TAILQ_INIT(&in_ifaddrhead);
348 in_ifaddrhashtbl = hashinit(INADDR_NHASH, M_IFADDR, &in_ifaddrhmask);
349 pr = pffindproto(PF_INET, IPPROTO_RAW, SOCK_RAW);
352 for (i = 0; i < IPPROTO_MAX; i++)
353 ip_protox[i] = pr - inetsw;
354 for (pr = inetdomain.dom_protosw;
355 pr < inetdomain.dom_protoswNPROTOSW; pr++)
356 if (pr->pr_domain->dom_family == PF_INET &&
357 pr->pr_protocol && pr->pr_protocol != IPPROTO_RAW)
358 ip_protox[pr->pr_protocol] = pr - inetsw;
360 inet_pfil_hook.ph_type = PFIL_TYPE_AF;
361 inet_pfil_hook.ph_af = AF_INET;
362 if ((i = pfil_head_register(&inet_pfil_hook)) != 0) {
363 printf("%s: WARNING: unable to register pfil hook, "
364 "error %d\n", __func__, i);
367 for (i = 0; i < IPREASS_NHASH; i++)
368 ipq[i].next = ipq[i].prev = &ipq[i];
370 maxnipq = nmbclusters / 32;
371 maxfragsperpacket = 16;
374 ip_id = time_second & 0xffff;
376 ipintrq.ifq_maxlen = ipqmaxlen;
379 * Initialize IP statistics.
381 * It is layed out as an array which is has one element for UP,
382 * and SMP_MAXCPU elements for SMP. This allows us to retain
383 * the access mechanism from userland for both UP and SMP.
386 for (cpu = 0; cpu < ncpus; ++cpu) {
387 bzero(&ipstats_ary[cpu], sizeof(struct ip_stats));
390 bzero(&ipstat, sizeof(struct ip_stats));
393 netisr_register(NETISR_IP, ip_mport, ip_input_handler);
397 * XXX watch out this one. It is perhaps used as a cache for
398 * the most recently used route ? it is cleared in in_addroute()
399 * when a new route is successfully created.
401 struct route ipforward_rt;
402 static struct sockaddr_in ipaddr = { sizeof(ipaddr), AF_INET };
404 /* Do transport protocol processing. */
406 transport_processing_oncpu(struct mbuf *m, int hlen, struct ip *ip,
407 struct sockaddr_in *nexthop)
410 * Switch out to protocol's input routine.
412 if (nexthop && ip->ip_p == IPPROTO_TCP) {
413 /* TCP needs IPFORWARD info if available */
416 tag.mh_type = MT_TAG;
417 tag.mh_flags = PACKET_TAG_IPFORWARD;
418 tag.mh_data = (caddr_t)nexthop;
421 (*inetsw[ip_protox[ip->ip_p]].pr_input)
422 ((struct mbuf *)&tag, hlen, ip->ip_p);
424 (*inetsw[ip_protox[ip->ip_p]].pr_input)(m, hlen, ip->ip_p);
428 struct netmsg_transport_packet {
429 struct lwkt_msg nm_lmsg;
430 struct mbuf *nm_mbuf;
432 boolean_t nm_hasnexthop;
433 struct sockaddr_in nm_nexthop;
437 transport_processing_handler(lwkt_msg_t lmsg)
439 struct netmsg_transport_packet *msg = (void *)lmsg;
440 struct sockaddr_in *nexthop;
443 ip = mtod(msg->nm_mbuf, struct ip *);
444 nexthop = msg->nm_hasnexthop ? &msg->nm_nexthop : NULL;
445 transport_processing_oncpu(msg->nm_mbuf, msg->nm_hlen, ip, nexthop);
446 lwkt_replymsg(lmsg, 0);
451 ip_input_handler(struct netmsg *msg0)
453 struct mbuf *m = ((struct netmsg_packet *)msg0)->nm_packet;
456 lwkt_replymsg(&msg0->nm_lmsg, 0);
461 * Ip input routine. Checksum and byte swap header. If fragmented
462 * try to reassemble. Process options. Pass to next level.
465 ip_input(struct mbuf *m)
469 struct in_ifaddr *ia = NULL;
471 int i, hlen, checkif;
473 struct in_addr pkt_dst;
474 u_int32_t divert_info = 0; /* packet divert/tee info */
475 struct ip_fw_args args;
476 boolean_t using_srcrt = FALSE; /* forward (by PFIL_HOOKS) */
477 boolean_t needredispatch = FALSE;
478 struct in_addr odst; /* original dst address(NAT) */
481 struct tdb_ident *tdbi;
482 struct secpolicy *sp;
489 args.divert_rule = 0; /* divert cookie */
490 args.next_hop = NULL;
492 /* Grab info from MT_TAG mbufs prepended to the chain. */
493 for (; m && m->m_type == MT_TAG; m = m->m_next) {
494 switch(m->_m_tag_id) {
496 printf("ip_input: unrecognised MT_TAG tag %d\n",
500 case PACKET_TAG_DUMMYNET:
501 args.rule = ((struct dn_pkt *)m)->rule;
504 case PACKET_TAG_DIVERT:
505 args.divert_rule = (int)m->m_hdr.mh_data & 0xffff;
508 case PACKET_TAG_IPFORWARD:
509 args.next_hop = (struct sockaddr_in *)m->m_hdr.mh_data;
514 KASSERT(m != NULL && (m->m_flags & M_PKTHDR) != 0,
515 ("ip_input: no HDR"));
517 if (args.rule) { /* dummynet already filtered us */
518 ip = mtod(m, struct ip *);
519 hlen = IP_VHL_HL(ip->ip_vhl) << 2;
525 /* length checks already done in ip_demux() */
526 KASSERT(m->m_len >= sizeof(ip), ("IP header not in one mbuf"));
528 ip = mtod(m, struct ip *);
530 if (IP_VHL_V(ip->ip_vhl) != IPVERSION) {
531 ipstat.ips_badvers++;
535 hlen = IP_VHL_HL(ip->ip_vhl) << 2;
536 /* length checks already done in ip_demux() */
537 KASSERT(hlen >= sizeof(struct ip), ("IP header len too small"));
538 KASSERT(m->m_len >= hlen, ("packet shorter than IP header length"));
540 /* 127/8 must not appear on wire - RFC1122 */
541 if ((ntohl(ip->ip_dst.s_addr) >> IN_CLASSA_NSHIFT) == IN_LOOPBACKNET ||
542 (ntohl(ip->ip_src.s_addr) >> IN_CLASSA_NSHIFT) == IN_LOOPBACKNET) {
543 if (!(m->m_pkthdr.rcvif->if_flags & IFF_LOOPBACK)) {
544 ipstat.ips_badaddr++;
549 if (m->m_pkthdr.csum_flags & CSUM_IP_CHECKED) {
550 sum = !(m->m_pkthdr.csum_flags & CSUM_IP_VALID);
552 if (hlen == sizeof(struct ip)) {
553 sum = in_cksum_hdr(ip);
555 sum = in_cksum(m, hlen);
564 * Convert fields to host representation.
566 ip->ip_len = ntohs(ip->ip_len);
567 if (ip->ip_len < hlen) {
571 ip->ip_off = ntohs(ip->ip_off);
574 * Check that the amount of data in the buffers
575 * is as at least much as the IP header would have us expect.
576 * Trim mbufs if longer than we expect.
577 * Drop packet if shorter than we expect.
579 if (m->m_pkthdr.len < ip->ip_len) {
580 ipstat.ips_tooshort++;
583 if (m->m_pkthdr.len > ip->ip_len) {
584 if (m->m_len == m->m_pkthdr.len) {
585 m->m_len = ip->ip_len;
586 m->m_pkthdr.len = ip->ip_len;
588 m_adj(m, ip->ip_len - m->m_pkthdr.len);
590 #if defined(IPSEC) && !defined(IPSEC_FILTERGIF)
592 * Bypass packet filtering for packets from a tunnel (gif).
594 if (ipsec_gethist(m, NULL))
600 * Right now when no processing on packet has done
601 * and it is still fresh out of network we do our black
603 * - Firewall: deny/allow/divert
604 * - Xlate: translate packet's addr/port (NAT).
605 * - Pipe: pass pkt through dummynet.
606 * - Wrap: fake packet's addr/port <unimpl.>
607 * - Encapsulate: put it in another IP and send out. <unimp.>
613 * Run through list of hooks for input packets.
615 * NB: Beware of the destination address changing (e.g.
616 * by NAT rewriting). When this happens, tell
617 * ip_forward to do the right thing.
619 if (pfil_has_hooks(&inet_pfil_hook)) {
621 if (pfil_run_hooks(&inet_pfil_hook, &m,
622 m->m_pkthdr.rcvif, PFIL_IN)) {
625 if (m == NULL) /* consumed by filter */
627 ip = mtod(m, struct ip *);
628 using_srcrt = (odst.s_addr != ip->ip_dst.s_addr);
631 if (fw_enable && IPFW_LOADED) {
633 * If we've been forwarded from the output side, then
634 * skip the firewall a second time
640 i = ip_fw_chk_ptr(&args);
643 if ( (i & IP_FW_PORT_DENY_FLAG) || m == NULL) { /* drop */
648 ip = mtod(m, struct ip *); /* just in case m changed */
649 if (i == 0 && args.next_hop == NULL) /* common case */
651 if (DUMMYNET_LOADED && (i & IP_FW_PORT_DYNT_FLAG)) {
652 /* Send packet to the appropriate pipe */
653 ip_dn_io_ptr(m, i&0xffff, DN_TO_IP_IN, &args);
657 if (i != 0 && !(i & IP_FW_PORT_DYNT_FLAG)) {
658 /* Divert or tee packet */
663 if (i == 0 && args.next_hop != NULL)
666 * if we get here, the packet must be dropped
674 * Process options and, if not destined for us,
675 * ship it on. ip_dooptions returns 1 when an
676 * error was detected (causing an icmp message
677 * to be sent and the original packet to be freed).
679 ip_nhops = 0; /* for source routed packets */
680 if (hlen > sizeof(struct ip) && ip_dooptions(m, 0, args.next_hop))
683 /* greedy RSVP, snatches any PATH packet of the RSVP protocol and no
684 * matter if it is destined to another node, or whether it is
685 * a multicast one, RSVP wants it! and prevents it from being forwarded
686 * anywhere else. Also checks if the rsvp daemon is running before
687 * grabbing the packet.
689 if (rsvp_on && ip->ip_p == IPPROTO_RSVP)
693 * Check our list of addresses, to see if the packet is for us.
694 * If we don't have any addresses, assume any unicast packet
695 * we receive might be for us (and let the upper layers deal
698 if (TAILQ_EMPTY(&in_ifaddrhead) && !(m->m_flags & (M_MCAST | M_BCAST)))
702 * Cache the destination address of the packet; this may be
703 * changed by use of 'ipfw fwd'.
705 pkt_dst = args.next_hop ? args.next_hop->sin_addr : ip->ip_dst;
708 * Enable a consistency check between the destination address
709 * and the arrival interface for a unicast packet (the RFC 1122
710 * strong ES model) if IP forwarding is disabled and the packet
711 * is not locally generated and the packet is not subject to
714 * XXX - Checking also should be disabled if the destination
715 * address is ipnat'ed to a different interface.
717 * XXX - Checking is incompatible with IP aliases added
718 * to the loopback interface instead of the interface where
719 * the packets are received.
721 checkif = ip_checkinterface &&
723 m->m_pkthdr.rcvif != NULL &&
724 !(m->m_pkthdr.rcvif->if_flags & IFF_LOOPBACK) &&
725 (args.next_hop == NULL);
728 * Check for exact addresses in the hash bucket.
730 LIST_FOREACH(ia, INADDR_HASH(pkt_dst.s_addr), ia_hash) {
732 * If the address matches, verify that the packet
733 * arrived via the correct interface if checking is
736 if (IA_SIN(ia)->sin_addr.s_addr == pkt_dst.s_addr &&
737 (!checkif || ia->ia_ifp == m->m_pkthdr.rcvif))
741 * Check for broadcast addresses.
743 * Only accept broadcast packets that arrive via the matching
744 * interface. Reception of forwarded directed broadcasts would
745 * be handled via ip_forward() and ether_output() with the loopback
746 * into the stack for SIMPLEX interfaces handled by ether_output().
748 if (m->m_pkthdr.rcvif->if_flags & IFF_BROADCAST) {
749 TAILQ_FOREACH(ifa, &m->m_pkthdr.rcvif->if_addrhead, ifa_link) {
750 if (ifa->ifa_addr == NULL) /* shutdown/startup race */
752 if (ifa->ifa_addr->sa_family != AF_INET)
755 if (satosin(&ia->ia_broadaddr)->sin_addr.s_addr ==
758 if (ia->ia_netbroadcast.s_addr == pkt_dst.s_addr)
761 if (IA_SIN(ia)->sin_addr.s_addr == INADDR_ANY)
766 if (IN_MULTICAST(ntohl(ip->ip_dst.s_addr))) {
767 struct in_multi *inm;
770 * If we are acting as a multicast router, all
771 * incoming multicast packets are passed to the
772 * kernel-level multicast forwarding function.
773 * The packet is returned (relatively) intact; if
774 * ip_mforward() returns a non-zero value, the packet
775 * must be discarded, else it may be accepted below.
778 ip_mforward(ip, m->m_pkthdr.rcvif, m, NULL) != 0) {
779 ipstat.ips_cantforward++;
785 * The process-level routing daemon needs to receive
786 * all multicast IGMP packets, whether or not this
787 * host belongs to their destination groups.
789 if (ip->ip_p == IPPROTO_IGMP)
791 ipstat.ips_forward++;
794 * See if we belong to the destination multicast group on the
797 IN_LOOKUP_MULTI(ip->ip_dst, m->m_pkthdr.rcvif, inm);
799 ipstat.ips_notmember++;
805 if (ip->ip_dst.s_addr == INADDR_BROADCAST)
807 if (ip->ip_dst.s_addr == INADDR_ANY)
811 * FAITH(Firewall Aided Internet Translator)
813 if (m->m_pkthdr.rcvif && m->m_pkthdr.rcvif->if_type == IFT_FAITH) {
815 if (ip->ip_p == IPPROTO_TCP || ip->ip_p == IPPROTO_ICMP)
823 * Not for us; forward if possible and desirable.
826 ipstat.ips_cantforward++;
831 * Enforce inbound IPsec SPD.
833 if (ipsec4_in_reject(m, NULL)) {
834 ipsecstat.in_polvio++;
839 mtag = m_tag_find(m, PACKET_TAG_IPSEC_IN_DONE, NULL);
842 tdbi = (struct tdb_ident *)(mtag + 1);
843 sp = ipsec_getpolicy(tdbi, IPSEC_DIR_INBOUND);
845 sp = ipsec_getpolicybyaddr(m, IPSEC_DIR_INBOUND,
846 IP_FORWARDING, &error);
848 if (sp == NULL) { /* NB: can happen if error */
850 /*XXX error stat???*/
851 DPRINTF(("ip_input: no SP for forwarding\n")); /*XXX*/
856 * Check security policy against packet attributes.
858 error = ipsec_in_reject(sp, m);
862 ipstat.ips_cantforward++;
866 ip_forward(m, using_srcrt, args.next_hop);
873 * IPSTEALTH: Process non-routing options only
874 * if the packet is destined for us.
877 hlen > sizeof(struct ip) &&
878 ip_dooptions(m, 1, args.next_hop))
881 /* Count the packet in the ip address stats */
883 ia->ia_ifa.if_ipackets++;
884 ia->ia_ifa.if_ibytes += m->m_pkthdr.len;
888 * If offset or IP_MF are set, must reassemble.
889 * Otherwise, nothing need be done.
890 * (We could look in the reassembly queue to see
891 * if the packet was previously fragmented,
892 * but it's not worth the time; just let them time out.)
894 if (ip->ip_off & (IP_MF | IP_OFFMASK)) {
896 /* If maxnipq is 0, never accept fragments. */
898 ipstat.ips_fragments++;
899 ipstat.ips_fragdropped++;
903 sum = IPREASS_HASH(ip->ip_src.s_addr, ip->ip_id);
905 * Look for queue of fragments
908 for (fp = ipq[sum].next; fp != &ipq[sum]; fp = fp->next)
909 if (ip->ip_id == fp->ipq_id &&
910 ip->ip_src.s_addr == fp->ipq_src.s_addr &&
911 ip->ip_dst.s_addr == fp->ipq_dst.s_addr &&
912 ip->ip_p == fp->ipq_p)
918 * Enforce upper bound on number of fragmented packets
919 * for which we attempt reassembly;
920 * If maxnipq is -1, accept all fragments without limitation.
922 if ((nipq > maxnipq) && (maxnipq > 0)) {
924 * drop something from the tail of the current queue
925 * before proceeding further
927 if (ipq[sum].prev == &ipq[sum]) { /* gak */
928 for (i = 0; i < IPREASS_NHASH; i++) {
929 if (ipq[i].prev != &ipq[i]) {
930 ipstat.ips_fragtimeout +=
931 ipq[i].prev->ipq_nfrags;
932 ip_freef(ipq[i].prev);
937 ipstat.ips_fragtimeout +=
938 ipq[sum].prev->ipq_nfrags;
939 ip_freef(ipq[sum].prev);
944 * Adjust ip_len to not reflect header,
945 * convert offset of this to bytes.
948 if (ip->ip_off & IP_MF) {
950 * Make sure that fragments have a data length
951 * that's a non-zero multiple of 8 bytes.
953 if (ip->ip_len == 0 || (ip->ip_len & 0x7) != 0) {
954 ipstat.ips_toosmall++; /* XXX */
957 m->m_flags |= M_FRAG;
959 m->m_flags &= ~M_FRAG;
963 * Attempt reassembly; if it succeeds, proceed.
964 * ip_reass() will return a different mbuf, and update
965 * the divert info in divert_info and args.divert_rule.
967 ipstat.ips_fragments++;
968 m->m_pkthdr.header = ip;
969 m = ip_reass(m, fp, &ipq[sum], &divert_info, &args.divert_rule);
972 ipstat.ips_reassembled++;
973 needredispatch = TRUE;
974 ip = mtod(m, struct ip *);
975 /* Get the header length of the reassembled packet */
976 hlen = IP_VHL_HL(ip->ip_vhl) << 2;
978 /* Restore original checksum before diverting packet */
979 if (divert_info != 0) {
981 ip->ip_len = htons(ip->ip_len);
982 ip->ip_off = htons(ip->ip_off);
984 if (hlen == sizeof(struct ip))
985 ip->ip_sum = in_cksum_hdr(ip);
987 ip->ip_sum = in_cksum(m, hlen);
988 ip->ip_off = ntohs(ip->ip_off);
989 ip->ip_len = ntohs(ip->ip_len);
999 * Divert or tee packet to the divert protocol if required.
1001 if (divert_info != 0) {
1002 struct mbuf *clone = NULL;
1004 /* Clone packet if we're doing a 'tee' */
1005 if ((divert_info & IP_FW_PORT_TEE_FLAG) != 0)
1006 clone = m_dup(m, MB_DONTWAIT);
1008 /* Restore packet header fields to original values */
1010 ip->ip_len = htons(ip->ip_len);
1011 ip->ip_off = htons(ip->ip_off);
1013 /* Deliver packet to divert input routine */
1014 divert_packet(m, 1, divert_info & 0xffff, args.divert_rule);
1015 ipstat.ips_delivered++;
1017 /* If 'tee', continue with original packet */
1021 ip = mtod(m, struct ip *);
1024 * Jump backwards to complete processing of the
1025 * packet. But first clear divert_info to avoid
1026 * entering this block again.
1027 * We do not need to clear args.divert_rule
1028 * or args.next_hop as they will not be used.
1037 * enforce IPsec policy checking if we are seeing last header.
1038 * note that we do not visit this with protocols with pcb layer
1039 * code - like udp/tcp/raw ip.
1041 if ((inetsw[ip_protox[ip->ip_p]].pr_flags & PR_LASTHDR) &&
1042 ipsec4_in_reject(m, NULL)) {
1043 ipsecstat.in_polvio++;
1049 * enforce IPsec policy checking if we are seeing last header.
1050 * note that we do not visit this with protocols with pcb layer
1051 * code - like udp/tcp/raw ip.
1053 if (inetsw[ip_protox[ip->ip_p]].pr_flags & PR_LASTHDR) {
1055 * Check if the packet has already had IPsec processing
1056 * done. If so, then just pass it along. This tag gets
1057 * set during AH, ESP, etc. input handling, before the
1058 * packet is returned to the ip input queue for delivery.
1060 mtag = m_tag_find(m, PACKET_TAG_IPSEC_IN_DONE, NULL);
1063 tdbi = (struct tdb_ident *)(mtag + 1);
1064 sp = ipsec_getpolicy(tdbi, IPSEC_DIR_INBOUND);
1066 sp = ipsec_getpolicybyaddr(m, IPSEC_DIR_INBOUND,
1067 IP_FORWARDING, &error);
1071 * Check security policy against packet attributes.
1073 error = ipsec_in_reject(sp, m);
1076 /* XXX error stat??? */
1078 DPRINTF(("ip_input: no SP, packet discarded\n"));/*XXX*/
1085 #endif /* FAST_IPSEC */
1087 ipstat.ips_delivered++;
1088 if (needredispatch) {
1089 struct netmsg_transport_packet *msg;
1092 msg = malloc(sizeof(struct netmsg_transport_packet),
1093 M_LWKTMSG, M_INTWAIT | M_NULLOK);
1097 lwkt_initmsg(&msg->nm_lmsg, &netisr_afree_rport, 0,
1098 lwkt_cmd_func(transport_processing_handler),
1100 msg->nm_hlen = hlen;
1101 msg->nm_hasnexthop = (args.next_hop != NULL);
1102 if (msg->nm_hasnexthop)
1103 msg->nm_nexthop = *args.next_hop; /* structure copy */
1105 ip->ip_off = htons(ip->ip_off);
1106 ip->ip_len = htons(ip->ip_len);
1107 port = ip_mport(&m);
1110 ip = mtod(m, struct ip *);
1111 ip->ip_len = ntohs(ip->ip_len);
1112 ip->ip_off = ntohs(ip->ip_off);
1113 lwkt_sendmsg(port, &msg->nm_lmsg);
1116 transport_processing_oncpu(m, hlen, ip, args.next_hop);
1125 * Take incoming datagram fragment and try to reassemble it into
1126 * whole datagram. If a chain for reassembly of this datagram already
1127 * exists, then it is given as fp; otherwise have to make a chain.
1129 * When IPDIVERT enabled, keep additional state with each packet that
1130 * tells us if we need to divert or tee the packet we're building.
1131 * In particular, *divinfo includes the port and TEE flag,
1132 * *divert_rule is the number of the matching rule.
1135 static struct mbuf *
1136 ip_reass(struct mbuf *m, struct ipq *fp, struct ipq *where,
1137 u_int32_t *divinfo, u_int16_t *divert_rule)
1139 struct ip *ip = mtod(m, struct ip *);
1140 struct mbuf *p = NULL, *q, *nq;
1142 int hlen = IP_VHL_HL(ip->ip_vhl) << 2;
1146 * Presence of header sizes in mbufs
1147 * would confuse code below.
1153 * If first fragment to arrive, create a reassembly queue.
1156 if ((fp = mpipe_alloc_nowait(&ipq_mpipe)) == NULL)
1161 fp->ipq_ttl = IPFRAGTTL;
1162 fp->ipq_p = ip->ip_p;
1163 fp->ipq_id = ip->ip_id;
1164 fp->ipq_src = ip->ip_src;
1165 fp->ipq_dst = ip->ip_dst;
1167 m->m_nextpkt = NULL;
1169 fp->ipq_div_info = 0;
1170 fp->ipq_div_cookie = 0;
1177 #define GETIP(m) ((struct ip*)((m)->m_pkthdr.header))
1180 * Find a segment which begins after this one does.
1182 for (p = NULL, q = fp->ipq_frags; q; p = q, q = q->m_nextpkt)
1183 if (GETIP(q)->ip_off > ip->ip_off)
1187 * If there is a preceding segment, it may provide some of
1188 * our data already. If so, drop the data from the incoming
1189 * segment. If it provides all of our data, drop us, otherwise
1190 * stick new segment in the proper place.
1192 * If some of the data is dropped from the the preceding
1193 * segment, then it's checksum is invalidated.
1196 i = GETIP(p)->ip_off + GETIP(p)->ip_len - ip->ip_off;
1198 if (i >= ip->ip_len)
1201 m->m_pkthdr.csum_flags = 0;
1205 m->m_nextpkt = p->m_nextpkt;
1208 m->m_nextpkt = fp->ipq_frags;
1213 * While we overlap succeeding segments trim them or,
1214 * if they are completely covered, dequeue them.
1216 for (; q != NULL && ip->ip_off + ip->ip_len > GETIP(q)->ip_off;
1218 i = (ip->ip_off + ip->ip_len) - GETIP(q)->ip_off;
1219 if (i < GETIP(q)->ip_len) {
1220 GETIP(q)->ip_len -= i;
1221 GETIP(q)->ip_off += i;
1223 q->m_pkthdr.csum_flags = 0;
1228 ipstat.ips_fragdropped++;
1237 * Transfer firewall instructions to the fragment structure.
1238 * Only trust info in the fragment at offset 0.
1240 if (ip->ip_off == 0) {
1241 fp->ipq_div_info = *divinfo;
1242 fp->ipq_div_cookie = *divert_rule;
1249 * Check for complete reassembly and perform frag per packet
1252 * Frag limiting is performed here so that the nth frag has
1253 * a chance to complete the packet before we drop the packet.
1254 * As a result, n+1 frags are actually allowed per packet, but
1255 * only n will ever be stored. (n = maxfragsperpacket.)
1259 for (p = NULL, q = fp->ipq_frags; q; p = q, q = q->m_nextpkt) {
1260 if (GETIP(q)->ip_off != next) {
1261 if (fp->ipq_nfrags > maxfragsperpacket) {
1262 ipstat.ips_fragdropped += fp->ipq_nfrags;
1267 next += GETIP(q)->ip_len;
1269 /* Make sure the last packet didn't have the IP_MF flag */
1270 if (p->m_flags & M_FRAG) {
1271 if (fp->ipq_nfrags > maxfragsperpacket) {
1272 ipstat.ips_fragdropped += fp->ipq_nfrags;
1279 * Reassembly is complete. Make sure the packet is a sane size.
1283 if (next + (IP_VHL_HL(ip->ip_vhl) << 2) > IP_MAXPACKET) {
1284 ipstat.ips_toolong++;
1285 ipstat.ips_fragdropped += fp->ipq_nfrags;
1291 * Concatenate fragments.
1298 q->m_nextpkt = NULL;
1299 for (q = nq; q != NULL; q = nq) {
1301 q->m_nextpkt = NULL;
1302 m->m_pkthdr.csum_flags &= q->m_pkthdr.csum_flags;
1303 m->m_pkthdr.csum_data += q->m_pkthdr.csum_data;
1309 * Extract firewall instructions from the fragment structure.
1311 *divinfo = fp->ipq_div_info;
1312 *divert_rule = fp->ipq_div_cookie;
1316 * Create header for new ip packet by
1317 * modifying header of first packet;
1318 * dequeue and discard fragment reassembly header.
1319 * Make header visible.
1322 ip->ip_src = fp->ipq_src;
1323 ip->ip_dst = fp->ipq_dst;
1326 mpipe_free(&ipq_mpipe, fp);
1327 m->m_len += (IP_VHL_HL(ip->ip_vhl) << 2);
1328 m->m_data -= (IP_VHL_HL(ip->ip_vhl) << 2);
1329 /* some debugging cruft by sklower, below, will go away soon */
1330 if (m->m_flags & M_PKTHDR) { /* XXX this should be done elsewhere */
1333 for (n = m; n; n = n->m_next)
1335 m->m_pkthdr.len = plen;
1344 ipstat.ips_fragdropped++;
1354 * Free a fragment reassembly header and all
1355 * associated datagrams.
1358 ip_freef(struct ipq *fp)
1362 while (fp->ipq_frags) {
1364 fp->ipq_frags = q->m_nextpkt;
1368 mpipe_free(&ipq_mpipe, fp);
1373 * IP timer processing;
1374 * if a timer expires on a reassembly
1375 * queue, discard it.
1384 for (i = 0; i < IPREASS_NHASH; i++) {
1388 while (fp != &ipq[i]) {
1391 if (fp->prev->ipq_ttl == 0) {
1392 ipstat.ips_fragtimeout += fp->prev->ipq_nfrags;
1398 * If we are over the maximum number of fragments
1399 * (due to the limit being lowered), drain off
1400 * enough to get down to the new limit.
1402 if (maxnipq >= 0 && nipq > maxnipq) {
1403 for (i = 0; i < IPREASS_NHASH; i++) {
1404 while (nipq > maxnipq &&
1405 (ipq[i].next != &ipq[i])) {
1406 ipstat.ips_fragdropped +=
1407 ipq[i].next->ipq_nfrags;
1408 ip_freef(ipq[i].next);
1417 * Drain off all datagram fragments.
1424 for (i = 0; i < IPREASS_NHASH; i++) {
1425 while (ipq[i].next != &ipq[i]) {
1426 ipstat.ips_fragdropped += ipq[i].next->ipq_nfrags;
1427 ip_freef(ipq[i].next);
1434 * Do option processing on a datagram,
1435 * possibly discarding it if bad options are encountered,
1436 * or forwarding it if source-routed.
1437 * The pass argument is used when operating in the IPSTEALTH
1438 * mode to tell what options to process:
1439 * [LS]SRR (pass 0) or the others (pass 1).
1440 * The reason for as many as two passes is that when doing IPSTEALTH,
1441 * non-routing options should be processed only if the packet is for us.
1442 * Returns 1 if packet has been forwarded/freed,
1443 * 0 if the packet should be processed further.
1446 ip_dooptions(struct mbuf *m, int pass, struct sockaddr_in *next_hop)
1448 struct ip *ip = mtod(m, struct ip *);
1450 struct in_ifaddr *ia;
1451 int opt, optlen, cnt, off, code, type = ICMP_PARAMPROB;
1452 boolean_t forward = FALSE;
1453 struct in_addr *sin, dst;
1457 cp = (u_char *)(ip + 1);
1458 cnt = (IP_VHL_HL(ip->ip_vhl) << 2) - sizeof(struct ip);
1459 for (; cnt > 0; cnt -= optlen, cp += optlen) {
1460 opt = cp[IPOPT_OPTVAL];
1461 if (opt == IPOPT_EOL)
1463 if (opt == IPOPT_NOP)
1466 if (cnt < IPOPT_OLEN + sizeof(*cp)) {
1467 code = &cp[IPOPT_OLEN] - (u_char *)ip;
1470 optlen = cp[IPOPT_OLEN];
1471 if (optlen < IPOPT_OLEN + sizeof(*cp) || optlen > cnt) {
1472 code = &cp[IPOPT_OLEN] - (u_char *)ip;
1482 * Source routing with record.
1483 * Find interface with current destination address.
1484 * If none on this machine then drop if strictly routed,
1485 * or do nothing if loosely routed.
1486 * Record interface address and bring up next address
1487 * component. If strictly routed make sure next
1488 * address is on directly accessible net.
1492 if (ipstealth && pass > 0)
1494 if (optlen < IPOPT_OFFSET + sizeof(*cp)) {
1495 code = &cp[IPOPT_OLEN] - (u_char *)ip;
1498 if ((off = cp[IPOPT_OFFSET]) < IPOPT_MINOFF) {
1499 code = &cp[IPOPT_OFFSET] - (u_char *)ip;
1502 ipaddr.sin_addr = ip->ip_dst;
1503 ia = (struct in_ifaddr *)
1504 ifa_ifwithaddr((struct sockaddr *)&ipaddr);
1506 if (opt == IPOPT_SSRR) {
1507 type = ICMP_UNREACH;
1508 code = ICMP_UNREACH_SRCFAIL;
1511 if (!ip_dosourceroute)
1512 goto nosourcerouting;
1514 * Loose routing, and not at next destination
1515 * yet; nothing to do except forward.
1519 off--; /* 0 origin */
1520 if (off > optlen - (int)sizeof(struct in_addr)) {
1522 * End of source route. Should be for us.
1524 if (!ip_acceptsourceroute)
1525 goto nosourcerouting;
1526 save_rte(cp, ip->ip_src);
1531 if (!ip_dosourceroute) {
1533 char buf[16]; /* aaa.bbb.ccc.ddd\0 */
1535 * Acting as a router, so generate ICMP
1538 strcpy(buf, inet_ntoa(ip->ip_dst));
1540 "attempted source route from %s to %s\n",
1541 inet_ntoa(ip->ip_src), buf);
1542 type = ICMP_UNREACH;
1543 code = ICMP_UNREACH_SRCFAIL;
1547 * Not acting as a router,
1551 ipstat.ips_cantforward++;
1558 * locate outgoing interface
1560 memcpy(&ipaddr.sin_addr, cp + off,
1561 sizeof ipaddr.sin_addr);
1563 if (opt == IPOPT_SSRR) {
1564 #define INA struct in_ifaddr *
1565 #define SA struct sockaddr *
1566 if ((ia = (INA)ifa_ifwithdstaddr((SA)&ipaddr))
1568 ia = (INA)ifa_ifwithnet((SA)&ipaddr);
1570 ia = ip_rtaddr(ipaddr.sin_addr, &ipforward_rt);
1572 type = ICMP_UNREACH;
1573 code = ICMP_UNREACH_SRCFAIL;
1576 ip->ip_dst = ipaddr.sin_addr;
1577 memcpy(cp + off, &IA_SIN(ia)->sin_addr,
1578 sizeof(struct in_addr));
1579 cp[IPOPT_OFFSET] += sizeof(struct in_addr);
1581 * Let ip_intr's mcast routing check handle mcast pkts
1583 forward = !IN_MULTICAST(ntohl(ip->ip_dst.s_addr));
1587 if (ipstealth && pass == 0)
1589 if (optlen < IPOPT_OFFSET + sizeof(*cp)) {
1590 code = &cp[IPOPT_OFFSET] - (u_char *)ip;
1593 if ((off = cp[IPOPT_OFFSET]) < IPOPT_MINOFF) {
1594 code = &cp[IPOPT_OFFSET] - (u_char *)ip;
1598 * If no space remains, ignore.
1600 off--; /* 0 origin */
1601 if (off > optlen - (int)sizeof(struct in_addr))
1603 memcpy(&ipaddr.sin_addr, &ip->ip_dst,
1604 sizeof ipaddr.sin_addr);
1606 * locate outgoing interface; if we're the destination,
1607 * use the incoming interface (should be same).
1609 if ((ia = (INA)ifa_ifwithaddr((SA)&ipaddr)) == NULL &&
1610 (ia = ip_rtaddr(ipaddr.sin_addr, &ipforward_rt))
1612 type = ICMP_UNREACH;
1613 code = ICMP_UNREACH_HOST;
1616 memcpy(cp + off, &IA_SIN(ia)->sin_addr,
1617 sizeof(struct in_addr));
1618 cp[IPOPT_OFFSET] += sizeof(struct in_addr);
1622 if (ipstealth && pass == 0)
1624 code = cp - (u_char *)ip;
1625 if (optlen < 4 || optlen > 40) {
1626 code = &cp[IPOPT_OLEN] - (u_char *)ip;
1629 if ((off = cp[IPOPT_OFFSET]) < 5) {
1630 code = &cp[IPOPT_OLEN] - (u_char *)ip;
1633 if (off > optlen - (int)sizeof(int32_t)) {
1634 cp[IPOPT_OFFSET + 1] += (1 << 4);
1635 if ((cp[IPOPT_OFFSET + 1] & 0xf0) == 0) {
1636 code = &cp[IPOPT_OFFSET] - (u_char *)ip;
1641 off--; /* 0 origin */
1642 sin = (struct in_addr *)(cp + off);
1643 switch (cp[IPOPT_OFFSET + 1] & 0x0f) {
1645 case IPOPT_TS_TSONLY:
1648 case IPOPT_TS_TSANDADDR:
1649 if (off + sizeof(n_time) +
1650 sizeof(struct in_addr) > optlen) {
1651 code = &cp[IPOPT_OFFSET] - (u_char *)ip;
1654 ipaddr.sin_addr = dst;
1655 ia = (INA)ifaof_ifpforaddr((SA)&ipaddr,
1659 memcpy(sin, &IA_SIN(ia)->sin_addr,
1660 sizeof(struct in_addr));
1661 cp[IPOPT_OFFSET] += sizeof(struct in_addr);
1662 off += sizeof(struct in_addr);
1665 case IPOPT_TS_PRESPEC:
1666 if (off + sizeof(n_time) +
1667 sizeof(struct in_addr) > optlen) {
1668 code = &cp[IPOPT_OFFSET] - (u_char *)ip;
1671 memcpy(&ipaddr.sin_addr, sin,
1672 sizeof(struct in_addr));
1673 if (ifa_ifwithaddr((SA)&ipaddr) == NULL)
1675 cp[IPOPT_OFFSET] += sizeof(struct in_addr);
1676 off += sizeof(struct in_addr);
1680 code = &cp[IPOPT_OFFSET + 1] - (u_char *)ip;
1684 memcpy(cp + off, &ntime, sizeof(n_time));
1685 cp[IPOPT_OFFSET] += sizeof(n_time);
1688 if (forward && ipforwarding) {
1689 ip_forward(m, 1, next_hop);
1694 icmp_error(m, type, code, 0, NULL);
1695 ipstat.ips_badoptions++;
1700 * Given address of next destination (final or next hop),
1701 * return internet address info of interface to be used to get there.
1704 ip_rtaddr(struct in_addr dst, struct route *rt)
1706 struct sockaddr_in *sin;
1708 sin = (struct sockaddr_in *)&rt->ro_dst;
1710 if (rt->ro_rt == NULL || dst.s_addr != sin->sin_addr.s_addr) {
1711 if (rt->ro_rt != NULL) {
1715 sin->sin_family = AF_INET;
1716 sin->sin_len = sizeof(*sin);
1717 sin->sin_addr = dst;
1718 rtalloc_ign(rt, RTF_PRCLONING);
1721 if (rt->ro_rt == NULL)
1724 return (ifatoia(rt->ro_rt->rt_ifa));
1728 * Save incoming source route for use in replies,
1729 * to be picked up later by ip_srcroute if the receiver is interested.
1732 save_rte(u_char *option, struct in_addr dst)
1736 olen = option[IPOPT_OLEN];
1739 printf("save_rte: olen %d\n", olen);
1741 if (olen > sizeof(ip_srcrt) - (1 + sizeof(dst)))
1743 bcopy(option, ip_srcrt.srcopt, olen);
1744 ip_nhops = (olen - IPOPT_OFFSET - 1) / sizeof(struct in_addr);
1749 * Retrieve incoming source route for use in replies,
1750 * in the same form used by setsockopt.
1751 * The first hop is placed before the options, will be removed later.
1756 struct in_addr *p, *q;
1761 m = m_get(MB_DONTWAIT, MT_HEADER);
1765 #define OPTSIZ (sizeof(ip_srcrt.nop) + sizeof(ip_srcrt.srcopt))
1767 /* length is (nhops+1)*sizeof(addr) + sizeof(nop + srcrt header) */
1768 m->m_len = ip_nhops * sizeof(struct in_addr) + sizeof(struct in_addr) +
1772 printf("ip_srcroute: nhops %d mlen %d", ip_nhops, m->m_len);
1776 * First save first hop for return route
1778 p = &ip_srcrt.route[ip_nhops - 1];
1779 *(mtod(m, struct in_addr *)) = *p--;
1782 printf(" hops %x", ntohl(mtod(m, struct in_addr *)->s_addr));
1786 * Copy option fields and padding (nop) to mbuf.
1788 ip_srcrt.nop = IPOPT_NOP;
1789 ip_srcrt.srcopt[IPOPT_OFFSET] = IPOPT_MINOFF;
1790 memcpy(mtod(m, caddr_t) + sizeof(struct in_addr), &ip_srcrt.nop,
1792 q = (struct in_addr *)(mtod(m, caddr_t) +
1793 sizeof(struct in_addr) + OPTSIZ);
1796 * Record return path as an IP source route,
1797 * reversing the path (pointers are now aligned).
1799 while (p >= ip_srcrt.route) {
1802 printf(" %x", ntohl(q->s_addr));
1807 * Last hop goes to final destination.
1812 printf(" %x\n", ntohl(q->s_addr));
1818 * Strip out IP options.
1821 ip_stripoptions(struct mbuf *m)
1824 struct ip *ip = mtod(m, struct ip *);
1828 optlen = (IP_VHL_HL(ip->ip_vhl) << 2) - sizeof(struct ip);
1829 opts = (caddr_t)(ip + 1);
1830 datalen = m->m_len - (sizeof(struct ip) + optlen);
1831 bcopy(opts + optlen, opts, datalen);
1833 if (m->m_flags & M_PKTHDR)
1834 m->m_pkthdr.len -= optlen;
1835 ip->ip_vhl = IP_MAKE_VHL(IPVERSION, sizeof(struct ip) >> 2);
1838 u_char inetctlerrmap[PRC_NCMDS] = {
1840 0, EMSGSIZE, EHOSTDOWN, EHOSTUNREACH,
1841 EHOSTUNREACH, EHOSTUNREACH, ECONNREFUSED, ECONNREFUSED,
1842 EMSGSIZE, EHOSTUNREACH, 0, 0,
1844 ENOPROTOOPT, ECONNREFUSED
1848 * Forward a packet. If some error occurs return the sender
1849 * an icmp packet. Note we can't always generate a meaningful
1850 * icmp message because icmp doesn't have a large enough repertoire
1851 * of codes and types.
1853 * If not forwarding, just drop the packet. This could be confusing
1854 * if ipforwarding was zero but some routing protocol was advancing
1855 * us as a gateway to somewhere. However, we must let the routing
1856 * protocol deal with that.
1858 * The using_srcrt parameter indicates whether the packet is being forwarded
1859 * via a source route.
1862 ip_forward(struct mbuf *m, int using_srcrt, struct sockaddr_in *next_hop)
1864 struct ip *ip = mtod(m, struct ip *);
1865 struct sockaddr_in *sin;
1867 int error, type = 0, code = 0;
1870 struct in_addr pkt_dst;
1871 struct ifnet *destifp;
1873 #if defined(IPSEC) || defined(FAST_IPSEC)
1874 struct ifnet dummyifp;
1879 * Cache the destination address of the packet; this may be
1880 * changed by use of 'ipfw fwd'.
1882 pkt_dst = next_hop ? next_hop->sin_addr : ip->ip_dst;
1886 printf("forward: src %x dst %x ttl %x\n",
1887 ip->ip_src.s_addr, pkt_dst.s_addr, ip->ip_ttl);
1890 if (m->m_flags & (M_BCAST | M_MCAST) || !in_canforward(pkt_dst)) {
1891 ipstat.ips_cantforward++;
1895 if (!ipstealth && ip->ip_ttl <= IPTTLDEC) {
1896 icmp_error(m, ICMP_TIMXCEED, ICMP_TIMXCEED_INTRANS, dest, NULL);
1900 sin = (struct sockaddr_in *)&ipforward_rt.ro_dst;
1901 if ((rt = ipforward_rt.ro_rt) == NULL ||
1902 pkt_dst.s_addr != sin->sin_addr.s_addr) {
1903 if (ipforward_rt.ro_rt != NULL) {
1904 RTFREE(ipforward_rt.ro_rt);
1905 ipforward_rt.ro_rt = NULL;
1907 sin->sin_family = AF_INET;
1908 sin->sin_len = sizeof(*sin);
1909 sin->sin_addr = pkt_dst;
1911 rtalloc_ign(&ipforward_rt, RTF_PRCLONING);
1912 if (ipforward_rt.ro_rt == NULL) {
1913 icmp_error(m, ICMP_UNREACH, ICMP_UNREACH_HOST, dest,
1917 rt = ipforward_rt.ro_rt;
1921 * Save the IP header and at most 8 bytes of the payload,
1922 * in case we need to generate an ICMP message to the src.
1924 * XXX this can be optimized a lot by saving the data in a local
1925 * buffer on the stack (72 bytes at most), and only allocating the
1926 * mbuf if really necessary. The vast majority of the packets
1927 * are forwarded without having to send an ICMP back (either
1928 * because unnecessary, or because rate limited), so we are
1929 * really we are wasting a lot of work here.
1931 * We don't use m_copy() because it might return a reference
1932 * to a shared cluster. Both this function and ip_output()
1933 * assume exclusive access to the IP header in `m', so any
1934 * data in a cluster may change before we reach icmp_error().
1936 MGET(mcopy, MB_DONTWAIT, m->m_type);
1937 if (mcopy != NULL && !m_dup_pkthdr(mcopy, m, MB_DONTWAIT)) {
1939 * It's probably ok if the pkthdr dup fails (because
1940 * the deep copy of the tag chain failed), but for now
1941 * be conservative and just discard the copy since
1942 * code below may some day want the tags.
1947 if (mcopy != NULL) {
1948 mcopy->m_len = imin((IP_VHL_HL(ip->ip_vhl) << 2) + 8,
1950 mcopy->m_pkthdr.len = mcopy->m_len;
1951 m_copydata(m, 0, mcopy->m_len, mtod(mcopy, caddr_t));
1955 ip->ip_ttl -= IPTTLDEC;
1958 * If forwarding packet using same interface that it came in on,
1959 * perhaps should send a redirect to sender to shortcut a hop.
1960 * Only send redirect if source is sending directly to us,
1961 * and if packet was not source routed (or has any options).
1962 * Also, don't send redirect if forwarding using a default route
1963 * or a route modified by a redirect.
1965 if (rt->rt_ifp == m->m_pkthdr.rcvif &&
1966 !(rt->rt_flags & (RTF_DYNAMIC | RTF_MODIFIED)) &&
1967 satosin(rt_key(rt))->sin_addr.s_addr != INADDR_ANY &&
1968 ipsendredirects && !using_srcrt && next_hop != NULL) {
1969 u_long src = ntohl(ip->ip_src.s_addr);
1971 #define RTA(rt) ((struct in_ifaddr *)(rt->rt_ifa))
1972 if (RTA(rt) != NULL &&
1973 (src & RTA(rt)->ia_subnetmask) == RTA(rt)->ia_subnet) {
1974 if (rt->rt_flags & RTF_GATEWAY)
1975 dest = satosin(rt->rt_gateway)->sin_addr.s_addr;
1977 dest = pkt_dst.s_addr;
1979 * Router requirements says to only send
1982 type = ICMP_REDIRECT;
1983 code = ICMP_REDIRECT_HOST;
1986 printf("redirect (%d) to %x\n", code, dest);
1992 /* Pass IPFORWARD info if available */
1993 tag.mh_type = MT_TAG;
1994 tag.mh_flags = PACKET_TAG_IPFORWARD;
1995 tag.mh_data = (caddr_t)next_hop;
1997 m = (struct mbuf *)&tag;
2000 error = ip_output(m, NULL, &ipforward_rt, IP_FORWARDING, NULL, NULL);
2003 ipstat.ips_cantforward++;
2005 ipstat.ips_forward++;
2007 ipstat.ips_redirectsent++;
2010 ipflow_create(&ipforward_rt, mcopy);
2022 case 0: /* forwarded, but need redirect */
2023 /* type, code set above */
2026 case ENETUNREACH: /* shouldn't happen, checked above */
2031 type = ICMP_UNREACH;
2032 code = ICMP_UNREACH_HOST;
2036 type = ICMP_UNREACH;
2037 code = ICMP_UNREACH_NEEDFRAG;
2040 * If the packet is routed over IPsec tunnel, tell the
2041 * originator the tunnel MTU.
2042 * tunnel MTU = if MTU - sizeof(IP) - ESP/AH hdrsiz
2045 if (ipforward_rt.ro_rt != NULL) {
2046 struct secpolicy *sp = NULL;
2051 sp = ipsec4_getpolicybyaddr(mcopy,
2057 destifp = ipforward_rt.ro_rt->rt_ifp;
2059 /* count IPsec header size */
2060 ipsechdr = ipsec4_hdrsiz(mcopy,
2065 * find the correct route for outer IPv4
2066 * header, compute tunnel MTU.
2069 * The "dummyifp" code relies upon the fact
2070 * that icmp_error() touches only ifp->if_mtu.
2074 if (sp->req != NULL && 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;
2091 * If the packet is routed over IPsec tunnel, tell the
2092 * originator the tunnel MTU.
2093 * tunnel MTU = if MTU - sizeof(IP) - ESP/AH hdrsiz
2096 if (ipforward_rt.ro_rt != NULL) {
2097 struct secpolicy *sp = NULL;
2102 sp = ipsec_getpolicybyaddr(mcopy,
2108 destifp = ipforward_rt.ro_rt->rt_ifp;
2110 /* count IPsec header size */
2111 ipsechdr = ipsec4_hdrsiz(mcopy,
2116 * find the correct route for outer IPv4
2117 * header, compute tunnel MTU.
2120 * The "dummyifp" code relies upon the fact
2121 * that icmp_error() touches only ifp->if_mtu.
2125 if (sp->req != NULL &&
2126 sp->req->sav != NULL &&
2127 sp->req->sav->sah != NULL) {
2128 ro = &sp->req->sav->sah->sa_route;
2129 if (ro->ro_rt != NULL &&
2130 ro->ro_rt->rt_ifp != NULL) {
2132 ro->ro_rt->rt_ifp->if_mtu;
2133 dummyifp.if_mtu -= ipsechdr;
2134 destifp = &dummyifp;
2141 #else /* !IPSEC && !FAST_IPSEC */
2142 if (ipforward_rt.ro_rt != NULL)
2143 destifp = ipforward_rt.ro_rt->rt_ifp;
2145 ipstat.ips_cantfrag++;
2150 * A router should not generate ICMP_SOURCEQUENCH as
2151 * required in RFC1812 Requirements for IP Version 4 Routers.
2152 * Source quench could be a big problem under DoS attacks,
2153 * or if the underlying interface is rate-limited.
2154 * Those who need source quench packets may re-enable them
2155 * via the net.inet.ip.sendsourcequench sysctl.
2157 if (!ip_sendsourcequench) {
2161 type = ICMP_SOURCEQUENCH;
2166 case EACCES: /* ipfw denied packet */
2170 icmp_error(mcopy, type, code, dest, destifp);
2174 ip_savecontrol(struct inpcb *inp, struct mbuf **mp, struct ip *ip,
2177 if (inp->inp_socket->so_options & SO_TIMESTAMP) {
2181 *mp = sbcreatecontrol((caddr_t) &tv, sizeof(tv),
2182 SCM_TIMESTAMP, SOL_SOCKET);
2184 mp = &(*mp)->m_next;
2186 if (inp->inp_flags & INP_RECVDSTADDR) {
2187 *mp = sbcreatecontrol((caddr_t) &ip->ip_dst,
2188 sizeof(struct in_addr), IP_RECVDSTADDR, IPPROTO_IP);
2190 mp = &(*mp)->m_next;
2194 * Moving these out of udp_input() made them even more broken
2195 * than they already were.
2197 /* options were tossed already */
2198 if (inp->inp_flags & INP_RECVOPTS) {
2199 *mp = sbcreatecontrol((caddr_t) opts_deleted_above,
2200 sizeof(struct in_addr), IP_RECVOPTS, IPPROTO_IP);
2202 mp = &(*mp)->m_next;
2204 /* ip_srcroute doesn't do what we want here, need to fix */
2205 if (inp->inp_flags & INP_RECVRETOPTS) {
2206 *mp = sbcreatecontrol((caddr_t) ip_srcroute(),
2207 sizeof(struct in_addr), IP_RECVRETOPTS, IPPROTO_IP);
2209 mp = &(*mp)->m_next;
2212 if (inp->inp_flags & INP_RECVIF) {
2215 struct sockaddr_dl sdl;
2218 struct sockaddr_dl *sdp;
2219 struct sockaddr_dl *sdl2 = &sdlbuf.sdl;
2221 if (((ifp = m->m_pkthdr.rcvif)) &&
2222 ((ifp->if_index != 0) && (ifp->if_index <= if_index))) {
2223 sdp = (struct sockaddr_dl *)
2224 ifnet_addrs[ifp->if_index - 1]->ifa_addr;
2226 * Change our mind and don't try copy.
2228 if ((sdp->sdl_family != AF_LINK) ||
2229 (sdp->sdl_len > sizeof(sdlbuf))) {
2232 bcopy(sdp, sdl2, sdp->sdl_len);
2236 offsetof(struct sockaddr_dl, sdl_data[0]);
2237 sdl2->sdl_family = AF_LINK;
2238 sdl2->sdl_index = 0;
2239 sdl2->sdl_nlen = sdl2->sdl_alen = sdl2->sdl_slen = 0;
2241 *mp = sbcreatecontrol((caddr_t) sdl2, sdl2->sdl_len,
2242 IP_RECVIF, IPPROTO_IP);
2244 mp = &(*mp)->m_next;
2249 * XXX these routines are called from the upper part of the kernel.
2251 * They could also be moved to ip_mroute.c, since all the RSVP
2252 * handling is done there already.
2255 ip_rsvp_init(struct socket *so)
2257 if (so->so_type != SOCK_RAW ||
2258 so->so_proto->pr_protocol != IPPROTO_RSVP)
2261 if (ip_rsvpd != NULL)
2266 * This may seem silly, but we need to be sure we don't over-increment
2267 * the RSVP counter, in case something slips up.
2282 * This may seem silly, but we need to be sure we don't over-decrement
2283 * the RSVP counter, in case something slips up.
2293 rsvp_input(struct mbuf *m, ...) /* XXX must fixup manually */
2299 off = __va_arg(ap, int);
2300 proto = __va_arg(ap, int);
2303 if (rsvp_input_p) { /* call the real one if loaded */
2304 rsvp_input_p(m, off, proto);
2308 /* Can still get packets with rsvp_on = 0 if there is a local member
2309 * of the group to which the RSVP packet is addressed. But in this
2310 * case we want to throw the packet away.
2318 if (ip_rsvpd != NULL) {
2319 rip_input(m, off, proto);
2322 /* Drop the packet */