Clean up the routing and networking code before I parallelize routing.
[dragonfly.git] / sys / netinet / ip_input.c
1 /*
2  * Copyright (c) 2003, 2004 Jeffrey M. Hsu.  All rights reserved.
3  * Copyright (c) 2003, 2004 The DragonFly Project.  All rights reserved.
4  *
5  * This code is derived from software contributed to The DragonFly Project
6  * by Jeffrey M. Hsu.
7  *
8  * Redistribution and use in source and binary forms, with or without
9  * modification, are permitted provided that the following conditions
10  * are met:
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.
19  *
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
31  * SUCH DAMAGE.
32  */
33
34 /*
35  * Copyright (c) 2003, 2004 Jeffrey M. Hsu.  All rights reserved.
36  *
37  * License terms: all terms for the DragonFly license above plus the following:
38  *
39  * 4. All advertising materials mentioning features or use of this software
40  *    must display the following acknowledgement:
41  *
42  *      This product includes software developed by Jeffrey M. Hsu
43  *      for the DragonFly Project.
44  *
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
48  *    apply.
49  */
50
51 /*
52  * Copyright (c) 1982, 1986, 1988, 1993
53  *      The Regents of the University of California.  All rights reserved.
54  *
55  * Redistribution and use in source and binary forms, with or without
56  * modification, are permitted provided that the following conditions
57  * are met:
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.
70  *
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
81  * SUCH DAMAGE.
82  *
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 $
86  */
87
88 #define _IP_VHL
89
90 #include "opt_bootp.h"
91 #include "opt_ipfw.h"
92 #include "opt_ipdn.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"
98
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>
114
115 #include <sys/thread2.h>
116 #include <sys/msgport2.h>
117
118 #include <machine/stdarg.h>
119
120 #include <net/if.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>
128
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>
136
137
138 #include <sys/socketvar.h>
139
140 #include <net/ipfw/ip_fw.h>
141 #include <net/dummynet/ip_dummynet.h>
142
143 #ifdef IPSEC
144 #include <netinet6/ipsec.h>
145 #include <netproto/key/key.h>
146 #endif
147
148 #ifdef FAST_IPSEC
149 #include <netproto/ipsec/ipsec.h>
150 #include <netproto/ipsec/key.h>
151 #endif
152
153 int rsvp_on = 0;
154 static int ip_rsvp_on;
155 struct socket *ip_rsvpd;
156
157 int ipforwarding = 0;
158 SYSCTL_INT(_net_inet_ip, IPCTL_FORWARDING, forwarding, CTLFLAG_RW,
159     &ipforwarding, 0, "Enable IP forwarding between interfaces");
160
161 static int ipsendredirects = 1; /* XXX */
162 SYSCTL_INT(_net_inet_ip, IPCTL_SENDREDIRECTS, redirect, CTLFLAG_RW,
163     &ipsendredirects, 0, "Enable sending IP redirects");
164
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");
168
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");
172
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");
177
178 static int ip_keepfaith = 0;
179 SYSCTL_INT(_net_inet_ip, IPCTL_KEEPFAITH, keepfaith, CTLFLAG_RW,
180     &ip_keepfaith, 0,
181     "Enable packet capture for FAITH IPv4->IPv6 translater daemon");
182
183 static int nipq = 0;    /* total # of reass queues */
184 static int maxnipq;
185 SYSCTL_INT(_net_inet_ip, OID_AUTO, maxfragpackets, CTLFLAG_RW,
186     &maxnipq, 0,
187     "Maximum number of IPv4 fragment reassembly queue entries");
188
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");
193
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");
198
199 /*
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.
204  *
205  * XXX - ip_checkinterface currently must be disabled if you use ipnat
206  * to translate the destination address to another local interface.
207  *
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.
211  */
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");
215
216 #ifdef DIAGNOSTIC
217 static int ipprintfs = 0;
218 #endif
219
220 static struct ifqueue ipintrq;
221 static int ipqmaxlen = IFQ_MAXLEN;
222
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 */
229
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");
234
235 struct ip_stats ipstats_ary[MAXCPU];
236 #ifdef SMP
237 static int
238 sysctl_ipstats(SYSCTL_HANDLER_ARGS)
239 {
240         int cpu, error = 0;
241
242         for (cpu = 0; cpu < ncpus; ++cpu) {
243                 if ((error = SYSCTL_OUT(req, &ipstats_ary[cpu],
244                                         sizeof(struct ip_stats))))
245                         break;
246                 if ((error = SYSCTL_IN(req, &ipstats_ary[cpu],
247                                        sizeof(struct ip_stats))))
248                         break;
249         }
250
251         return (error);
252 }
253 SYSCTL_PROC(_net_inet_ip, IPCTL_STATS, stats, (CTLTYPE_OPAQUE | CTLFLAG_RW),
254     0, 0, sysctl_ipstats, "S,ip_stats", "IP statistics");
255 #else
256 SYSCTL_STRUCT(_net_inet_ip, IPCTL_STATS, stats, CTLFLAG_RW,
257     &ipstat, ip_stats, "IP statistics");
258 #endif
259
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)
266
267 static struct ipq ipq[IPREASS_NHASH];
268 const  int    ipintrq_present = 1;
269
270 #ifdef IPCTL_DEFMTU
271 SYSCTL_INT(_net_inet_ip, IPCTL_DEFMTU, mtu, CTLFLAG_RW,
272     &ip_mtu, 0, "Default MTU");
273 #endif
274
275 #ifdef IPSTEALTH
276 static int ipstealth = 0;
277 SYSCTL_INT(_net_inet_ip, OID_AUTO, stealth, CTLFLAG_RW, &ipstealth, 0, "");
278 #else
279 static const int ipstealth = 0;
280 #endif
281
282
283 /* Firewall hooks */
284 ip_fw_chk_t *ip_fw_chk_ptr;
285 int fw_enable = 1;
286 int fw_one_pass = 1;
287
288 /* Dummynet hooks */
289 ip_dn_io_t *ip_dn_io_ptr;
290
291 struct pfil_head inet_pfil_hook;
292
293 /*
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.
299  *
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
304  * to us.
305  */
306 static int ip_nhops = 0;
307
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)];
313 } ip_srcrt;
314
315 static MALLOC_DEFINE(M_IPQ, "ipq", "IP Fragment Management");
316 static struct malloc_pipe ipq_mpipe;
317
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 *);
327
328 /*
329  * IP initialization: fill in IP protocol switch table.
330  * All protocols not implemented in kernel go to raw IP protocol handler.
331  */
332 void
333 ip_init(void)
334 {
335         struct protosw *pr;
336         int i;
337 #ifdef SMP
338         int cpu;
339 #endif
340
341         /*
342          * Make sure we can handle a reasonable number of fragments but
343          * cap it at 4000 (XXX).
344          */
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);
350         if (pr == NULL)
351                 panic("ip_init");
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;
359
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);
365         }
366
367         for (i = 0; i < IPREASS_NHASH; i++)
368             ipq[i].next = ipq[i].prev = &ipq[i];
369
370         maxnipq = nmbclusters / 32;
371         maxfragsperpacket = 16;
372
373 #ifndef RANDOM_IP_ID
374         ip_id = time_second & 0xffff;
375 #endif
376         ipintrq.ifq_maxlen = ipqmaxlen;
377
378         /*
379          * Initialize IP statistics.
380          *
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.
384          */
385 #ifdef SMP
386         for (cpu = 0; cpu < ncpus; ++cpu) {
387                 bzero(&ipstats_ary[cpu], sizeof(struct ip_stats));
388         }
389 #else
390         bzero(&ipstat, sizeof(struct ip_stats));
391 #endif
392
393         netisr_register(NETISR_IP, ip_mport, ip_input_handler);
394 }
395
396 /*
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.
400  */
401 struct route ipforward_rt;
402 static struct sockaddr_in ipaddr = { sizeof(ipaddr), AF_INET };
403
404 /* Do transport protocol processing. */
405 static void
406 transport_processing_oncpu(struct mbuf *m, int hlen, struct ip *ip,
407                            struct sockaddr_in *nexthop)
408 {
409         /*
410          * Switch out to protocol's input routine.
411          */
412         if (nexthop && ip->ip_p == IPPROTO_TCP) {
413                 /* TCP needs IPFORWARD info if available */
414                 struct m_hdr tag;
415
416                 tag.mh_type = MT_TAG;
417                 tag.mh_flags = PACKET_TAG_IPFORWARD;
418                 tag.mh_data = (caddr_t)nexthop;
419                 tag.mh_next = m;
420
421                 (*inetsw[ip_protox[ip->ip_p]].pr_input)
422                     ((struct mbuf *)&tag, hlen, ip->ip_p);
423         } else {
424                 (*inetsw[ip_protox[ip->ip_p]].pr_input)(m, hlen, ip->ip_p);
425         }
426 }
427
428 struct netmsg_transport_packet {
429         struct lwkt_msg         nm_lmsg;
430         struct mbuf             *nm_mbuf;
431         int                     nm_hlen;
432         boolean_t               nm_hasnexthop;
433         struct sockaddr_in      nm_nexthop;
434 };
435
436 static int
437 transport_processing_handler(lwkt_msg_t lmsg)
438 {
439         struct netmsg_transport_packet *msg = (void *)lmsg;
440         struct sockaddr_in *nexthop;
441         struct ip *ip;
442
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);
447         return(EASYNC);
448 }
449
450 static int
451 ip_input_handler(struct netmsg *msg0)
452 {
453         struct mbuf *m = ((struct netmsg_packet *)msg0)->nm_packet;
454
455         ip_input(m);
456         lwkt_replymsg(&msg0->nm_lmsg, 0);
457         return(EASYNC);
458 }
459
460 /*
461  * Ip input routine.  Checksum and byte swap header.  If fragmented
462  * try to reassemble.  Process options.  Pass to next level.
463  */
464 void
465 ip_input(struct mbuf *m)
466 {
467         struct ip *ip;
468         struct ipq *fp;
469         struct in_ifaddr *ia = NULL;
470         struct ifaddr *ifa;
471         int i, hlen, checkif;
472         u_short sum;
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) */
479 #ifdef FAST_IPSEC
480         struct m_tag *mtag;
481         struct tdb_ident *tdbi;
482         struct secpolicy *sp;
483         int s, error;
484 #endif
485
486         args.eh = NULL;
487         args.oif = NULL;
488         args.rule = NULL;
489         args.divert_rule = 0;                   /* divert cookie */
490         args.next_hop = NULL;
491
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) {
495                 default:
496                         printf("ip_input: unrecognised MT_TAG tag %d\n",
497                             m->_m_tag_id);
498                         break;
499
500                 case PACKET_TAG_DUMMYNET:
501                         args.rule = ((struct dn_pkt *)m)->rule;
502                         break;
503
504                 case PACKET_TAG_DIVERT:
505                         args.divert_rule = (int)m->m_hdr.mh_data & 0xffff;
506                         break;
507
508                 case PACKET_TAG_IPFORWARD:
509                         args.next_hop = (struct sockaddr_in *)m->m_hdr.mh_data;
510                         break;
511                 }
512         }
513
514         KASSERT(m != NULL && (m->m_flags & M_PKTHDR) != 0,
515             ("ip_input: no HDR"));
516
517         if (args.rule) {        /* dummynet already filtered us */
518                 ip = mtod(m, struct ip *);
519                 hlen = IP_VHL_HL(ip->ip_vhl) << 2;
520                 goto iphack;
521         }
522
523         ipstat.ips_total++;
524
525         /* length checks already done in ip_demux() */
526         KASSERT(m->m_len >= sizeof(ip), ("IP header not in one mbuf"));
527
528         ip = mtod(m, struct ip *);
529
530         if (IP_VHL_V(ip->ip_vhl) != IPVERSION) {
531                 ipstat.ips_badvers++;
532                 goto bad;
533         }
534
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"));
539
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++;
545                         goto bad;
546                 }
547         }
548
549         if (m->m_pkthdr.csum_flags & CSUM_IP_CHECKED) {
550                 sum = !(m->m_pkthdr.csum_flags & CSUM_IP_VALID);
551         } else {
552                 if (hlen == sizeof(struct ip)) {
553                         sum = in_cksum_hdr(ip);
554                 } else {
555                         sum = in_cksum(m, hlen);
556                 }
557         }
558         if (sum) {
559                 ipstat.ips_badsum++;
560                 goto bad;
561         }
562
563         /*
564          * Convert fields to host representation.
565          */
566         ip->ip_len = ntohs(ip->ip_len);
567         if (ip->ip_len < hlen) {
568                 ipstat.ips_badlen++;
569                 goto bad;
570         }
571         ip->ip_off = ntohs(ip->ip_off);
572
573         /*
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.
578          */
579         if (m->m_pkthdr.len < ip->ip_len) {
580                 ipstat.ips_tooshort++;
581                 goto bad;
582         }
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;
587                 } else
588                         m_adj(m, ip->ip_len - m->m_pkthdr.len);
589         }
590 #if defined(IPSEC) && !defined(IPSEC_FILTERGIF)
591         /*
592          * Bypass packet filtering for packets from a tunnel (gif).
593          */
594         if (ipsec_gethist(m, NULL))
595                 goto pass;
596 #endif
597
598         /*
599          * IpHack's section.
600          * Right now when no processing on packet has done
601          * and it is still fresh out of network we do our black
602          * deals with it.
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.>
608          */
609
610 iphack:
611
612         /*
613          * Run through list of hooks for input packets.
614          *
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.
618          */
619         if (pfil_has_hooks(&inet_pfil_hook)) {
620                 odst = ip->ip_dst;
621                 if (pfil_run_hooks(&inet_pfil_hook, &m,
622                     m->m_pkthdr.rcvif, PFIL_IN)) {
623                         return;
624                 }
625                 if (m == NULL)                  /* consumed by filter */
626                         return;
627                 ip = mtod(m, struct ip *);
628                 using_srcrt = (odst.s_addr != ip->ip_dst.s_addr);
629         }
630
631         if (fw_enable && IPFW_LOADED) {
632                 /*
633                  * If we've been forwarded from the output side, then
634                  * skip the firewall a second time
635                  */
636                 if (args.next_hop)
637                         goto ours;
638
639                 args.m = m;
640                 i = ip_fw_chk_ptr(&args);
641                 m = args.m;
642
643                 if ( (i & IP_FW_PORT_DENY_FLAG) || m == NULL) { /* drop */
644                         if (m)
645                                 m_freem(m);
646                         return;
647                 }
648                 ip = mtod(m, struct ip *); /* just in case m changed */
649                 if (i == 0 && args.next_hop == NULL)    /* common case */
650                         goto pass;
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);
654                         return;
655                 }
656 #ifdef IPDIVERT
657                 if (i != 0 && !(i & IP_FW_PORT_DYNT_FLAG)) {
658                         /* Divert or tee packet */
659                         divert_info = i;
660                         goto ours;
661                 }
662 #endif
663                 if (i == 0 && args.next_hop != NULL)
664                         goto pass;
665                 /*
666                  * if we get here, the packet must be dropped
667                  */
668                 m_freem(m);
669                 return;
670         }
671 pass:
672
673         /*
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).
678          */
679         ip_nhops = 0;           /* for source routed packets */
680         if (hlen > sizeof(struct ip) && ip_dooptions(m, 0, args.next_hop))
681                 return;
682
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.
688          */
689         if (rsvp_on && ip->ip_p == IPPROTO_RSVP)
690                 goto ours;
691
692         /*
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
696          * with it).
697          */
698         if (TAILQ_EMPTY(&in_ifaddrhead) && !(m->m_flags & (M_MCAST | M_BCAST)))
699                 goto ours;
700
701         /*
702          * Cache the destination address of the packet; this may be
703          * changed by use of 'ipfw fwd'.
704          */
705         pkt_dst = args.next_hop ? args.next_hop->sin_addr : ip->ip_dst;
706
707         /*
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
712          * 'ipfw fwd'.
713          *
714          * XXX - Checking also should be disabled if the destination
715          * address is ipnat'ed to a different interface.
716          *
717          * XXX - Checking is incompatible with IP aliases added
718          * to the loopback interface instead of the interface where
719          * the packets are received.
720          */
721         checkif = ip_checkinterface &&
722                   !ipforwarding &&
723                   m->m_pkthdr.rcvif != NULL &&
724                   !(m->m_pkthdr.rcvif->if_flags & IFF_LOOPBACK) &&
725                   (args.next_hop == NULL);
726
727         /*
728          * Check for exact addresses in the hash bucket.
729          */
730         LIST_FOREACH(ia, INADDR_HASH(pkt_dst.s_addr), ia_hash) {
731                 /*
732                  * If the address matches, verify that the packet
733                  * arrived via the correct interface if checking is
734                  * enabled.
735                  */
736                 if (IA_SIN(ia)->sin_addr.s_addr == pkt_dst.s_addr &&
737                     (!checkif || ia->ia_ifp == m->m_pkthdr.rcvif))
738                         goto ours;
739         }
740         /*
741          * Check for broadcast addresses.
742          *
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().
747          */
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 */
751                                 continue;
752                         if (ifa->ifa_addr->sa_family != AF_INET)
753                                 continue;
754                         ia = ifatoia(ifa);
755                         if (satosin(&ia->ia_broadaddr)->sin_addr.s_addr ==
756                                                                 pkt_dst.s_addr)
757                                 goto ours;
758                         if (ia->ia_netbroadcast.s_addr == pkt_dst.s_addr)
759                                 goto ours;
760 #ifdef BOOTP_COMPAT
761                         if (IA_SIN(ia)->sin_addr.s_addr == INADDR_ANY)
762                                 goto ours;
763 #endif
764                 }
765         }
766         if (IN_MULTICAST(ntohl(ip->ip_dst.s_addr))) {
767                 struct in_multi *inm;
768                 if (ip_mrouter) {
769                         /*
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.
776                          */
777                         if (ip_mforward &&
778                             ip_mforward(ip, m->m_pkthdr.rcvif, m, NULL) != 0) {
779                                 ipstat.ips_cantforward++;
780                                 m_freem(m);
781                                 return;
782                         }
783
784                         /*
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.
788                          */
789                         if (ip->ip_p == IPPROTO_IGMP)
790                                 goto ours;
791                         ipstat.ips_forward++;
792                 }
793                 /*
794                  * See if we belong to the destination multicast group on the
795                  * arrival interface.
796                  */
797                 IN_LOOKUP_MULTI(ip->ip_dst, m->m_pkthdr.rcvif, inm);
798                 if (inm == NULL) {
799                         ipstat.ips_notmember++;
800                         m_freem(m);
801                         return;
802                 }
803                 goto ours;
804         }
805         if (ip->ip_dst.s_addr == INADDR_BROADCAST)
806                 goto ours;
807         if (ip->ip_dst.s_addr == INADDR_ANY)
808                 goto ours;
809
810         /*
811          * FAITH(Firewall Aided Internet Translator)
812          */
813         if (m->m_pkthdr.rcvif && m->m_pkthdr.rcvif->if_type == IFT_FAITH) {
814                 if (ip_keepfaith) {
815                         if (ip->ip_p == IPPROTO_TCP || ip->ip_p == IPPROTO_ICMP)
816                                 goto ours;
817                 }
818                 m_freem(m);
819                 return;
820         }
821
822         /*
823          * Not for us; forward if possible and desirable.
824          */
825         if (!ipforwarding) {
826                 ipstat.ips_cantforward++;
827                 m_freem(m);
828         } else {
829 #ifdef IPSEC
830                 /*
831                  * Enforce inbound IPsec SPD.
832                  */
833                 if (ipsec4_in_reject(m, NULL)) {
834                         ipsecstat.in_polvio++;
835                         goto bad;
836                 }
837 #endif
838 #ifdef FAST_IPSEC
839                 mtag = m_tag_find(m, PACKET_TAG_IPSEC_IN_DONE, NULL);
840                 s = splnet();
841                 if (mtag != NULL) {
842                         tdbi = (struct tdb_ident *)(mtag + 1);
843                         sp = ipsec_getpolicy(tdbi, IPSEC_DIR_INBOUND);
844                 } else {
845                         sp = ipsec_getpolicybyaddr(m, IPSEC_DIR_INBOUND,
846                                                    IP_FORWARDING, &error);
847                 }
848                 if (sp == NULL) {       /* NB: can happen if error */
849                         splx(s);
850                         /*XXX error stat???*/
851                         DPRINTF(("ip_input: no SP for forwarding\n"));  /*XXX*/
852                         goto bad;
853                 }
854
855                 /*
856                  * Check security policy against packet attributes.
857                  */
858                 error = ipsec_in_reject(sp, m);
859                 KEY_FREESP(&sp);
860                 splx(s);
861                 if (error) {
862                         ipstat.ips_cantforward++;
863                         goto bad;
864                 }
865 #endif
866                 ip_forward(m, using_srcrt, args.next_hop);
867         }
868         return;
869
870 ours:
871
872         /*
873          * IPSTEALTH: Process non-routing options only
874          * if the packet is destined for us.
875          */
876         if (ipstealth &&
877             hlen > sizeof(struct ip) &&
878             ip_dooptions(m, 1, args.next_hop))
879                 return;
880
881         /* Count the packet in the ip address stats */
882         if (ia != NULL) {
883                 ia->ia_ifa.if_ipackets++;
884                 ia->ia_ifa.if_ibytes += m->m_pkthdr.len;
885         }
886
887         /*
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.)
893          */
894         if (ip->ip_off & (IP_MF | IP_OFFMASK)) {
895
896                 /* If maxnipq is 0, never accept fragments. */
897                 if (maxnipq == 0) {
898                         ipstat.ips_fragments++;
899                         ipstat.ips_fragdropped++;
900                         goto bad;
901                 }
902
903                 sum = IPREASS_HASH(ip->ip_src.s_addr, ip->ip_id);
904                 /*
905                  * Look for queue of fragments
906                  * of this datagram.
907                  */
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)
913                                 goto found;
914
915                 fp = NULL;
916
917                 /*
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.
921                  */
922                 if ((nipq > maxnipq) && (maxnipq > 0)) {
923                         /*
924                          * drop something from the tail of the current queue
925                          * before proceeding further
926                          */
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);
933                                                 break;
934                                         }
935                                 }
936                         } else {
937                                 ipstat.ips_fragtimeout +=
938                                     ipq[sum].prev->ipq_nfrags;
939                                 ip_freef(ipq[sum].prev);
940                         }
941                 }
942 found:
943                 /*
944                  * Adjust ip_len to not reflect header,
945                  * convert offset of this to bytes.
946                  */
947                 ip->ip_len -= hlen;
948                 if (ip->ip_off & IP_MF) {
949                         /*
950                          * Make sure that fragments have a data length
951                          * that's a non-zero multiple of 8 bytes.
952                          */
953                         if (ip->ip_len == 0 || (ip->ip_len & 0x7) != 0) {
954                                 ipstat.ips_toosmall++; /* XXX */
955                                 goto bad;
956                         }
957                         m->m_flags |= M_FRAG;
958                 } else
959                         m->m_flags &= ~M_FRAG;
960                 ip->ip_off <<= 3;
961
962                 /*
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.
966                  */
967                 ipstat.ips_fragments++;
968                 m->m_pkthdr.header = ip;
969                 m = ip_reass(m, fp, &ipq[sum], &divert_info, &args.divert_rule);
970                 if (m == NULL)
971                         return;
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;
977 #ifdef IPDIVERT
978                 /* Restore original checksum before diverting packet */
979                 if (divert_info != 0) {
980                         ip->ip_len += hlen;
981                         ip->ip_len = htons(ip->ip_len);
982                         ip->ip_off = htons(ip->ip_off);
983                         ip->ip_sum = 0;
984                         if (hlen == sizeof(struct ip))
985                                 ip->ip_sum = in_cksum_hdr(ip);
986                         else
987                                 ip->ip_sum = in_cksum(m, hlen);
988                         ip->ip_off = ntohs(ip->ip_off);
989                         ip->ip_len = ntohs(ip->ip_len);
990                         ip->ip_len -= hlen;
991                 }
992 #endif
993         } else {
994                 ip->ip_len -= hlen;
995         }
996
997 #ifdef IPDIVERT
998         /*
999          * Divert or tee packet to the divert protocol if required.
1000          */
1001         if (divert_info != 0) {
1002                 struct mbuf *clone = NULL;
1003
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);
1007
1008                 /* Restore packet header fields to original values */
1009                 ip->ip_len += hlen;
1010                 ip->ip_len = htons(ip->ip_len);
1011                 ip->ip_off = htons(ip->ip_off);
1012
1013                 /* Deliver packet to divert input routine */
1014                 divert_packet(m, 1, divert_info & 0xffff, args.divert_rule);
1015                 ipstat.ips_delivered++;
1016
1017                 /* If 'tee', continue with original packet */
1018                 if (clone == NULL)
1019                         return;
1020                 m = clone;
1021                 ip = mtod(m, struct ip *);
1022                 ip->ip_len += hlen;
1023                 /*
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.
1029                  */
1030                 divert_info = 0;
1031                 goto pass;
1032         }
1033 #endif
1034
1035 #ifdef IPSEC
1036         /*
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.
1040          */
1041         if ((inetsw[ip_protox[ip->ip_p]].pr_flags & PR_LASTHDR) &&
1042             ipsec4_in_reject(m, NULL)) {
1043                 ipsecstat.in_polvio++;
1044                 goto bad;
1045         }
1046 #endif
1047 #if FAST_IPSEC
1048         /*
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.
1052          */
1053         if (inetsw[ip_protox[ip->ip_p]].pr_flags & PR_LASTHDR) {
1054                 /*
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.
1059                  */
1060                 mtag = m_tag_find(m, PACKET_TAG_IPSEC_IN_DONE, NULL);
1061                 s = splnet();
1062                 if (mtag != NULL) {
1063                         tdbi = (struct tdb_ident *)(mtag + 1);
1064                         sp = ipsec_getpolicy(tdbi, IPSEC_DIR_INBOUND);
1065                 } else {
1066                         sp = ipsec_getpolicybyaddr(m, IPSEC_DIR_INBOUND,
1067                                                    IP_FORWARDING, &error);
1068                 }
1069                 if (sp != NULL) {
1070                         /*
1071                          * Check security policy against packet attributes.
1072                          */
1073                         error = ipsec_in_reject(sp, m);
1074                         KEY_FREESP(&sp);
1075                 } else {
1076                         /* XXX error stat??? */
1077                         error = EINVAL;
1078 DPRINTF(("ip_input: no SP, packet discarded\n"));/*XXX*/
1079                         goto bad;
1080                 }
1081                 splx(s);
1082                 if (error)
1083                         goto bad;
1084         }
1085 #endif /* FAST_IPSEC */
1086
1087         ipstat.ips_delivered++;
1088         if (needredispatch) {
1089                 struct netmsg_transport_packet *msg;
1090                 lwkt_port_t port;
1091
1092                 msg = malloc(sizeof(struct netmsg_transport_packet),
1093                                 M_LWKTMSG, M_INTWAIT | M_NULLOK);
1094                 if (msg == NULL)
1095                         goto bad;
1096
1097                 lwkt_initmsg(&msg->nm_lmsg, &netisr_afree_rport, 0,
1098                         lwkt_cmd_func(transport_processing_handler),
1099                         lwkt_cmd_op_none);
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 */
1104
1105                 ip->ip_off = htons(ip->ip_off);
1106                 ip->ip_len = htons(ip->ip_len);
1107                 port = ip_mport(&m);
1108                 if (port) {
1109                     msg->nm_mbuf = 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);
1114                 }
1115         } else {
1116                 transport_processing_oncpu(m, hlen, ip, args.next_hop);
1117         }
1118         return;
1119
1120 bad:
1121         m_freem(m);
1122 }
1123
1124 /*
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.
1128  *
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.
1133  */
1134
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)
1138 {
1139         struct ip *ip = mtod(m, struct ip *);
1140         struct mbuf *p = NULL, *q, *nq;
1141         struct mbuf *n;
1142         int hlen = IP_VHL_HL(ip->ip_vhl) << 2;
1143         int i, next;
1144
1145         /*
1146          * Presence of header sizes in mbufs
1147          * would confuse code below.
1148          */
1149         m->m_data += hlen;
1150         m->m_len -= hlen;
1151
1152         /*
1153          * If first fragment to arrive, create a reassembly queue.
1154          */
1155         if (fp == NULL) {
1156                 if ((fp = mpipe_alloc_nowait(&ipq_mpipe)) == NULL)
1157                         goto dropfrag;
1158                 insque(fp, where);
1159                 nipq++;
1160                 fp->ipq_nfrags = 1;
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;
1166                 fp->ipq_frags = m;
1167                 m->m_nextpkt = NULL;
1168 #ifdef IPDIVERT
1169                 fp->ipq_div_info = 0;
1170                 fp->ipq_div_cookie = 0;
1171 #endif
1172                 goto inserted;
1173         } else {
1174                 fp->ipq_nfrags++;
1175         }
1176
1177 #define GETIP(m)        ((struct ip*)((m)->m_pkthdr.header))
1178
1179         /*
1180          * Find a segment which begins after this one does.
1181          */
1182         for (p = NULL, q = fp->ipq_frags; q; p = q, q = q->m_nextpkt)
1183                 if (GETIP(q)->ip_off > ip->ip_off)
1184                         break;
1185
1186         /*
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.
1191          *
1192          * If some of the data is dropped from the the preceding
1193          * segment, then it's checksum is invalidated.
1194          */
1195         if (p) {
1196                 i = GETIP(p)->ip_off + GETIP(p)->ip_len - ip->ip_off;
1197                 if (i > 0) {
1198                         if (i >= ip->ip_len)
1199                                 goto dropfrag;
1200                         m_adj(m, i);
1201                         m->m_pkthdr.csum_flags = 0;
1202                         ip->ip_off += i;
1203                         ip->ip_len -= i;
1204                 }
1205                 m->m_nextpkt = p->m_nextpkt;
1206                 p->m_nextpkt = m;
1207         } else {
1208                 m->m_nextpkt = fp->ipq_frags;
1209                 fp->ipq_frags = m;
1210         }
1211
1212         /*
1213          * While we overlap succeeding segments trim them or,
1214          * if they are completely covered, dequeue them.
1215          */
1216         for (; q != NULL && ip->ip_off + ip->ip_len > GETIP(q)->ip_off;
1217              q = nq) {
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;
1222                         m_adj(q, i);
1223                         q->m_pkthdr.csum_flags = 0;
1224                         break;
1225                 }
1226                 nq = q->m_nextpkt;
1227                 m->m_nextpkt = nq;
1228                 ipstat.ips_fragdropped++;
1229                 fp->ipq_nfrags--;
1230                 m_freem(q);
1231         }
1232
1233 inserted:
1234
1235 #ifdef IPDIVERT
1236         /*
1237          * Transfer firewall instructions to the fragment structure.
1238          * Only trust info in the fragment at offset 0.
1239          */
1240         if (ip->ip_off == 0) {
1241                 fp->ipq_div_info = *divinfo;
1242                 fp->ipq_div_cookie = *divert_rule;
1243         }
1244         *divinfo = 0;
1245         *divert_rule = 0;
1246 #endif
1247
1248         /*
1249          * Check for complete reassembly and perform frag per packet
1250          * limiting.
1251          *
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.)
1256          *
1257          */
1258         next = 0;
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;
1263                                 ip_freef(fp);
1264                         }
1265                         return (NULL);
1266                 }
1267                 next += GETIP(q)->ip_len;
1268         }
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;
1273                         ip_freef(fp);
1274                 }
1275                 return (NULL);
1276         }
1277
1278         /*
1279          * Reassembly is complete.  Make sure the packet is a sane size.
1280          */
1281         q = fp->ipq_frags;
1282         ip = GETIP(q);
1283         if (next + (IP_VHL_HL(ip->ip_vhl) << 2) > IP_MAXPACKET) {
1284                 ipstat.ips_toolong++;
1285                 ipstat.ips_fragdropped += fp->ipq_nfrags;
1286                 ip_freef(fp);
1287                 return (NULL);
1288         }
1289
1290         /*
1291          * Concatenate fragments.
1292          */
1293         m = q;
1294         n = m->m_next;
1295         m->m_next = NULL;
1296         m_cat(m, n);
1297         nq = q->m_nextpkt;
1298         q->m_nextpkt = NULL;
1299         for (q = nq; q != NULL; q = nq) {
1300                 nq = q->m_nextpkt;
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;
1304                 m_cat(m, q);
1305         }
1306
1307 #ifdef IPDIVERT
1308         /*
1309          * Extract firewall instructions from the fragment structure.
1310          */
1311         *divinfo = fp->ipq_div_info;
1312         *divert_rule = fp->ipq_div_cookie;
1313 #endif
1314
1315         /*
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.
1320          */
1321         ip->ip_len = next;
1322         ip->ip_src = fp->ipq_src;
1323         ip->ip_dst = fp->ipq_dst;
1324         remque(fp);
1325         nipq--;
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 */
1331                 int plen = 0;
1332
1333                 for (n = m; n; n = n->m_next)
1334                         plen += n->m_len;
1335                 m->m_pkthdr.len = plen;
1336         }
1337         return (m);
1338
1339 dropfrag:
1340 #ifdef IPDIVERT
1341         *divinfo = 0;
1342         *divert_rule = 0;
1343 #endif
1344         ipstat.ips_fragdropped++;
1345         if (fp != NULL)
1346                 fp->ipq_nfrags--;
1347         m_freem(m);
1348         return (NULL);
1349
1350 #undef GETIP
1351 }
1352
1353 /*
1354  * Free a fragment reassembly header and all
1355  * associated datagrams.
1356  */
1357 static void
1358 ip_freef(struct ipq *fp)
1359 {
1360         struct mbuf *q;
1361
1362         while (fp->ipq_frags) {
1363                 q = fp->ipq_frags;
1364                 fp->ipq_frags = q->m_nextpkt;
1365                 m_freem(q);
1366         }
1367         remque(fp);
1368         mpipe_free(&ipq_mpipe, fp);
1369         nipq--;
1370 }
1371
1372 /*
1373  * IP timer processing;
1374  * if a timer expires on a reassembly
1375  * queue, discard it.
1376  */
1377 void
1378 ip_slowtimo(void)
1379 {
1380         struct ipq *fp;
1381         int s = splnet();
1382         int i;
1383
1384         for (i = 0; i < IPREASS_NHASH; i++) {
1385                 fp = ipq[i].next;
1386                 if (fp == NULL)
1387                         continue;
1388                 while (fp != &ipq[i]) {
1389                         --fp->ipq_ttl;
1390                         fp = fp->next;
1391                         if (fp->prev->ipq_ttl == 0) {
1392                                 ipstat.ips_fragtimeout += fp->prev->ipq_nfrags;
1393                                 ip_freef(fp->prev);
1394                         }
1395                 }
1396         }
1397         /*
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.
1401          */
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);
1409                         }
1410                 }
1411         }
1412         ipflow_slowtimo();
1413         splx(s);
1414 }
1415
1416 /*
1417  * Drain off all datagram fragments.
1418  */
1419 void
1420 ip_drain(void)
1421 {
1422         int i;
1423
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);
1428                 }
1429         }
1430         in_rtqdrain();
1431 }
1432
1433 /*
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.
1444  */
1445 static int
1446 ip_dooptions(struct mbuf *m, int pass, struct sockaddr_in *next_hop)
1447 {
1448         struct ip *ip = mtod(m, struct ip *);
1449         u_char *cp;
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;
1454         n_time ntime;
1455
1456         dst = ip->ip_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)
1462                         break;
1463                 if (opt == IPOPT_NOP)
1464                         optlen = 1;
1465                 else {
1466                         if (cnt < IPOPT_OLEN + sizeof(*cp)) {
1467                                 code = &cp[IPOPT_OLEN] - (u_char *)ip;
1468                                 goto bad;
1469                         }
1470                         optlen = cp[IPOPT_OLEN];
1471                         if (optlen < IPOPT_OLEN + sizeof(*cp) || optlen > cnt) {
1472                                 code = &cp[IPOPT_OLEN] - (u_char *)ip;
1473                                 goto bad;
1474                         }
1475                 }
1476                 switch (opt) {
1477
1478                 default:
1479                         break;
1480
1481                 /*
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.
1489                  */
1490                 case IPOPT_LSRR:
1491                 case IPOPT_SSRR:
1492                         if (ipstealth && pass > 0)
1493                                 break;
1494                         if (optlen < IPOPT_OFFSET + sizeof(*cp)) {
1495                                 code = &cp[IPOPT_OLEN] - (u_char *)ip;
1496                                 goto bad;
1497                         }
1498                         if ((off = cp[IPOPT_OFFSET]) < IPOPT_MINOFF) {
1499                                 code = &cp[IPOPT_OFFSET] - (u_char *)ip;
1500                                 goto bad;
1501                         }
1502                         ipaddr.sin_addr = ip->ip_dst;
1503                         ia = (struct in_ifaddr *)
1504                                 ifa_ifwithaddr((struct sockaddr *)&ipaddr);
1505                         if (ia == NULL) {
1506                                 if (opt == IPOPT_SSRR) {
1507                                         type = ICMP_UNREACH;
1508                                         code = ICMP_UNREACH_SRCFAIL;
1509                                         goto bad;
1510                                 }
1511                                 if (!ip_dosourceroute)
1512                                         goto nosourcerouting;
1513                                 /*
1514                                  * Loose routing, and not at next destination
1515                                  * yet; nothing to do except forward.
1516                                  */
1517                                 break;
1518                         }
1519                         off--;                  /* 0 origin */
1520                         if (off > optlen - (int)sizeof(struct in_addr)) {
1521                                 /*
1522                                  * End of source route.  Should be for us.
1523                                  */
1524                                 if (!ip_acceptsourceroute)
1525                                         goto nosourcerouting;
1526                                 save_rte(cp, ip->ip_src);
1527                                 break;
1528                         }
1529                         if (ipstealth)
1530                                 goto dropit;
1531                         if (!ip_dosourceroute) {
1532                                 if (ipforwarding) {
1533                                         char buf[16]; /* aaa.bbb.ccc.ddd\0 */
1534                                         /*
1535                                          * Acting as a router, so generate ICMP
1536                                          */
1537 nosourcerouting:
1538                                         strcpy(buf, inet_ntoa(ip->ip_dst));
1539                                         log(LOG_WARNING,
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;
1544                                         goto bad;
1545                                 } else {
1546                                         /*
1547                                          * Not acting as a router,
1548                                          * so silently drop.
1549                                          */
1550 dropit:
1551                                         ipstat.ips_cantforward++;
1552                                         m_freem(m);
1553                                         return (1);
1554                                 }
1555                         }
1556
1557                         /*
1558                          * locate outgoing interface
1559                          */
1560                         memcpy(&ipaddr.sin_addr, cp + off,
1561                             sizeof ipaddr.sin_addr);
1562
1563                         if (opt == IPOPT_SSRR) {
1564 #define INA     struct in_ifaddr *
1565 #define SA      struct sockaddr *
1566                                 if ((ia = (INA)ifa_ifwithdstaddr((SA)&ipaddr))
1567                                                                         == NULL)
1568                                         ia = (INA)ifa_ifwithnet((SA)&ipaddr);
1569                         } else
1570                                 ia = ip_rtaddr(ipaddr.sin_addr, &ipforward_rt);
1571                         if (ia == NULL) {
1572                                 type = ICMP_UNREACH;
1573                                 code = ICMP_UNREACH_SRCFAIL;
1574                                 goto bad;
1575                         }
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);
1580                         /*
1581                          * Let ip_intr's mcast routing check handle mcast pkts
1582                          */
1583                         forward = !IN_MULTICAST(ntohl(ip->ip_dst.s_addr));
1584                         break;
1585
1586                 case IPOPT_RR:
1587                         if (ipstealth && pass == 0)
1588                                 break;
1589                         if (optlen < IPOPT_OFFSET + sizeof(*cp)) {
1590                                 code = &cp[IPOPT_OFFSET] - (u_char *)ip;
1591                                 goto bad;
1592                         }
1593                         if ((off = cp[IPOPT_OFFSET]) < IPOPT_MINOFF) {
1594                                 code = &cp[IPOPT_OFFSET] - (u_char *)ip;
1595                                 goto bad;
1596                         }
1597                         /*
1598                          * If no space remains, ignore.
1599                          */
1600                         off--;                  /* 0 origin */
1601                         if (off > optlen - (int)sizeof(struct in_addr))
1602                                 break;
1603                         memcpy(&ipaddr.sin_addr, &ip->ip_dst,
1604                             sizeof ipaddr.sin_addr);
1605                         /*
1606                          * locate outgoing interface; if we're the destination,
1607                          * use the incoming interface (should be same).
1608                          */
1609                         if ((ia = (INA)ifa_ifwithaddr((SA)&ipaddr)) == NULL &&
1610                             (ia = ip_rtaddr(ipaddr.sin_addr, &ipforward_rt))
1611                                                                      == NULL) {
1612                                 type = ICMP_UNREACH;
1613                                 code = ICMP_UNREACH_HOST;
1614                                 goto bad;
1615                         }
1616                         memcpy(cp + off, &IA_SIN(ia)->sin_addr,
1617                             sizeof(struct in_addr));
1618                         cp[IPOPT_OFFSET] += sizeof(struct in_addr);
1619                         break;
1620
1621                 case IPOPT_TS:
1622                         if (ipstealth && pass == 0)
1623                                 break;
1624                         code = cp - (u_char *)ip;
1625                         if (optlen < 4 || optlen > 40) {
1626                                 code = &cp[IPOPT_OLEN] - (u_char *)ip;
1627                                 goto bad;
1628                         }
1629                         if ((off = cp[IPOPT_OFFSET]) < 5) {
1630                                 code = &cp[IPOPT_OLEN] - (u_char *)ip;
1631                                 goto bad;
1632                         }
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;
1637                                         goto bad;
1638                                 }
1639                                 break;
1640                         }
1641                         off--;                          /* 0 origin */
1642                         sin = (struct in_addr *)(cp + off);
1643                         switch (cp[IPOPT_OFFSET + 1] & 0x0f) {
1644
1645                         case IPOPT_TS_TSONLY:
1646                                 break;
1647
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;
1652                                         goto bad;
1653                                 }
1654                                 ipaddr.sin_addr = dst;
1655                                 ia = (INA)ifaof_ifpforaddr((SA)&ipaddr,
1656                                                             m->m_pkthdr.rcvif);
1657                                 if (ia == NULL)
1658                                         continue;
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);
1663                                 break;
1664
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;
1669                                         goto bad;
1670                                 }
1671                                 memcpy(&ipaddr.sin_addr, sin,
1672                                     sizeof(struct in_addr));
1673                                 if (ifa_ifwithaddr((SA)&ipaddr) == NULL)
1674                                         continue;
1675                                 cp[IPOPT_OFFSET] += sizeof(struct in_addr);
1676                                 off += sizeof(struct in_addr);
1677                                 break;
1678
1679                         default:
1680                                 code = &cp[IPOPT_OFFSET + 1] - (u_char *)ip;
1681                                 goto bad;
1682                         }
1683                         ntime = iptime();
1684                         memcpy(cp + off, &ntime, sizeof(n_time));
1685                         cp[IPOPT_OFFSET] += sizeof(n_time);
1686                 }
1687         }
1688         if (forward && ipforwarding) {
1689                 ip_forward(m, 1, next_hop);
1690                 return (1);
1691         }
1692         return (0);
1693 bad:
1694         icmp_error(m, type, code, 0, NULL);
1695         ipstat.ips_badoptions++;
1696         return (1);
1697 }
1698
1699 /*
1700  * Given address of next destination (final or next hop),
1701  * return internet address info of interface to be used to get there.
1702  */
1703 struct in_ifaddr *
1704 ip_rtaddr(struct in_addr dst, struct route *rt)
1705 {
1706         struct sockaddr_in *sin;
1707
1708         sin = (struct sockaddr_in *)&rt->ro_dst;
1709
1710         if (rt->ro_rt == NULL || dst.s_addr != sin->sin_addr.s_addr) {
1711                 if (rt->ro_rt != NULL) {
1712                         RTFREE(rt->ro_rt);
1713                         rt->ro_rt = NULL;
1714                 }
1715                 sin->sin_family = AF_INET;
1716                 sin->sin_len = sizeof(*sin);
1717                 sin->sin_addr = dst;
1718                 rtalloc_ign(rt, RTF_PRCLONING);
1719         }
1720
1721         if (rt->ro_rt == NULL)
1722                 return (NULL);
1723
1724         return (ifatoia(rt->ro_rt->rt_ifa));
1725 }
1726
1727 /*
1728  * Save incoming source route for use in replies,
1729  * to be picked up later by ip_srcroute if the receiver is interested.
1730  */
1731 void
1732 save_rte(u_char *option, struct in_addr dst)
1733 {
1734         unsigned olen;
1735
1736         olen = option[IPOPT_OLEN];
1737 #ifdef DIAGNOSTIC
1738         if (ipprintfs)
1739                 printf("save_rte: olen %d\n", olen);
1740 #endif
1741         if (olen > sizeof(ip_srcrt) - (1 + sizeof(dst)))
1742                 return;
1743         bcopy(option, ip_srcrt.srcopt, olen);
1744         ip_nhops = (olen - IPOPT_OFFSET - 1) / sizeof(struct in_addr);
1745         ip_srcrt.dst = dst;
1746 }
1747
1748 /*
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.
1752  */
1753 struct mbuf *
1754 ip_srcroute(void)
1755 {
1756         struct in_addr *p, *q;
1757         struct mbuf *m;
1758
1759         if (ip_nhops == 0)
1760                 return (NULL);
1761         m = m_get(MB_DONTWAIT, MT_HEADER);
1762         if (m == NULL)
1763                 return (NULL);
1764
1765 #define OPTSIZ  (sizeof(ip_srcrt.nop) + sizeof(ip_srcrt.srcopt))
1766
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) +
1769             OPTSIZ;
1770 #ifdef DIAGNOSTIC
1771         if (ipprintfs)
1772                 printf("ip_srcroute: nhops %d mlen %d", ip_nhops, m->m_len);
1773 #endif
1774
1775         /*
1776          * First save first hop for return route
1777          */
1778         p = &ip_srcrt.route[ip_nhops - 1];
1779         *(mtod(m, struct in_addr *)) = *p--;
1780 #ifdef DIAGNOSTIC
1781         if (ipprintfs)
1782                 printf(" hops %x", ntohl(mtod(m, struct in_addr *)->s_addr));
1783 #endif
1784
1785         /*
1786          * Copy option fields and padding (nop) to mbuf.
1787          */
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,
1791             OPTSIZ);
1792         q = (struct in_addr *)(mtod(m, caddr_t) +
1793             sizeof(struct in_addr) + OPTSIZ);
1794 #undef OPTSIZ
1795         /*
1796          * Record return path as an IP source route,
1797          * reversing the path (pointers are now aligned).
1798          */
1799         while (p >= ip_srcrt.route) {
1800 #ifdef DIAGNOSTIC
1801                 if (ipprintfs)
1802                         printf(" %x", ntohl(q->s_addr));
1803 #endif
1804                 *q++ = *p--;
1805         }
1806         /*
1807          * Last hop goes to final destination.
1808          */
1809         *q = ip_srcrt.dst;
1810 #ifdef DIAGNOSTIC
1811         if (ipprintfs)
1812                 printf(" %x\n", ntohl(q->s_addr));
1813 #endif
1814         return (m);
1815 }
1816
1817 /*
1818  * Strip out IP options.
1819  */
1820 void
1821 ip_stripoptions(struct mbuf *m)
1822 {
1823         int datalen;
1824         struct ip *ip = mtod(m, struct ip *);
1825         caddr_t opts;
1826         int optlen;
1827
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);
1832         m->m_len -= optlen;
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);
1836 }
1837
1838 u_char inetctlerrmap[PRC_NCMDS] = {
1839         0,              0,              0,              0,
1840         0,              EMSGSIZE,       EHOSTDOWN,      EHOSTUNREACH,
1841         EHOSTUNREACH,   EHOSTUNREACH,   ECONNREFUSED,   ECONNREFUSED,
1842         EMSGSIZE,       EHOSTUNREACH,   0,              0,
1843         0,              0,              0,              0,
1844         ENOPROTOOPT,    ECONNREFUSED
1845 };
1846
1847 /*
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.
1852  *
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.
1857  *
1858  * The using_srcrt parameter indicates whether the packet is being forwarded
1859  * via a source route.
1860  */
1861 static void
1862 ip_forward(struct mbuf *m, int using_srcrt, struct sockaddr_in *next_hop)
1863 {
1864         struct ip *ip = mtod(m, struct ip *);
1865         struct sockaddr_in *sin;
1866         struct rtentry *rt;
1867         int error, type = 0, code = 0;
1868         struct mbuf *mcopy;
1869         n_long dest;
1870         struct in_addr pkt_dst;
1871         struct ifnet *destifp;
1872         struct m_hdr tag;
1873 #if defined(IPSEC) || defined(FAST_IPSEC)
1874         struct ifnet dummyifp;
1875 #endif
1876
1877         dest = 0;
1878         /*
1879          * Cache the destination address of the packet; this may be
1880          * changed by use of 'ipfw fwd'.
1881          */
1882         pkt_dst = next_hop ? next_hop->sin_addr : ip->ip_dst;
1883
1884 #ifdef DIAGNOSTIC
1885         if (ipprintfs)
1886                 printf("forward: src %x dst %x ttl %x\n",
1887                        ip->ip_src.s_addr, pkt_dst.s_addr, ip->ip_ttl);
1888 #endif
1889
1890         if (m->m_flags & (M_BCAST | M_MCAST) || !in_canforward(pkt_dst)) {
1891                 ipstat.ips_cantforward++;
1892                 m_freem(m);
1893                 return;
1894         }
1895         if (!ipstealth && ip->ip_ttl <= IPTTLDEC) {
1896                 icmp_error(m, ICMP_TIMXCEED, ICMP_TIMXCEED_INTRANS, dest, NULL);
1897                 return;
1898         }
1899
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;
1906                 }
1907                 sin->sin_family = AF_INET;
1908                 sin->sin_len = sizeof(*sin);
1909                 sin->sin_addr = pkt_dst;
1910
1911                 rtalloc_ign(&ipforward_rt, RTF_PRCLONING);
1912                 if (ipforward_rt.ro_rt == NULL) {
1913                         icmp_error(m, ICMP_UNREACH, ICMP_UNREACH_HOST, dest,
1914                                    NULL);
1915                         return;
1916                 }
1917                 rt = ipforward_rt.ro_rt;
1918         }
1919
1920         /*
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.
1923          *
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.
1930          *
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().
1935          */
1936         MGET(mcopy, MB_DONTWAIT, m->m_type);
1937         if (mcopy != NULL && !m_dup_pkthdr(mcopy, m, MB_DONTWAIT)) {
1938                 /*
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.
1943                  */
1944                 m_free(mcopy);
1945                 mcopy = NULL;
1946         }
1947         if (mcopy != NULL) {
1948                 mcopy->m_len = imin((IP_VHL_HL(ip->ip_vhl) << 2) + 8,
1949                     (int)ip->ip_len);
1950                 mcopy->m_pkthdr.len = mcopy->m_len;
1951                 m_copydata(m, 0, mcopy->m_len, mtod(mcopy, caddr_t));
1952         }
1953
1954         if (!ipstealth)
1955                 ip->ip_ttl -= IPTTLDEC;
1956
1957         /*
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.
1964          */
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);
1970
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;
1976                         else
1977                                 dest = pkt_dst.s_addr;
1978                         /*
1979                          * Router requirements says to only send
1980                          * host redirects.
1981                          */
1982                         type = ICMP_REDIRECT;
1983                         code = ICMP_REDIRECT_HOST;
1984 #ifdef DIAGNOSTIC
1985                         if (ipprintfs)
1986                                 printf("redirect (%d) to %x\n", code, dest);
1987 #endif
1988                 }
1989         }
1990
1991         if (next_hop) {
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;
1996                 tag.mh_next = m;
1997                 m = (struct mbuf *)&tag;
1998         }
1999
2000         error = ip_output(m, NULL, &ipforward_rt, IP_FORWARDING, NULL, NULL);
2001
2002         if (error)
2003                 ipstat.ips_cantforward++;
2004         else {
2005                 ipstat.ips_forward++;
2006                 if (type)
2007                         ipstat.ips_redirectsent++;
2008                 else {
2009                         if (mcopy) {
2010                                 ipflow_create(&ipforward_rt, mcopy);
2011                                 m_freem(mcopy);
2012                         }
2013                         return;
2014                 }
2015         }
2016         if (mcopy == NULL)
2017                 return;
2018         destifp = NULL;
2019
2020         switch (error) {
2021
2022         case 0:                         /* forwarded, but need redirect */
2023                 /* type, code set above */
2024                 break;
2025
2026         case ENETUNREACH:               /* shouldn't happen, checked above */
2027         case EHOSTUNREACH:
2028         case ENETDOWN:
2029         case EHOSTDOWN:
2030         default:
2031                 type = ICMP_UNREACH;
2032                 code = ICMP_UNREACH_HOST;
2033                 break;
2034
2035         case EMSGSIZE:
2036                 type = ICMP_UNREACH;
2037                 code = ICMP_UNREACH_NEEDFRAG;
2038 #ifdef IPSEC
2039                 /*
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
2043                  * XXX quickhack!!!
2044                  */
2045                 if (ipforward_rt.ro_rt != NULL) {
2046                         struct secpolicy *sp = NULL;
2047                         int ipsecerror;
2048                         int ipsechdr;
2049                         struct route *ro;
2050
2051                         sp = ipsec4_getpolicybyaddr(mcopy,
2052                                                     IPSEC_DIR_OUTBOUND,
2053                                                     IP_FORWARDING,
2054                                                     &ipsecerror);
2055
2056                         if (sp == NULL)
2057                                 destifp = ipforward_rt.ro_rt->rt_ifp;
2058                         else {
2059                                 /* count IPsec header size */
2060                                 ipsechdr = ipsec4_hdrsiz(mcopy,
2061                                                          IPSEC_DIR_OUTBOUND,
2062                                                          NULL);
2063
2064                                 /*
2065                                  * find the correct route for outer IPv4
2066                                  * header, compute tunnel MTU.
2067                                  *
2068                                  * XXX BUG ALERT
2069                                  * The "dummyifp" code relies upon the fact
2070                                  * that icmp_error() touches only ifp->if_mtu.
2071                                  */
2072                                 /*XXX*/
2073                                 destifp = NULL;
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) {
2079                                                 dummyifp.if_mtu =
2080                                                     ro->ro_rt->rt_ifp->if_mtu;
2081                                                 dummyifp.if_mtu -= ipsechdr;
2082                                                 destifp = &dummyifp;
2083                                         }
2084                                 }
2085
2086                                 key_freesp(sp);
2087                         }
2088                 }
2089 #elif FAST_IPSEC
2090                 /*
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
2094                  * XXX quickhack!!!
2095                  */
2096                 if (ipforward_rt.ro_rt != NULL) {
2097                         struct secpolicy *sp = NULL;
2098                         int ipsecerror;
2099                         int ipsechdr;
2100                         struct route *ro;
2101
2102                         sp = ipsec_getpolicybyaddr(mcopy,
2103                                                    IPSEC_DIR_OUTBOUND,
2104                                                    IP_FORWARDING,
2105                                                    &ipsecerror);
2106
2107                         if (sp == NULL)
2108                                 destifp = ipforward_rt.ro_rt->rt_ifp;
2109                         else {
2110                                 /* count IPsec header size */
2111                                 ipsechdr = ipsec4_hdrsiz(mcopy,
2112                                                          IPSEC_DIR_OUTBOUND,
2113                                                          NULL);
2114
2115                                 /*
2116                                  * find the correct route for outer IPv4
2117                                  * header, compute tunnel MTU.
2118                                  *
2119                                  * XXX BUG ALERT
2120                                  * The "dummyifp" code relies upon the fact
2121                                  * that icmp_error() touches only ifp->if_mtu.
2122                                  */
2123                                 /*XXX*/
2124                                 destifp = NULL;
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) {
2131                                                 dummyifp.if_mtu =
2132                                                     ro->ro_rt->rt_ifp->if_mtu;
2133                                                 dummyifp.if_mtu -= ipsechdr;
2134                                                 destifp = &dummyifp;
2135                                         }
2136                                 }
2137
2138                                 KEY_FREESP(&sp);
2139                         }
2140                 }
2141 #else /* !IPSEC && !FAST_IPSEC */
2142                 if (ipforward_rt.ro_rt != NULL)
2143                         destifp = ipforward_rt.ro_rt->rt_ifp;
2144 #endif /*IPSEC*/
2145                 ipstat.ips_cantfrag++;
2146                 break;
2147
2148         case ENOBUFS:
2149                 /*
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.
2156                  */
2157                 if (!ip_sendsourcequench) {
2158                         m_freem(mcopy);
2159                         return;
2160                 } else {
2161                         type = ICMP_SOURCEQUENCH;
2162                         code = 0;
2163                 }
2164                 break;
2165
2166         case EACCES:                    /* ipfw denied packet */
2167                 m_freem(mcopy);
2168                 return;
2169         }
2170         icmp_error(mcopy, type, code, dest, destifp);
2171 }
2172
2173 void
2174 ip_savecontrol(struct inpcb *inp, struct mbuf **mp, struct ip *ip,
2175                struct mbuf *m)
2176 {
2177         if (inp->inp_socket->so_options & SO_TIMESTAMP) {
2178                 struct timeval tv;
2179
2180                 microtime(&tv);
2181                 *mp = sbcreatecontrol((caddr_t) &tv, sizeof(tv),
2182                     SCM_TIMESTAMP, SOL_SOCKET);
2183                 if (*mp)
2184                         mp = &(*mp)->m_next;
2185         }
2186         if (inp->inp_flags & INP_RECVDSTADDR) {
2187                 *mp = sbcreatecontrol((caddr_t) &ip->ip_dst,
2188                     sizeof(struct in_addr), IP_RECVDSTADDR, IPPROTO_IP);
2189                 if (*mp)
2190                         mp = &(*mp)->m_next;
2191         }
2192 #ifdef notyet
2193         /* XXX
2194          * Moving these out of udp_input() made them even more broken
2195          * than they already were.
2196          */
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);
2201                 if (*mp)
2202                         mp = &(*mp)->m_next;
2203         }
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);
2208                 if (*mp)
2209                         mp = &(*mp)->m_next;
2210         }
2211 #endif
2212         if (inp->inp_flags & INP_RECVIF) {
2213                 struct ifnet *ifp;
2214                 struct sdlbuf {
2215                         struct sockaddr_dl sdl;
2216                         u_char  pad[32];
2217                 } sdlbuf;
2218                 struct sockaddr_dl *sdp;
2219                 struct sockaddr_dl *sdl2 = &sdlbuf.sdl;
2220
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;
2225                         /*
2226                          * Change our mind and don't try copy.
2227                          */
2228                         if ((sdp->sdl_family != AF_LINK) ||
2229                             (sdp->sdl_len > sizeof(sdlbuf))) {
2230                                 goto makedummy;
2231                         }
2232                         bcopy(sdp, sdl2, sdp->sdl_len);
2233                 } else {
2234 makedummy:
2235                         sdl2->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;
2240                 }
2241                 *mp = sbcreatecontrol((caddr_t) sdl2, sdl2->sdl_len,
2242                         IP_RECVIF, IPPROTO_IP);
2243                 if (*mp)
2244                         mp = &(*mp)->m_next;
2245         }
2246 }
2247
2248 /*
2249  * XXX these routines are called from the upper part of the kernel.
2250  *
2251  * They could also be moved to ip_mroute.c, since all the RSVP
2252  *  handling is done there already.
2253  */
2254 int
2255 ip_rsvp_init(struct socket *so)
2256 {
2257         if (so->so_type != SOCK_RAW ||
2258             so->so_proto->pr_protocol != IPPROTO_RSVP)
2259                 return EOPNOTSUPP;
2260
2261         if (ip_rsvpd != NULL)
2262                 return EADDRINUSE;
2263
2264         ip_rsvpd = so;
2265         /*
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.
2268          */
2269         if (!ip_rsvp_on) {
2270                 ip_rsvp_on = 1;
2271                 rsvp_on++;
2272         }
2273
2274         return 0;
2275 }
2276
2277 int
2278 ip_rsvp_done(void)
2279 {
2280         ip_rsvpd = NULL;
2281         /*
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.
2284          */
2285         if (ip_rsvp_on) {
2286                 ip_rsvp_on = 0;
2287                 rsvp_on--;
2288         }
2289         return 0;
2290 }
2291
2292 void
2293 rsvp_input(struct mbuf *m, ...) /* XXX must fixup manually */
2294 {
2295         int off, proto;
2296         __va_list ap;
2297
2298         __va_start(ap, m);
2299         off = __va_arg(ap, int);
2300         proto = __va_arg(ap, int);
2301         __va_end(ap);
2302
2303         if (rsvp_input_p) { /* call the real one if loaded */
2304                 rsvp_input_p(m, off, proto);
2305                 return;
2306         }
2307
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.
2311          */
2312
2313         if (!rsvp_on) {
2314                 m_freem(m);
2315                 return;
2316         }
2317
2318         if (ip_rsvpd != NULL) {
2319                 rip_input(m, off, proto);
2320                 return;
2321         }
2322         /* Drop the packet */
2323         m_freem(m);
2324 }