Make IP statistics counters per-CPU so they can be updated safely.
[dragonfly.git] / sys / netinet / ip_input.c
1 /*
2  * Copyright (c) 1982, 1986, 1988, 1993
3  *      The Regents of the University of California.  All rights reserved.
4  *
5  * Redistribution and use in source and binary forms, with or without
6  * modification, are permitted provided that the following conditions
7  * are met:
8  * 1. Redistributions of source code must retain the above copyright
9  *    notice, this list of conditions and the following disclaimer.
10  * 2. Redistributions in binary form must reproduce the above copyright
11  *    notice, this list of conditions and the following disclaimer in the
12  *    documentation and/or other materials provided with the distribution.
13  * 3. All advertising materials mentioning features or use of this software
14  *    must display the following acknowledgement:
15  *      This product includes software developed by the University of
16  *      California, Berkeley and its contributors.
17  * 4. Neither the name of the University nor the names of its contributors
18  *    may be used to endorse or promote products derived from this software
19  *    without specific prior written permission.
20  *
21  * THIS SOFTWARE IS PROVIDED BY THE REGENTS AND CONTRIBUTORS ``AS IS'' AND
22  * ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
23  * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE
24  * ARE DISCLAIMED.  IN NO EVENT SHALL THE REGENTS OR CONTRIBUTORS BE LIABLE
25  * FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL
26  * DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS
27  * OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION)
28  * HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT
29  * LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY
30  * OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF
31  * SUCH DAMAGE.
32  *
33  *      @(#)ip_input.c  8.2 (Berkeley) 1/4/94
34  * $FreeBSD: src/sys/netinet/ip_input.c,v 1.130.2.52 2003/03/07 07:01:28 silby Exp $
35  * $DragonFly: src/sys/netinet/ip_input.c,v 1.24 2004/05/03 15:18:25 hmp Exp $
36  */
37
38 #define _IP_VHL
39
40 #include "opt_bootp.h"
41 #include "opt_ipfw.h"
42 #include "opt_ipdn.h"
43 #include "opt_ipdivert.h"
44 #include "opt_ipfilter.h"
45 #include "opt_ipstealth.h"
46 #include "opt_ipsec.h"
47 #include "opt_pfil_hooks.h"
48 #include "opt_random_ip_id.h"
49
50 #include <sys/param.h>
51 #include <sys/systm.h>
52 #include <sys/mbuf.h>
53 #include <sys/malloc.h>
54 #include <sys/domain.h>
55 #include <sys/protosw.h>
56 #include <sys/socket.h>
57 #include <sys/time.h>
58 #include <sys/globaldata.h>
59 #include <sys/thread.h>
60 #include <sys/kernel.h>
61 #include <sys/syslog.h>
62 #include <sys/sysctl.h>
63 #include <sys/in_cksum.h>
64
65 #include <sys/thread2.h>
66 #include <sys/msgport2.h>
67
68 #include <net/if.h>
69 #include <net/if_types.h>
70 #include <net/if_var.h>
71 #include <net/if_dl.h>
72 #ifdef PFIL_HOOKS
73 #include <net/pfil.h>
74 #endif
75 #include <net/route.h>
76 #include <net/netisr.h>
77 #include <net/intrq.h>
78
79 #include <netinet/in.h>
80 #include <netinet/in_systm.h>
81 #include <netinet/in_var.h>
82 #include <netinet/ip.h>
83 #include <netinet/in_pcb.h>
84 #include <netinet/ip_var.h>
85 #include <netinet/ip_icmp.h>
86
87 #include <netinet/ipprotosw.h>
88
89 #include <sys/socketvar.h>
90
91 #include <net/ipfw/ip_fw.h>
92 #include <net/dummynet/ip_dummynet.h>
93
94 #ifdef IPSEC
95 #include <netinet6/ipsec.h>
96 #include <netproto/key/key.h>
97 #endif
98
99 #ifdef FAST_IPSEC
100 #include <netipsec/ipsec.h>
101 #include <netipsec/key.h>
102 #endif
103
104 int rsvp_on = 0;
105 static int ip_rsvp_on;
106 struct socket *ip_rsvpd;
107
108 int ipforwarding = 0;
109 SYSCTL_INT(_net_inet_ip, IPCTL_FORWARDING, forwarding, CTLFLAG_RW,
110     &ipforwarding, 0, "Enable IP forwarding between interfaces");
111
112 static int ipsendredirects = 1; /* XXX */
113 SYSCTL_INT(_net_inet_ip, IPCTL_SENDREDIRECTS, redirect, CTLFLAG_RW,
114     &ipsendredirects, 0, "Enable sending IP redirects");
115
116 int ip_defttl = IPDEFTTL;
117 SYSCTL_INT(_net_inet_ip, IPCTL_DEFTTL, ttl, CTLFLAG_RW,
118     &ip_defttl, 0, "Maximum TTL on IP packets");
119
120 static int ip_dosourceroute = 0;
121 SYSCTL_INT(_net_inet_ip, IPCTL_SOURCEROUTE, sourceroute, CTLFLAG_RW,
122     &ip_dosourceroute, 0, "Enable forwarding source routed IP packets");
123
124 static int ip_acceptsourceroute = 0;
125 SYSCTL_INT(_net_inet_ip, IPCTL_ACCEPTSOURCEROUTE, accept_sourceroute,
126     CTLFLAG_RW, &ip_acceptsourceroute, 0,
127     "Enable accepting source routed IP packets");
128
129 static int ip_keepfaith = 0;
130 SYSCTL_INT(_net_inet_ip, IPCTL_KEEPFAITH, keepfaith, CTLFLAG_RW,
131     &ip_keepfaith, 0,
132     "Enable packet capture for FAITH IPv4->IPv6 translater daemon");
133
134 static int nipq = 0;    /* total # of reass queues */
135 static int maxnipq;
136 SYSCTL_INT(_net_inet_ip, OID_AUTO, maxfragpackets, CTLFLAG_RW,
137     &maxnipq, 0,
138     "Maximum number of IPv4 fragment reassembly queue entries");
139
140 static int maxfragsperpacket;
141 SYSCTL_INT(_net_inet_ip, OID_AUTO, maxfragsperpacket, CTLFLAG_RW,
142     &maxfragsperpacket, 0,
143     "Maximum number of IPv4 fragments allowed per packet");
144
145 static int ip_sendsourcequench = 0;
146 SYSCTL_INT(_net_inet_ip, OID_AUTO, sendsourcequench, CTLFLAG_RW,
147     &ip_sendsourcequench, 0,
148     "Enable the transmission of source quench packets");
149
150 /*
151  * XXX - Setting ip_checkinterface mostly implements the receive side of
152  * the Strong ES model described in RFC 1122, but since the routing table
153  * and transmit implementation do not implement the Strong ES model,
154  * setting this to 1 results in an odd hybrid.
155  *
156  * XXX - ip_checkinterface currently must be disabled if you use ipnat
157  * to translate the destination address to another local interface.
158  *
159  * XXX - ip_checkinterface must be disabled if you add IP aliases
160  * to the loopback interface instead of the interface where the
161  * packets for those addresses are received.
162  */
163 static int ip_checkinterface = 0;
164 SYSCTL_INT(_net_inet_ip, OID_AUTO, check_interface, CTLFLAG_RW,
165     &ip_checkinterface, 0, "Verify packet arrives on correct interface");
166
167 #ifdef DIAGNOSTIC
168 static int ipprintfs = 0;
169 #endif
170
171 static struct ifqueue ipintrq;
172 static int ipqmaxlen = IFQ_MAXLEN;
173
174 extern  struct domain inetdomain;
175 extern  struct ipprotosw inetsw[];
176 u_char  ip_protox[IPPROTO_MAX];
177 struct  in_ifaddrhead in_ifaddrhead;            /* first inet address */
178 struct  in_ifaddrhashhead *in_ifaddrhashtbl;    /* inet addr hash table */
179 u_long  in_ifaddrhmask;                         /* mask for hash table */
180
181 SYSCTL_INT(_net_inet_ip, IPCTL_INTRQMAXLEN, intr_queue_maxlen, CTLFLAG_RW,
182     &ipintrq.ifq_maxlen, 0, "Maximum size of the IP input queue");
183 SYSCTL_INT(_net_inet_ip, IPCTL_INTRQDROPS, intr_queue_drops, CTLFLAG_RD,
184     &ipintrq.ifq_drops, 0, "Number of packets dropped from the IP input queue");
185
186 struct ip_stats ipstats_ary[MAXCPU];
187 #ifdef SMP
188 static int
189 sysctl_ipstats(SYSCTL_HANDLER_ARGS)
190 {
191         int cpu, error = 0;
192
193         for (cpu = 0; cpu < ncpus; ++cpu) {
194                 if ((error = SYSCTL_OUT(req, (void *)&ipstats_ary[cpu],
195                                         sizeof(struct ip_stats))))
196                         break;
197                 if ((error = SYSCTL_IN(req, (void *)&ipstats_ary[cpu],
198                                        sizeof(struct ip_stats))))
199                         break;
200         }
201
202         return (error);
203 }
204 SYSCTL_PROC(_net_inet_ip, IPCTL_STATS, stats, (CTLTYPE_OPAQUE | CTLFLAG_RW),
205     0, 0, sysctl_ipstats, "S,ip_stats", "IP statistics");
206 #else
207 SYSCTL_STRUCT(_net_inet_ip, IPCTL_STATS, stats, CTLFLAG_RW,
208     &ipstat, ip_stats, "IP statistics");
209 #endif
210
211 /* Packet reassembly stuff */
212 #define IPREASS_NHASH_LOG2      6
213 #define IPREASS_NHASH           (1 << IPREASS_NHASH_LOG2)
214 #define IPREASS_HMASK           (IPREASS_NHASH - 1)
215 #define IPREASS_HASH(x,y)                                               \
216     (((((x) & 0xF) | ((((x) >> 8) & 0xF) << 4)) ^ (y)) & IPREASS_HMASK)
217
218 static struct ipq ipq[IPREASS_NHASH];
219 const  int    ipintrq_present = 1;
220
221 #ifdef IPCTL_DEFMTU
222 SYSCTL_INT(_net_inet_ip, IPCTL_DEFMTU, mtu, CTLFLAG_RW,
223     &ip_mtu, 0, "Default MTU");
224 #endif
225
226 #ifdef IPSTEALTH
227 static int ipstealth = 0;
228 SYSCTL_INT(_net_inet_ip, OID_AUTO, stealth, CTLFLAG_RW, &ipstealth, 0, "");
229 #else
230 static const int ipstealth = 0;
231 #endif
232
233
234 /* Firewall hooks */
235 ip_fw_chk_t *ip_fw_chk_ptr;
236 int fw_enable = 1;
237 int fw_one_pass = 1;
238
239 /* Dummynet hooks */
240 ip_dn_io_t *ip_dn_io_ptr;
241
242 #ifdef PFIL_HOOKS
243 struct pfil_head inet_pfil_hook;
244 #endif
245
246 /*
247  * XXX this is ugly -- the following two global variables are
248  * used to store packet state while it travels through the stack.
249  * Note that the code even makes assumptions on the size and
250  * alignment of fields inside struct ip_srcrt so e.g. adding some
251  * fields will break the code. This needs to be fixed.
252  *
253  * We need to save the IP options in case a protocol wants to respond
254  * to an incoming packet over the same route if the packet got here
255  * using IP source routing.  This allows connection establishment and
256  * maintenance when the remote end is on a network that is not known
257  * to us.
258  */
259 static int ip_nhops = 0;
260
261 static  struct ip_srcrt {
262         struct  in_addr dst;                    /* final destination */
263         char    nop;                            /* one NOP to align */
264         char    srcopt[IPOPT_OFFSET + 1];       /* OPTVAL, OLEN and OFFSET */
265         struct  in_addr route[MAX_IPOPTLEN/sizeof(struct in_addr)];
266 } ip_srcrt;
267
268 static void             save_rte (u_char *, struct in_addr);
269 static int              ip_dooptions (struct mbuf *m, int,
270                                         struct sockaddr_in *next_hop);
271 static void             ip_forward (struct mbuf *m, int srcrt,
272                                         struct sockaddr_in *next_hop);
273 static void             ip_freef (struct ipq *);
274 static int              ip_input_handler (struct netmsg *);
275 static struct mbuf      *ip_reass (struct mbuf *, struct ipq *,
276                                         struct ipq *, u_int32_t *, u_int16_t *);
277
278 /*
279  * IP initialization: fill in IP protocol switch table.
280  * All protocols not implemented in kernel go to raw IP protocol handler.
281  */
282 void
283 ip_init()
284 {
285         struct ipprotosw *pr;
286         int i;
287 #ifdef SMP
288         int cpu;
289 #endif
290
291         TAILQ_INIT(&in_ifaddrhead);
292         in_ifaddrhashtbl = hashinit(INADDR_NHASH, M_IFADDR, &in_ifaddrhmask);
293         pr = (struct ipprotosw *)pffindproto(PF_INET, IPPROTO_RAW, SOCK_RAW);
294         if (pr == NULL)
295                 panic("ip_init");
296         for (i = 0; i < IPPROTO_MAX; i++)
297                 ip_protox[i] = pr - inetsw;
298         for (pr = (struct ipprotosw *)inetdomain.dom_protosw;
299              pr < (struct ipprotosw *)inetdomain.dom_protoswNPROTOSW; pr++)
300                 if (pr->pr_domain->dom_family == PF_INET &&
301                     pr->pr_protocol && pr->pr_protocol != IPPROTO_RAW)
302                         ip_protox[pr->pr_protocol] = pr - inetsw;
303
304 #ifdef PFIL_HOOKS
305         inet_pfil_hook.ph_type = PFIL_TYPE_AF;
306         inet_pfil_hook.ph_af = AF_INET;
307         if ((i = pfil_head_register(&inet_pfil_hook)) != 0)
308                 printf("%s: WARNING: unable to register pfil hook, "
309                         "error %d\n", __func__, i);
310 #endif
311
312         for (i = 0; i < IPREASS_NHASH; i++)
313             ipq[i].next = ipq[i].prev = &ipq[i];
314
315         maxnipq = nmbclusters / 32;
316         maxfragsperpacket = 16;
317
318 #ifndef RANDOM_IP_ID
319         ip_id = time_second & 0xffff;
320 #endif
321         ipintrq.ifq_maxlen = ipqmaxlen;
322
323         /*
324          * Initialize IP statistics.
325          *
326          * It is layed out as an array which is has one element for UP,
327          * and SMP_MAXCPU elements for SMP.  This allows us to retain
328          * the access mechanism from userland for both UP and SMP.
329          */
330 #ifdef SMP
331         for (cpu = 0; cpu < ncpus; ++cpu) {
332                 bzero(&ipstats_ary[cpu], sizeof(struct ip_stats));
333         }
334 #else
335         bzero(&ipstat, sizeof(struct ip_stats));
336 #endif
337
338         netisr_register(NETISR_IP, ip_mport, ip_input_handler);
339 }
340
341 /*
342  * XXX watch out this one. It is perhaps used as a cache for
343  * the most recently used route ? it is cleared in in_addroute()
344  * when a new route is successfully created.
345  */
346 struct route ipforward_rt;
347 static struct sockaddr_in ipaddr = { sizeof(ipaddr), AF_INET };
348
349 /* Do transport protocol processing. */
350 static void
351 transport_processing_oncpu(struct mbuf *m, int hlen, struct ip *ip,
352                            struct sockaddr_in *nexthop)
353 {
354         /*
355          * Switch out to protocol's input routine.
356          */
357         if (nexthop && ip->ip_p == IPPROTO_TCP) {
358                 /* TCP needs IPFORWARD info if available */
359                 struct m_hdr tag;
360
361                 tag.mh_type = MT_TAG;
362                 tag.mh_flags = PACKET_TAG_IPFORWARD;
363                 tag.mh_data = (caddr_t)nexthop;
364                 tag.mh_next = m;
365
366                 (*inetsw[ip_protox[ip->ip_p]].pr_input)
367                     ((struct mbuf *)&tag, hlen, ip->ip_p);
368         } else {
369                 (*inetsw[ip_protox[ip->ip_p]].pr_input)(m, hlen, ip->ip_p);
370         }
371 }
372
373 struct netmsg_transport_packet {
374         struct lwkt_msg         nm_lmsg;
375         struct mbuf             *nm_mbuf;
376         int                     nm_hlen;
377         boolean_t               nm_hasnexthop;
378         struct sockaddr_in      nm_nexthop;
379 };
380
381 static int
382 transport_processing_handler(lwkt_msg_t lmsg)
383 {
384         struct netmsg_transport_packet *msg = (void *)lmsg;
385         struct sockaddr_in *nexthop;
386         struct ip *ip;
387
388         ip = mtod(msg->nm_mbuf, struct ip *);
389         nexthop = msg->nm_hasnexthop ? &msg->nm_nexthop : NULL;
390         transport_processing_oncpu(msg->nm_mbuf, msg->nm_hlen, ip, nexthop);
391         lwkt_replymsg(lmsg, 0);
392         return(EASYNC);
393 }
394
395 static int
396 ip_input_handler(struct netmsg *msg0)
397 {
398         struct mbuf *m = ((struct netmsg_packet *)msg0)->nm_packet;
399
400         ip_input(m);
401         lwkt_replymsg(&msg0->nm_lmsg, 0);
402         return(EASYNC);
403 }
404
405 /*
406  * Ip input routine.  Checksum and byte swap header.  If fragmented
407  * try to reassemble.  Process options.  Pass to next level.
408  */
409 void
410 ip_input(struct mbuf *m)
411 {
412         struct ip *ip;
413         struct ipq *fp;
414         struct in_ifaddr *ia = NULL;
415         struct ifaddr *ifa;
416         int i, hlen, checkif;
417         u_short sum;
418         struct in_addr pkt_dst;
419         u_int32_t divert_info = 0;              /* packet divert/tee info */
420         struct ip_fw_args args;
421         boolean_t using_srcrt = FALSE;          /* forward (by PFIL_HOOKS) */
422         boolean_t needredispatch = FALSE;
423 #ifdef PFIL_HOOKS
424         struct in_addr odst;                    /* original dst address(NAT) */
425 #endif
426 #ifdef FAST_IPSEC
427         struct m_tag *mtag;
428         struct tdb_ident *tdbi;
429         struct secpolicy *sp;
430         int s, error;
431 #endif
432
433         args.eh = NULL;
434         args.oif = NULL;
435         args.rule = NULL;
436         args.divert_rule = 0;                   /* divert cookie */
437         args.next_hop = NULL;
438
439         /* Grab info from MT_TAG mbufs prepended to the chain. */
440         for (; m && m->m_type == MT_TAG; m = m->m_next) {
441                 switch(m->_m_tag_id) {
442                 default:
443                         printf("ip_input: unrecognised MT_TAG tag %d\n",
444                             m->_m_tag_id);
445                         break;
446
447                 case PACKET_TAG_DUMMYNET:
448                         args.rule = ((struct dn_pkt *)m)->rule;
449                         break;
450
451                 case PACKET_TAG_DIVERT:
452                         args.divert_rule = (int)m->m_hdr.mh_data & 0xffff;
453                         break;
454
455                 case PACKET_TAG_IPFORWARD:
456                         args.next_hop = (struct sockaddr_in *)m->m_hdr.mh_data;
457                         break;
458                 }
459         }
460
461         KASSERT(m != NULL && (m->m_flags & M_PKTHDR) != 0,
462             ("ip_input: no HDR"));
463
464         if (args.rule) {        /* dummynet already filtered us */
465                 ip = mtod(m, struct ip *);
466                 hlen = IP_VHL_HL(ip->ip_vhl) << 2;
467                 goto iphack;
468         }
469
470         ipstat.ips_total++;
471
472         /* length checks already done in ip_demux() */
473         KASSERT(m->m_len >= sizeof(ip), ("IP header not in one mbuf"));
474
475         ip = mtod(m, struct ip *);
476
477         if (IP_VHL_V(ip->ip_vhl) != IPVERSION) {
478                 ipstat.ips_badvers++;
479                 goto bad;
480         }
481
482         hlen = IP_VHL_HL(ip->ip_vhl) << 2;
483         /* length checks already done in ip_demux() */
484         KASSERT(hlen >= sizeof(struct ip), ("IP header len too small"));
485         KASSERT(m->m_len >= hlen, ("packet shorter than IP header length"));
486
487         /* 127/8 must not appear on wire - RFC1122 */
488         if ((ntohl(ip->ip_dst.s_addr) >> IN_CLASSA_NSHIFT) == IN_LOOPBACKNET ||
489             (ntohl(ip->ip_src.s_addr) >> IN_CLASSA_NSHIFT) == IN_LOOPBACKNET) {
490                 if (!(m->m_pkthdr.rcvif->if_flags & IFF_LOOPBACK)) {
491                         ipstat.ips_badaddr++;
492                         goto bad;
493                 }
494         }
495
496         if (m->m_pkthdr.csum_flags & CSUM_IP_CHECKED) {
497                 sum = !(m->m_pkthdr.csum_flags & CSUM_IP_VALID);
498         } else {
499                 if (hlen == sizeof(struct ip)) {
500                         sum = in_cksum_hdr(ip);
501                 } else {
502                         sum = in_cksum(m, hlen);
503                 }
504         }
505         if (sum) {
506                 ipstat.ips_badsum++;
507                 goto bad;
508         }
509
510         /*
511          * Convert fields to host representation.
512          */
513         ip->ip_len = ntohs(ip->ip_len);
514         if (ip->ip_len < hlen) {
515                 ipstat.ips_badlen++;
516                 goto bad;
517         }
518         ip->ip_off = ntohs(ip->ip_off);
519
520         /*
521          * Check that the amount of data in the buffers
522          * is as at least much as the IP header would have us expect.
523          * Trim mbufs if longer than we expect.
524          * Drop packet if shorter than we expect.
525          */
526         if (m->m_pkthdr.len < ip->ip_len) {
527                 ipstat.ips_tooshort++;
528                 goto bad;
529         }
530         if (m->m_pkthdr.len > ip->ip_len) {
531                 if (m->m_len == m->m_pkthdr.len) {
532                         m->m_len = ip->ip_len;
533                         m->m_pkthdr.len = ip->ip_len;
534                 } else
535                         m_adj(m, ip->ip_len - m->m_pkthdr.len);
536         }
537 #if defined(IPSEC) && !defined(IPSEC_FILTERGIF)
538         /*
539          * Bypass packet filtering for packets from a tunnel (gif).
540          */
541         if (ipsec_gethist(m, NULL))
542                 goto pass;
543 #endif
544
545         /*
546          * IpHack's section.
547          * Right now when no processing on packet has done
548          * and it is still fresh out of network we do our black
549          * deals with it.
550          * - Firewall: deny/allow/divert
551          * - Xlate: translate packet's addr/port (NAT).
552          * - Pipe: pass pkt through dummynet.
553          * - Wrap: fake packet's addr/port <unimpl.>
554          * - Encapsulate: put it in another IP and send out. <unimp.>
555          */
556
557 iphack:
558
559 #ifdef PFIL_HOOKS
560         /*
561          * Run through list of hooks for input packets.
562          *
563          * NB: Beware of the destination address changing (e.g.
564          *     by NAT rewriting). When this happens, tell
565          *     ip_forward to do the right thing.
566          */
567         odst = ip->ip_dst;
568         if (pfil_run_hooks(&inet_pfil_hook, &m, m->m_pkthdr.rcvif, PFIL_IN))
569                 return;
570         if (m == NULL)                  /* consumed by filter */
571                 return;
572         ip = mtod(m, struct ip *);
573         using_srcrt = (odst.s_addr != ip->ip_dst.s_addr);
574 #endif
575
576         if (fw_enable && IPFW_LOADED) {
577                 /*
578                  * If we've been forwarded from the output side, then
579                  * skip the firewall a second time
580                  */
581                 if (args.next_hop)
582                         goto ours;
583
584                 args.m = m;
585                 i = ip_fw_chk_ptr(&args);
586                 m = args.m;
587
588                 if ( (i & IP_FW_PORT_DENY_FLAG) || m == NULL) { /* drop */
589                         if (m)
590                                 m_freem(m);
591                         return;
592                 }
593                 ip = mtod(m, struct ip *); /* just in case m changed */
594                 if (i == 0 && args.next_hop == NULL)    /* common case */
595                         goto pass;
596                 if (DUMMYNET_LOADED && (i & IP_FW_PORT_DYNT_FLAG)) {
597                         /* Send packet to the appropriate pipe */
598                         ip_dn_io_ptr(m, i&0xffff, DN_TO_IP_IN, &args);
599                         return;
600                 }
601 #ifdef IPDIVERT
602                 if (i != 0 && !(i & IP_FW_PORT_DYNT_FLAG)) {
603                         /* Divert or tee packet */
604                         divert_info = i;
605                         goto ours;
606                 }
607 #endif
608                 if (i == 0 && args.next_hop != NULL)
609                         goto pass;
610                 /*
611                  * if we get here, the packet must be dropped
612                  */
613                 m_freem(m);
614                 return;
615         }
616 pass:
617
618         /*
619          * Process options and, if not destined for us,
620          * ship it on.  ip_dooptions returns 1 when an
621          * error was detected (causing an icmp message
622          * to be sent and the original packet to be freed).
623          */
624         ip_nhops = 0;           /* for source routed packets */
625         if (hlen > sizeof(struct ip) && ip_dooptions(m, 0, args.next_hop))
626                 return;
627
628         /* greedy RSVP, snatches any PATH packet of the RSVP protocol and no
629          * matter if it is destined to another node, or whether it is
630          * a multicast one, RSVP wants it! and prevents it from being forwarded
631          * anywhere else. Also checks if the rsvp daemon is running before
632          * grabbing the packet.
633          */
634         if (rsvp_on && ip->ip_p == IPPROTO_RSVP)
635                 goto ours;
636
637         /*
638          * Check our list of addresses, to see if the packet is for us.
639          * If we don't have any addresses, assume any unicast packet
640          * we receive might be for us (and let the upper layers deal
641          * with it).
642          */
643         if (TAILQ_EMPTY(&in_ifaddrhead) && !(m->m_flags & (M_MCAST | M_BCAST)))
644                 goto ours;
645
646         /*
647          * Cache the destination address of the packet; this may be
648          * changed by use of 'ipfw fwd'.
649          */
650         pkt_dst = args.next_hop ? args.next_hop->sin_addr : ip->ip_dst;
651
652         /*
653          * Enable a consistency check between the destination address
654          * and the arrival interface for a unicast packet (the RFC 1122
655          * strong ES model) if IP forwarding is disabled and the packet
656          * is not locally generated and the packet is not subject to
657          * 'ipfw fwd'.
658          *
659          * XXX - Checking also should be disabled if the destination
660          * address is ipnat'ed to a different interface.
661          *
662          * XXX - Checking is incompatible with IP aliases added
663          * to the loopback interface instead of the interface where
664          * the packets are received.
665          */
666         checkif = ip_checkinterface &&
667                   !ipforwarding &&
668                   m->m_pkthdr.rcvif != NULL &&
669                   !(m->m_pkthdr.rcvif->if_flags & IFF_LOOPBACK) &&
670                   (args.next_hop == NULL);
671
672         /*
673          * Check for exact addresses in the hash bucket.
674          */
675         LIST_FOREACH(ia, INADDR_HASH(pkt_dst.s_addr), ia_hash) {
676                 /*
677                  * If the address matches, verify that the packet
678                  * arrived via the correct interface if checking is
679                  * enabled.
680                  */
681                 if (IA_SIN(ia)->sin_addr.s_addr == pkt_dst.s_addr &&
682                     (!checkif || ia->ia_ifp == m->m_pkthdr.rcvif))
683                         goto ours;
684         }
685         /*
686          * Check for broadcast addresses.
687          *
688          * Only accept broadcast packets that arrive via the matching
689          * interface.  Reception of forwarded directed broadcasts would
690          * be handled via ip_forward() and ether_output() with the loopback
691          * into the stack for SIMPLEX interfaces handled by ether_output().
692          */
693         if (m->m_pkthdr.rcvif->if_flags & IFF_BROADCAST) {
694                 TAILQ_FOREACH(ifa, &m->m_pkthdr.rcvif->if_addrhead, ifa_link) {
695                         if (ifa->ifa_addr->sa_family != AF_INET)
696                                 continue;
697                         ia = ifatoia(ifa);
698                         if (satosin(&ia->ia_broadaddr)->sin_addr.s_addr ==
699                                                                 pkt_dst.s_addr)
700                                 goto ours;
701                         if (ia->ia_netbroadcast.s_addr == pkt_dst.s_addr)
702                                 goto ours;
703 #ifdef BOOTP_COMPAT
704                         if (IA_SIN(ia)->sin_addr.s_addr == INADDR_ANY)
705                                 goto ours;
706 #endif
707                 }
708         }
709         if (IN_MULTICAST(ntohl(ip->ip_dst.s_addr))) {
710                 struct in_multi *inm;
711                 if (ip_mrouter) {
712                         /*
713                          * If we are acting as a multicast router, all
714                          * incoming multicast packets are passed to the
715                          * kernel-level multicast forwarding function.
716                          * The packet is returned (relatively) intact; if
717                          * ip_mforward() returns a non-zero value, the packet
718                          * must be discarded, else it may be accepted below.
719                          */
720                         if (ip_mforward &&
721                             ip_mforward(ip, m->m_pkthdr.rcvif, m, NULL) != 0) {
722                                 ipstat.ips_cantforward++;
723                                 m_freem(m);
724                                 return;
725                         }
726
727                         /*
728                          * The process-level routing daemon needs to receive
729                          * all multicast IGMP packets, whether or not this
730                          * host belongs to their destination groups.
731                          */
732                         if (ip->ip_p == IPPROTO_IGMP)
733                                 goto ours;
734                         ipstat.ips_forward++;
735                 }
736                 /*
737                  * See if we belong to the destination multicast group on the
738                  * arrival interface.
739                  */
740                 IN_LOOKUP_MULTI(ip->ip_dst, m->m_pkthdr.rcvif, inm);
741                 if (inm == NULL) {
742                         ipstat.ips_notmember++;
743                         m_freem(m);
744                         return;
745                 }
746                 goto ours;
747         }
748         if (ip->ip_dst.s_addr == INADDR_BROADCAST)
749                 goto ours;
750         if (ip->ip_dst.s_addr == INADDR_ANY)
751                 goto ours;
752
753         /*
754          * FAITH(Firewall Aided Internet Translator)
755          */
756         if (m->m_pkthdr.rcvif && m->m_pkthdr.rcvif->if_type == IFT_FAITH) {
757                 if (ip_keepfaith) {
758                         if (ip->ip_p == IPPROTO_TCP || ip->ip_p == IPPROTO_ICMP)
759                                 goto ours;
760                 }
761                 m_freem(m);
762                 return;
763         }
764
765         /*
766          * Not for us; forward if possible and desirable.
767          */
768         if (!ipforwarding) {
769                 ipstat.ips_cantforward++;
770                 m_freem(m);
771         } else {
772 #ifdef IPSEC
773                 /*
774                  * Enforce inbound IPsec SPD.
775                  */
776                 if (ipsec4_in_reject(m, NULL)) {
777                         ipsecstat.in_polvio++;
778                         goto bad;
779                 }
780 #endif
781 #ifdef FAST_IPSEC
782                 mtag = m_tag_find(m, PACKET_TAG_IPSEC_IN_DONE, NULL);
783                 s = splnet();
784                 if (mtag != NULL) {
785                         tdbi = (struct tdb_ident *)(mtag + 1);
786                         sp = ipsec_getpolicy(tdbi, IPSEC_DIR_INBOUND);
787                 } else {
788                         sp = ipsec_getpolicybyaddr(m, IPSEC_DIR_INBOUND,
789                                                    IP_FORWARDING, &error);
790                 }
791                 if (sp == NULL) {       /* NB: can happen if error */
792                         splx(s);
793                         /*XXX error stat???*/
794                         DPRINTF(("ip_input: no SP for forwarding\n"));  /*XXX*/
795                         goto bad;
796                 }
797
798                 /*
799                  * Check security policy against packet attributes.
800                  */
801                 error = ipsec_in_reject(sp, m);
802                 KEY_FREESP(&sp);
803                 splx(s);
804                 if (error) {
805                         ipstat.ips_cantforward++;
806                         goto bad;
807                 }
808 #endif
809                 ip_forward(m, using_srcrt, args.next_hop);
810         }
811         return;
812
813 ours:
814
815         /*
816          * IPSTEALTH: Process non-routing options only
817          * if the packet is destined for us.
818          */
819         if (ipstealth &&
820             hlen > sizeof(struct ip) &&
821             ip_dooptions(m, 1, args.next_hop))
822                 return;
823
824         /* Count the packet in the ip address stats */
825         if (ia != NULL) {
826                 ia->ia_ifa.if_ipackets++;
827                 ia->ia_ifa.if_ibytes += m->m_pkthdr.len;
828         }
829
830         /*
831          * If offset or IP_MF are set, must reassemble.
832          * Otherwise, nothing need be done.
833          * (We could look in the reassembly queue to see
834          * if the packet was previously fragmented,
835          * but it's not worth the time; just let them time out.)
836          */
837         if (ip->ip_off & (IP_MF | IP_OFFMASK)) {
838
839                 /* If maxnipq is 0, never accept fragments. */
840                 if (maxnipq == 0) {
841                         ipstat.ips_fragments++;
842                         ipstat.ips_fragdropped++;
843                         goto bad;
844                 }
845
846                 sum = IPREASS_HASH(ip->ip_src.s_addr, ip->ip_id);
847                 /*
848                  * Look for queue of fragments
849                  * of this datagram.
850                  */
851                 for (fp = ipq[sum].next; fp != &ipq[sum]; fp = fp->next)
852                         if (ip->ip_id == fp->ipq_id &&
853                             ip->ip_src.s_addr == fp->ipq_src.s_addr &&
854                             ip->ip_dst.s_addr == fp->ipq_dst.s_addr &&
855                             ip->ip_p == fp->ipq_p)
856                                 goto found;
857
858                 fp = NULL;
859
860                 /*
861                  * Enforce upper bound on number of fragmented packets
862                  * for which we attempt reassembly;
863                  * If maxnipq is -1, accept all fragments without limitation.
864                  */
865                 if ((nipq > maxnipq) && (maxnipq > 0)) {
866                         /*
867                          * drop something from the tail of the current queue
868                          * before proceeding further
869                          */
870                         if (ipq[sum].prev == &ipq[sum]) {   /* gak */
871                                 for (i = 0; i < IPREASS_NHASH; i++) {
872                                         if (ipq[i].prev != &ipq[i]) {
873                                                 ipstat.ips_fragtimeout +=
874                                                     ipq[i].prev->ipq_nfrags;
875                                                 ip_freef(ipq[i].prev);
876                                                 break;
877                                         }
878                                 }
879                         } else {
880                                 ipstat.ips_fragtimeout +=
881                                     ipq[sum].prev->ipq_nfrags;
882                                 ip_freef(ipq[sum].prev);
883                         }
884                 }
885 found:
886                 /*
887                  * Adjust ip_len to not reflect header,
888                  * convert offset of this to bytes.
889                  */
890                 ip->ip_len -= hlen;
891                 if (ip->ip_off & IP_MF) {
892                         /*
893                          * Make sure that fragments have a data length
894                          * that's a non-zero multiple of 8 bytes.
895                          */
896                         if (ip->ip_len == 0 || (ip->ip_len & 0x7) != 0) {
897                                 ipstat.ips_toosmall++; /* XXX */
898                                 goto bad;
899                         }
900                         m->m_flags |= M_FRAG;
901                 } else
902                         m->m_flags &= ~M_FRAG;
903                 ip->ip_off <<= 3;
904
905                 /*
906                  * Attempt reassembly; if it succeeds, proceed.
907                  * ip_reass() will return a different mbuf, and update
908                  * the divert info in divert_info and args.divert_rule.
909                  */
910                 ipstat.ips_fragments++;
911                 m->m_pkthdr.header = ip;
912                 m = ip_reass(m, fp, &ipq[sum], &divert_info, &args.divert_rule);
913                 if (m == NULL)
914                         return;
915                 ipstat.ips_reassembled++;
916                 needredispatch = TRUE;
917                 ip = mtod(m, struct ip *);
918                 /* Get the header length of the reassembled packet */
919                 hlen = IP_VHL_HL(ip->ip_vhl) << 2;
920 #ifdef IPDIVERT
921                 /* Restore original checksum before diverting packet */
922                 if (divert_info != 0) {
923                         ip->ip_len += hlen;
924                         ip->ip_len = htons(ip->ip_len);
925                         ip->ip_off = htons(ip->ip_off);
926                         ip->ip_sum = 0;
927                         if (hlen == sizeof(struct ip))
928                                 ip->ip_sum = in_cksum_hdr(ip);
929                         else
930                                 ip->ip_sum = in_cksum(m, hlen);
931                         ip->ip_off = ntohs(ip->ip_off);
932                         ip->ip_len = ntohs(ip->ip_len);
933                         ip->ip_len -= hlen;
934                 }
935 #endif
936         } else {
937                 ip->ip_len -= hlen;
938         }
939
940 #ifdef IPDIVERT
941         /*
942          * Divert or tee packet to the divert protocol if required.
943          */
944         if (divert_info != 0) {
945                 struct mbuf *clone = NULL;
946
947                 /* Clone packet if we're doing a 'tee' */
948                 if ((divert_info & IP_FW_PORT_TEE_FLAG) != 0)
949                         clone = m_dup(m, M_DONTWAIT);
950
951                 /* Restore packet header fields to original values */
952                 ip->ip_len += hlen;
953                 ip->ip_len = htons(ip->ip_len);
954                 ip->ip_off = htons(ip->ip_off);
955
956                 /* Deliver packet to divert input routine */
957                 divert_packet(m, 1, divert_info & 0xffff, args.divert_rule);
958                 ipstat.ips_delivered++;
959
960                 /* If 'tee', continue with original packet */
961                 if (clone == NULL)
962                         return;
963                 m = clone;
964                 ip = mtod(m, struct ip *);
965                 ip->ip_len += hlen;
966                 /*
967                  * Jump backwards to complete processing of the
968                  * packet. But first clear divert_info to avoid
969                  * entering this block again.
970                  * We do not need to clear args.divert_rule
971                  * or args.next_hop as they will not be used.
972                  */
973                 divert_info = 0;
974                 goto pass;
975         }
976 #endif
977
978 #ifdef IPSEC
979         /*
980          * enforce IPsec policy checking if we are seeing last header.
981          * note that we do not visit this with protocols with pcb layer
982          * code - like udp/tcp/raw ip.
983          */
984         if ((inetsw[ip_protox[ip->ip_p]].pr_flags & PR_LASTHDR) &&
985             ipsec4_in_reject(m, NULL)) {
986                 ipsecstat.in_polvio++;
987                 goto bad;
988         }
989 #endif
990 #if FAST_IPSEC
991         /*
992          * enforce IPsec policy checking if we are seeing last header.
993          * note that we do not visit this with protocols with pcb layer
994          * code - like udp/tcp/raw ip.
995          */
996         if (inetsw[ip_protox[ip->ip_p]].pr_flags & PR_LASTHDR) {
997                 /*
998                  * Check if the packet has already had IPsec processing
999                  * done.  If so, then just pass it along.  This tag gets
1000                  * set during AH, ESP, etc. input handling, before the
1001                  * packet is returned to the ip input queue for delivery.
1002                  */
1003                 mtag = m_tag_find(m, PACKET_TAG_IPSEC_IN_DONE, NULL);
1004                 s = splnet();
1005                 if (mtag != NULL) {
1006                         tdbi = (struct tdb_ident *)(mtag + 1);
1007                         sp = ipsec_getpolicy(tdbi, IPSEC_DIR_INBOUND);
1008                 } else {
1009                         sp = ipsec_getpolicybyaddr(m, IPSEC_DIR_INBOUND,
1010                                                    IP_FORWARDING, &error);
1011                 }
1012                 if (sp != NULL) {
1013                         /*
1014                          * Check security policy against packet attributes.
1015                          */
1016                         error = ipsec_in_reject(sp, m);
1017                         KEY_FREESP(&sp);
1018                 } else {
1019                         /* XXX error stat??? */
1020                         error = EINVAL;
1021 DPRINTF(("ip_input: no SP, packet discarded\n"));/*XXX*/
1022                         goto bad;
1023                 }
1024                 splx(s);
1025                 if (error)
1026                         goto bad;
1027         }
1028 #endif /* FAST_IPSEC */
1029
1030         ipstat.ips_delivered++;
1031         if (needredispatch) {
1032                 struct netmsg_transport_packet *msg;
1033                 lwkt_port_t port;
1034
1035                 msg = malloc(sizeof(struct netmsg_transport_packet),
1036                                 M_LWKTMSG, M_INTWAIT | M_NULLOK);
1037                 if (msg == NULL)
1038                         goto bad;
1039
1040                 lwkt_initmsg(&msg->nm_lmsg, &netisr_afree_rport, 0,
1041                         lwkt_cmd_func(transport_processing_handler),
1042                         lwkt_cmd_op_none);
1043                 msg->nm_mbuf = m;
1044                 msg->nm_hlen = hlen;
1045                 msg->nm_hasnexthop = (args.next_hop != NULL);
1046                 if (msg->nm_hasnexthop)
1047                         msg->nm_nexthop = *args.next_hop;  /* structure copy */
1048
1049                 ip->ip_off = htons(ip->ip_off);
1050                 ip->ip_len = htons(ip->ip_len);
1051                 port = ip_mport(m);
1052                 if (port == NULL)
1053                         goto bad;
1054                 ip->ip_len = ntohs(ip->ip_len);
1055                 ip->ip_off = ntohs(ip->ip_off);
1056
1057                 lwkt_sendmsg(port, &msg->nm_lmsg);
1058         } else {
1059                 transport_processing_oncpu(m, hlen, ip, args.next_hop);
1060         }
1061         return;
1062
1063 bad:
1064         m_freem(m);
1065 }
1066
1067 /*
1068  * Take incoming datagram fragment and try to reassemble it into
1069  * whole datagram.  If a chain for reassembly of this datagram already
1070  * exists, then it is given as fp; otherwise have to make a chain.
1071  *
1072  * When IPDIVERT enabled, keep additional state with each packet that
1073  * tells us if we need to divert or tee the packet we're building.
1074  * In particular, *divinfo includes the port and TEE flag,
1075  * *divert_rule is the number of the matching rule.
1076  */
1077
1078 static struct mbuf *
1079 ip_reass(struct mbuf *m, struct ipq *fp, struct ipq *where,
1080          u_int32_t *divinfo, u_int16_t *divert_rule)
1081 {
1082         struct ip *ip = mtod(m, struct ip *);
1083         struct mbuf *p = NULL, *q, *nq;
1084         struct mbuf *t;
1085         int hlen = IP_VHL_HL(ip->ip_vhl) << 2;
1086         int i, next;
1087
1088         /*
1089          * Presence of header sizes in mbufs
1090          * would confuse code below.
1091          */
1092         m->m_data += hlen;
1093         m->m_len -= hlen;
1094
1095         /*
1096          * If first fragment to arrive, create a reassembly queue.
1097          */
1098         if (fp == NULL) {
1099                 if ((t = m_get(M_DONTWAIT, MT_FTABLE)) == NULL)
1100                         goto dropfrag;
1101                 fp = mtod(t, struct ipq *);
1102                 insque(fp, where);
1103                 nipq++;
1104                 fp->ipq_nfrags = 1;
1105                 fp->ipq_ttl = IPFRAGTTL;
1106                 fp->ipq_p = ip->ip_p;
1107                 fp->ipq_id = ip->ip_id;
1108                 fp->ipq_src = ip->ip_src;
1109                 fp->ipq_dst = ip->ip_dst;
1110                 fp->ipq_frags = m;
1111                 m->m_nextpkt = NULL;
1112 #ifdef IPDIVERT
1113                 fp->ipq_div_info = 0;
1114                 fp->ipq_div_cookie = 0;
1115 #endif
1116                 goto inserted;
1117         } else {
1118                 fp->ipq_nfrags++;
1119         }
1120
1121 #define GETIP(m)        ((struct ip*)((m)->m_pkthdr.header))
1122
1123         /*
1124          * Find a segment which begins after this one does.
1125          */
1126         for (p = NULL, q = fp->ipq_frags; q; p = q, q = q->m_nextpkt)
1127                 if (GETIP(q)->ip_off > ip->ip_off)
1128                         break;
1129
1130         /*
1131          * If there is a preceding segment, it may provide some of
1132          * our data already.  If so, drop the data from the incoming
1133          * segment.  If it provides all of our data, drop us, otherwise
1134          * stick new segment in the proper place.
1135          *
1136          * If some of the data is dropped from the the preceding
1137          * segment, then it's checksum is invalidated.
1138          */
1139         if (p) {
1140                 i = GETIP(p)->ip_off + GETIP(p)->ip_len - ip->ip_off;
1141                 if (i > 0) {
1142                         if (i >= ip->ip_len)
1143                                 goto dropfrag;
1144                         m_adj(m, i);
1145                         m->m_pkthdr.csum_flags = 0;
1146                         ip->ip_off += i;
1147                         ip->ip_len -= i;
1148                 }
1149                 m->m_nextpkt = p->m_nextpkt;
1150                 p->m_nextpkt = m;
1151         } else {
1152                 m->m_nextpkt = fp->ipq_frags;
1153                 fp->ipq_frags = m;
1154         }
1155
1156         /*
1157          * While we overlap succeeding segments trim them or,
1158          * if they are completely covered, dequeue them.
1159          */
1160         for (; q != NULL && ip->ip_off + ip->ip_len > GETIP(q)->ip_off;
1161              q = nq) {
1162                 i = (ip->ip_off + ip->ip_len) - GETIP(q)->ip_off;
1163                 if (i < GETIP(q)->ip_len) {
1164                         GETIP(q)->ip_len -= i;
1165                         GETIP(q)->ip_off += i;
1166                         m_adj(q, i);
1167                         q->m_pkthdr.csum_flags = 0;
1168                         break;
1169                 }
1170                 nq = q->m_nextpkt;
1171                 m->m_nextpkt = nq;
1172                 ipstat.ips_fragdropped++;
1173                 fp->ipq_nfrags--;
1174                 m_freem(q);
1175         }
1176
1177 inserted:
1178
1179 #ifdef IPDIVERT
1180         /*
1181          * Transfer firewall instructions to the fragment structure.
1182          * Only trust info in the fragment at offset 0.
1183          */
1184         if (ip->ip_off == 0) {
1185                 fp->ipq_div_info = *divinfo;
1186                 fp->ipq_div_cookie = *divert_rule;
1187         }
1188         *divinfo = 0;
1189         *divert_rule = 0;
1190 #endif
1191
1192         /*
1193          * Check for complete reassembly and perform frag per packet
1194          * limiting.
1195          *
1196          * Frag limiting is performed here so that the nth frag has
1197          * a chance to complete the packet before we drop the packet.
1198          * As a result, n+1 frags are actually allowed per packet, but
1199          * only n will ever be stored. (n = maxfragsperpacket.)
1200          *
1201          */
1202         next = 0;
1203         for (p = NULL, q = fp->ipq_frags; q; p = q, q = q->m_nextpkt) {
1204                 if (GETIP(q)->ip_off != next) {
1205                         if (fp->ipq_nfrags > maxfragsperpacket) {
1206                                 ipstat.ips_fragdropped += fp->ipq_nfrags;
1207                                 ip_freef(fp);
1208                         }
1209                         return (NULL);
1210                 }
1211                 next += GETIP(q)->ip_len;
1212         }
1213         /* Make sure the last packet didn't have the IP_MF flag */
1214         if (p->m_flags & M_FRAG) {
1215                 if (fp->ipq_nfrags > maxfragsperpacket) {
1216                         ipstat.ips_fragdropped += fp->ipq_nfrags;
1217                         ip_freef(fp);
1218                 }
1219                 return (NULL);
1220         }
1221
1222         /*
1223          * Reassembly is complete.  Make sure the packet is a sane size.
1224          */
1225         q = fp->ipq_frags;
1226         ip = GETIP(q);
1227         if (next + (IP_VHL_HL(ip->ip_vhl) << 2) > IP_MAXPACKET) {
1228                 ipstat.ips_toolong++;
1229                 ipstat.ips_fragdropped += fp->ipq_nfrags;
1230                 ip_freef(fp);
1231                 return (NULL);
1232         }
1233
1234         /*
1235          * Concatenate fragments.
1236          */
1237         m = q;
1238         t = m->m_next;
1239         m->m_next = NULL;
1240         m_cat(m, t);
1241         nq = q->m_nextpkt;
1242         q->m_nextpkt = NULL;
1243         for (q = nq; q != NULL; q = nq) {
1244                 nq = q->m_nextpkt;
1245                 q->m_nextpkt = NULL;
1246                 m->m_pkthdr.csum_flags &= q->m_pkthdr.csum_flags;
1247                 m->m_pkthdr.csum_data += q->m_pkthdr.csum_data;
1248                 m_cat(m, q);
1249         }
1250
1251 #ifdef IPDIVERT
1252         /*
1253          * Extract firewall instructions from the fragment structure.
1254          */
1255         *divinfo = fp->ipq_div_info;
1256         *divert_rule = fp->ipq_div_cookie;
1257 #endif
1258
1259         /*
1260          * Create header for new ip packet by
1261          * modifying header of first packet;
1262          * dequeue and discard fragment reassembly header.
1263          * Make header visible.
1264          */
1265         ip->ip_len = next;
1266         ip->ip_src = fp->ipq_src;
1267         ip->ip_dst = fp->ipq_dst;
1268         remque(fp);
1269         nipq--;
1270         (void) m_free(dtom(fp));
1271         m->m_len += (IP_VHL_HL(ip->ip_vhl) << 2);
1272         m->m_data -= (IP_VHL_HL(ip->ip_vhl) << 2);
1273         /* some debugging cruft by sklower, below, will go away soon */
1274         if (m->m_flags & M_PKTHDR) { /* XXX this should be done elsewhere */
1275                 int plen = 0;
1276
1277                 for (t = m; t; t = t->m_next)
1278                         plen += t->m_len;
1279                 m->m_pkthdr.len = plen;
1280         }
1281         return (m);
1282
1283 dropfrag:
1284 #ifdef IPDIVERT
1285         *divinfo = 0;
1286         *divert_rule = 0;
1287 #endif
1288         ipstat.ips_fragdropped++;
1289         if (fp != NULL)
1290                 fp->ipq_nfrags--;
1291         m_freem(m);
1292         return (NULL);
1293
1294 #undef GETIP
1295 }
1296
1297 /*
1298  * Free a fragment reassembly header and all
1299  * associated datagrams.
1300  */
1301 static void
1302 ip_freef(struct ipq *fp)
1303 {
1304         struct mbuf *q;
1305
1306         while (fp->ipq_frags) {
1307                 q = fp->ipq_frags;
1308                 fp->ipq_frags = q->m_nextpkt;
1309                 m_freem(q);
1310         }
1311         remque(fp);
1312         (void) m_free(dtom(fp));
1313         nipq--;
1314 }
1315
1316 /*
1317  * IP timer processing;
1318  * if a timer expires on a reassembly
1319  * queue, discard it.
1320  */
1321 void
1322 ip_slowtimo()
1323 {
1324         struct ipq *fp;
1325         int s = splnet();
1326         int i;
1327
1328         for (i = 0; i < IPREASS_NHASH; i++) {
1329                 fp = ipq[i].next;
1330                 if (fp == NULL)
1331                         continue;
1332                 while (fp != &ipq[i]) {
1333                         --fp->ipq_ttl;
1334                         fp = fp->next;
1335                         if (fp->prev->ipq_ttl == 0) {
1336                                 ipstat.ips_fragtimeout += fp->prev->ipq_nfrags;
1337                                 ip_freef(fp->prev);
1338                         }
1339                 }
1340         }
1341         /*
1342          * If we are over the maximum number of fragments
1343          * (due to the limit being lowered), drain off
1344          * enough to get down to the new limit.
1345          */
1346         if (maxnipq >= 0 && nipq > maxnipq) {
1347                 for (i = 0; i < IPREASS_NHASH; i++) {
1348                         while (nipq > maxnipq &&
1349                                 (ipq[i].next != &ipq[i])) {
1350                                 ipstat.ips_fragdropped +=
1351                                     ipq[i].next->ipq_nfrags;
1352                                 ip_freef(ipq[i].next);
1353                         }
1354                 }
1355         }
1356         ipflow_slowtimo();
1357         splx(s);
1358 }
1359
1360 /*
1361  * Drain off all datagram fragments.
1362  */
1363 void
1364 ip_drain()
1365 {
1366         int i;
1367
1368         for (i = 0; i < IPREASS_NHASH; i++) {
1369                 while (ipq[i].next != &ipq[i]) {
1370                         ipstat.ips_fragdropped += ipq[i].next->ipq_nfrags;
1371                         ip_freef(ipq[i].next);
1372                 }
1373         }
1374         in_rtqdrain();
1375 }
1376
1377 /*
1378  * Do option processing on a datagram,
1379  * possibly discarding it if bad options are encountered,
1380  * or forwarding it if source-routed.
1381  * The pass argument is used when operating in the IPSTEALTH
1382  * mode to tell what options to process:
1383  * [LS]SRR (pass 0) or the others (pass 1).
1384  * The reason for as many as two passes is that when doing IPSTEALTH,
1385  * non-routing options should be processed only if the packet is for us.
1386  * Returns 1 if packet has been forwarded/freed,
1387  * 0 if the packet should be processed further.
1388  */
1389 static int
1390 ip_dooptions(struct mbuf *m, int pass, struct sockaddr_in *next_hop)
1391 {
1392         struct ip *ip = mtod(m, struct ip *);
1393         u_char *cp;
1394         struct in_ifaddr *ia;
1395         int opt, optlen, cnt, off, code, type = ICMP_PARAMPROB;
1396         boolean_t forward = FALSE;
1397         struct in_addr *sin, dst;
1398         n_time ntime;
1399
1400         dst = ip->ip_dst;
1401         cp = (u_char *)(ip + 1);
1402         cnt = (IP_VHL_HL(ip->ip_vhl) << 2) - sizeof(struct ip);
1403         for (; cnt > 0; cnt -= optlen, cp += optlen) {
1404                 opt = cp[IPOPT_OPTVAL];
1405                 if (opt == IPOPT_EOL)
1406                         break;
1407                 if (opt == IPOPT_NOP)
1408                         optlen = 1;
1409                 else {
1410                         if (cnt < IPOPT_OLEN + sizeof(*cp)) {
1411                                 code = &cp[IPOPT_OLEN] - (u_char *)ip;
1412                                 goto bad;
1413                         }
1414                         optlen = cp[IPOPT_OLEN];
1415                         if (optlen < IPOPT_OLEN + sizeof(*cp) || optlen > cnt) {
1416                                 code = &cp[IPOPT_OLEN] - (u_char *)ip;
1417                                 goto bad;
1418                         }
1419                 }
1420                 switch (opt) {
1421
1422                 default:
1423                         break;
1424
1425                 /*
1426                  * Source routing with record.
1427                  * Find interface with current destination address.
1428                  * If none on this machine then drop if strictly routed,
1429                  * or do nothing if loosely routed.
1430                  * Record interface address and bring up next address
1431                  * component.  If strictly routed make sure next
1432                  * address is on directly accessible net.
1433                  */
1434                 case IPOPT_LSRR:
1435                 case IPOPT_SSRR:
1436                         if (ipstealth && pass > 0)
1437                                 break;
1438                         if (optlen < IPOPT_OFFSET + sizeof(*cp)) {
1439                                 code = &cp[IPOPT_OLEN] - (u_char *)ip;
1440                                 goto bad;
1441                         }
1442                         if ((off = cp[IPOPT_OFFSET]) < IPOPT_MINOFF) {
1443                                 code = &cp[IPOPT_OFFSET] - (u_char *)ip;
1444                                 goto bad;
1445                         }
1446                         ipaddr.sin_addr = ip->ip_dst;
1447                         ia = (struct in_ifaddr *)
1448                                 ifa_ifwithaddr((struct sockaddr *)&ipaddr);
1449                         if (ia == NULL) {
1450                                 if (opt == IPOPT_SSRR) {
1451                                         type = ICMP_UNREACH;
1452                                         code = ICMP_UNREACH_SRCFAIL;
1453                                         goto bad;
1454                                 }
1455                                 if (!ip_dosourceroute)
1456                                         goto nosourcerouting;
1457                                 /*
1458                                  * Loose routing, and not at next destination
1459                                  * yet; nothing to do except forward.
1460                                  */
1461                                 break;
1462                         }
1463                         off--;                  /* 0 origin */
1464                         if (off > optlen - (int)sizeof(struct in_addr)) {
1465                                 /*
1466                                  * End of source route.  Should be for us.
1467                                  */
1468                                 if (!ip_acceptsourceroute)
1469                                         goto nosourcerouting;
1470                                 save_rte(cp, ip->ip_src);
1471                                 break;
1472                         }
1473                         if (ipstealth)
1474                                 goto dropit;
1475                         if (!ip_dosourceroute) {
1476                                 if (ipforwarding) {
1477                                         char buf[16]; /* aaa.bbb.ccc.ddd\0 */
1478                                         /*
1479                                          * Acting as a router, so generate ICMP
1480                                          */
1481 nosourcerouting:
1482                                         strcpy(buf, inet_ntoa(ip->ip_dst));
1483                                         log(LOG_WARNING,
1484                                             "attempted source route from %s to %s\n",
1485                                             inet_ntoa(ip->ip_src), buf);
1486                                         type = ICMP_UNREACH;
1487                                         code = ICMP_UNREACH_SRCFAIL;
1488                                         goto bad;
1489                                 } else {
1490                                         /*
1491                                          * Not acting as a router,
1492                                          * so silently drop.
1493                                          */
1494 dropit:
1495                                         ipstat.ips_cantforward++;
1496                                         m_freem(m);
1497                                         return (1);
1498                                 }
1499                         }
1500
1501                         /*
1502                          * locate outgoing interface
1503                          */
1504                         (void)memcpy(&ipaddr.sin_addr, cp + off,
1505                             sizeof(ipaddr.sin_addr));
1506
1507                         if (opt == IPOPT_SSRR) {
1508 #define INA     struct in_ifaddr *
1509 #define SA      struct sockaddr *
1510                                 if ((ia = (INA)ifa_ifwithdstaddr((SA)&ipaddr))
1511                                                                         == NULL)
1512                                         ia = (INA)ifa_ifwithnet((SA)&ipaddr);
1513                         } else
1514                                 ia = ip_rtaddr(ipaddr.sin_addr, &ipforward_rt);
1515                         if (ia == NULL) {
1516                                 type = ICMP_UNREACH;
1517                                 code = ICMP_UNREACH_SRCFAIL;
1518                                 goto bad;
1519                         }
1520                         ip->ip_dst = ipaddr.sin_addr;
1521                         (void)memcpy(cp + off, &(IA_SIN(ia)->sin_addr),
1522                             sizeof(struct in_addr));
1523                         cp[IPOPT_OFFSET] += sizeof(struct in_addr);
1524                         /*
1525                          * Let ip_intr's mcast routing check handle mcast pkts
1526                          */
1527                         forward = !IN_MULTICAST(ntohl(ip->ip_dst.s_addr));
1528                         break;
1529
1530                 case IPOPT_RR:
1531                         if (ipstealth && pass == 0)
1532                                 break;
1533                         if (optlen < IPOPT_OFFSET + sizeof(*cp)) {
1534                                 code = &cp[IPOPT_OFFSET] - (u_char *)ip;
1535                                 goto bad;
1536                         }
1537                         if ((off = cp[IPOPT_OFFSET]) < IPOPT_MINOFF) {
1538                                 code = &cp[IPOPT_OFFSET] - (u_char *)ip;
1539                                 goto bad;
1540                         }
1541                         /*
1542                          * If no space remains, ignore.
1543                          */
1544                         off--;                  /* 0 origin */
1545                         if (off > optlen - (int)sizeof(struct in_addr))
1546                                 break;
1547                         (void)memcpy(&ipaddr.sin_addr, &ip->ip_dst,
1548                             sizeof(ipaddr.sin_addr));
1549                         /*
1550                          * locate outgoing interface; if we're the destination,
1551                          * use the incoming interface (should be same).
1552                          */
1553                         if ((ia = (INA)ifa_ifwithaddr((SA)&ipaddr)) == NULL &&
1554                             (ia = ip_rtaddr(ipaddr.sin_addr, &ipforward_rt))
1555                                                                      == NULL) {
1556                                 type = ICMP_UNREACH;
1557                                 code = ICMP_UNREACH_HOST;
1558                                 goto bad;
1559                         }
1560                         (void)memcpy(cp + off, &(IA_SIN(ia)->sin_addr),
1561                             sizeof(struct in_addr));
1562                         cp[IPOPT_OFFSET] += sizeof(struct in_addr);
1563                         break;
1564
1565                 case IPOPT_TS:
1566                         if (ipstealth && pass == 0)
1567                                 break;
1568                         code = cp - (u_char *)ip;
1569                         if (optlen < 4 || optlen > 40) {
1570                                 code = &cp[IPOPT_OLEN] - (u_char *)ip;
1571                                 goto bad;
1572                         }
1573                         if ((off = cp[IPOPT_OFFSET]) < 5) {
1574                                 code = &cp[IPOPT_OLEN] - (u_char *)ip;
1575                                 goto bad;
1576                         }
1577                         if (off > optlen - (int)sizeof(int32_t)) {
1578                                 cp[IPOPT_OFFSET + 1] += (1 << 4);
1579                                 if ((cp[IPOPT_OFFSET + 1] & 0xf0) == 0) {
1580                                         code = &cp[IPOPT_OFFSET] - (u_char *)ip;
1581                                         goto bad;
1582                                 }
1583                                 break;
1584                         }
1585                         off--;                          /* 0 origin */
1586                         sin = (struct in_addr *)(cp + off);
1587                         switch (cp[IPOPT_OFFSET + 1] & 0x0f) {
1588
1589                         case IPOPT_TS_TSONLY:
1590                                 break;
1591
1592                         case IPOPT_TS_TSANDADDR:
1593                                 if (off + sizeof(n_time) +
1594                                     sizeof(struct in_addr) > optlen) {
1595                                         code = &cp[IPOPT_OFFSET] - (u_char *)ip;
1596                                         goto bad;
1597                                 }
1598                                 ipaddr.sin_addr = dst;
1599                                 ia = (INA)ifaof_ifpforaddr((SA)&ipaddr,
1600                                                             m->m_pkthdr.rcvif);
1601                                 if (ia == NULL)
1602                                         continue;
1603                                 (void)memcpy(sin, &IA_SIN(ia)->sin_addr,
1604                                     sizeof(struct in_addr));
1605                                 cp[IPOPT_OFFSET] += sizeof(struct in_addr);
1606                                 off += sizeof(struct in_addr);
1607                                 break;
1608
1609                         case IPOPT_TS_PRESPEC:
1610                                 if (off + sizeof(n_time) +
1611                                     sizeof(struct in_addr) > optlen) {
1612                                         code = &cp[IPOPT_OFFSET] - (u_char *)ip;
1613                                         goto bad;
1614                                 }
1615                                 (void)memcpy(&ipaddr.sin_addr, sin,
1616                                     sizeof(struct in_addr));
1617                                 if (ifa_ifwithaddr((SA)&ipaddr) == NULL)
1618                                         continue;
1619                                 cp[IPOPT_OFFSET] += sizeof(struct in_addr);
1620                                 off += sizeof(struct in_addr);
1621                                 break;
1622
1623                         default:
1624                                 code = &cp[IPOPT_OFFSET + 1] - (u_char *)ip;
1625                                 goto bad;
1626                         }
1627                         ntime = iptime();
1628                         (void)memcpy(cp + off, &ntime, sizeof(n_time));
1629                         cp[IPOPT_OFFSET] += sizeof(n_time);
1630                 }
1631         }
1632         if (forward && ipforwarding) {
1633                 ip_forward(m, 1, next_hop);
1634                 return (1);
1635         }
1636         return (0);
1637 bad:
1638         icmp_error(m, type, code, 0, NULL);
1639         ipstat.ips_badoptions++;
1640         return (1);
1641 }
1642
1643 /*
1644  * Given address of next destination (final or next hop),
1645  * return internet address info of interface to be used to get there.
1646  */
1647 struct in_ifaddr *
1648 ip_rtaddr(struct in_addr dst, struct route *rt)
1649 {
1650         struct sockaddr_in *sin;
1651
1652         sin = (struct sockaddr_in *)&rt->ro_dst;
1653
1654         if (rt->ro_rt == NULL || dst.s_addr != sin->sin_addr.s_addr) {
1655                 if (rt->ro_rt != NULL) {
1656                         RTFREE(rt->ro_rt);
1657                         rt->ro_rt = NULL;
1658                 }
1659                 sin->sin_family = AF_INET;
1660                 sin->sin_len = sizeof(*sin);
1661                 sin->sin_addr = dst;
1662                 rtalloc_ign(rt, RTF_PRCLONING);
1663         }
1664
1665         if (rt->ro_rt == NULL)
1666                 return (NULL);
1667
1668         return (ifatoia(rt->ro_rt->rt_ifa));
1669 }
1670
1671 /*
1672  * Save incoming source route for use in replies,
1673  * to be picked up later by ip_srcroute if the receiver is interested.
1674  */
1675 void
1676 save_rte(u_char *option, struct in_addr dst)
1677 {
1678         unsigned olen;
1679
1680         olen = option[IPOPT_OLEN];
1681 #ifdef DIAGNOSTIC
1682         if (ipprintfs)
1683                 printf("save_rte: olen %d\n", olen);
1684 #endif
1685         if (olen > sizeof(ip_srcrt) - (1 + sizeof(dst)))
1686                 return;
1687         bcopy(option, ip_srcrt.srcopt, olen);
1688         ip_nhops = (olen - IPOPT_OFFSET - 1) / sizeof(struct in_addr);
1689         ip_srcrt.dst = dst;
1690 }
1691
1692 /*
1693  * Retrieve incoming source route for use in replies,
1694  * in the same form used by setsockopt.
1695  * The first hop is placed before the options, will be removed later.
1696  */
1697 struct mbuf *
1698 ip_srcroute()
1699 {
1700         struct in_addr *p, *q;
1701         struct mbuf *m;
1702
1703         if (ip_nhops == 0)
1704                 return (NULL);
1705         m = m_get(M_DONTWAIT, MT_HEADER);
1706         if (m == NULL)
1707                 return (NULL);
1708
1709 #define OPTSIZ  (sizeof(ip_srcrt.nop) + sizeof(ip_srcrt.srcopt))
1710
1711         /* length is (nhops+1)*sizeof(addr) + sizeof(nop + srcrt header) */
1712         m->m_len = ip_nhops * sizeof(struct in_addr) + sizeof(struct in_addr) +
1713             OPTSIZ;
1714 #ifdef DIAGNOSTIC
1715         if (ipprintfs)
1716                 printf("ip_srcroute: nhops %d mlen %d", ip_nhops, m->m_len);
1717 #endif
1718
1719         /*
1720          * First save first hop for return route
1721          */
1722         p = &ip_srcrt.route[ip_nhops - 1];
1723         *(mtod(m, struct in_addr *)) = *p--;
1724 #ifdef DIAGNOSTIC
1725         if (ipprintfs)
1726                 printf(" hops %lx", ntohl(mtod(m, struct in_addr *)->s_addr));
1727 #endif
1728
1729         /*
1730          * Copy option fields and padding (nop) to mbuf.
1731          */
1732         ip_srcrt.nop = IPOPT_NOP;
1733         ip_srcrt.srcopt[IPOPT_OFFSET] = IPOPT_MINOFF;
1734         (void)memcpy(mtod(m, caddr_t) + sizeof(struct in_addr), &ip_srcrt.nop,
1735             OPTSIZ);
1736         q = (struct in_addr *)(mtod(m, caddr_t) +
1737             sizeof(struct in_addr) + OPTSIZ);
1738 #undef OPTSIZ
1739         /*
1740          * Record return path as an IP source route,
1741          * reversing the path (pointers are now aligned).
1742          */
1743         while (p >= ip_srcrt.route) {
1744 #ifdef DIAGNOSTIC
1745                 if (ipprintfs)
1746                         printf(" %lx", ntohl(q->s_addr));
1747 #endif
1748                 *q++ = *p--;
1749         }
1750         /*
1751          * Last hop goes to final destination.
1752          */
1753         *q = ip_srcrt.dst;
1754 #ifdef DIAGNOSTIC
1755         if (ipprintfs)
1756                 printf(" %lx\n", ntohl(q->s_addr));
1757 #endif
1758         return (m);
1759 }
1760
1761 /*
1762  * Strip out IP options.
1763  */
1764 void
1765 ip_stripoptions(struct mbuf *m)
1766 {
1767         int datalen;
1768         struct ip *ip = mtod(m, struct ip *);
1769         caddr_t opts;
1770         int optlen;
1771
1772         optlen = (IP_VHL_HL(ip->ip_vhl) << 2) - sizeof(struct ip);
1773         opts = (caddr_t)(ip + 1);
1774         datalen = m->m_len - (sizeof(struct ip) + optlen);
1775         bcopy(opts + optlen, opts, datalen);
1776         m->m_len -= optlen;
1777         if (m->m_flags & M_PKTHDR)
1778                 m->m_pkthdr.len -= optlen;
1779         ip->ip_vhl = IP_MAKE_VHL(IPVERSION, sizeof(struct ip) >> 2);
1780 }
1781
1782 u_char inetctlerrmap[PRC_NCMDS] = {
1783         0,              0,              0,              0,
1784         0,              EMSGSIZE,       EHOSTDOWN,      EHOSTUNREACH,
1785         EHOSTUNREACH,   EHOSTUNREACH,   ECONNREFUSED,   ECONNREFUSED,
1786         EMSGSIZE,       EHOSTUNREACH,   0,              0,
1787         0,              0,              0,              0,
1788         ENOPROTOOPT,    ECONNREFUSED
1789 };
1790
1791 /*
1792  * Forward a packet.  If some error occurs return the sender
1793  * an icmp packet.  Note we can't always generate a meaningful
1794  * icmp message because icmp doesn't have a large enough repertoire
1795  * of codes and types.
1796  *
1797  * If not forwarding, just drop the packet.  This could be confusing
1798  * if ipforwarding was zero but some routing protocol was advancing
1799  * us as a gateway to somewhere.  However, we must let the routing
1800  * protocol deal with that.
1801  *
1802  * The using_srcrt parameter indicates whether the packet is being forwarded
1803  * via a source route.
1804  */
1805 static void
1806 ip_forward(struct mbuf *m, int using_srcrt, struct sockaddr_in *next_hop)
1807 {
1808         struct ip *ip = mtod(m, struct ip *);
1809         struct sockaddr_in *sin;
1810         struct rtentry *rt;
1811         int error, type = 0, code = 0;
1812         struct mbuf *mcopy;
1813         n_long dest;
1814         struct in_addr pkt_dst;
1815         struct ifnet *destifp;
1816         struct m_hdr tag;
1817 #if defined(IPSEC) || defined(FAST_IPSEC)
1818         struct ifnet dummyifp;
1819 #endif
1820
1821         dest = 0;
1822         /*
1823          * Cache the destination address of the packet; this may be
1824          * changed by use of 'ipfw fwd'.
1825          */
1826         pkt_dst = next_hop ? next_hop->sin_addr : ip->ip_dst;
1827
1828 #ifdef DIAGNOSTIC
1829         if (ipprintfs)
1830                 printf("forward: src %lx dst %lx ttl %x\n",
1831                        ip->ip_src.s_addr, pkt_dst.s_addr, ip->ip_ttl);
1832 #endif
1833
1834         if (m->m_flags & (M_BCAST | M_MCAST) || !in_canforward(pkt_dst)) {
1835                 ipstat.ips_cantforward++;
1836                 m_freem(m);
1837                 return;
1838         }
1839         if (!ipstealth && ip->ip_ttl <= IPTTLDEC) {
1840                 icmp_error(m, ICMP_TIMXCEED, ICMP_TIMXCEED_INTRANS, dest, NULL);
1841                 return;
1842         }
1843
1844         sin = (struct sockaddr_in *)&ipforward_rt.ro_dst;
1845         if ((rt = ipforward_rt.ro_rt) == NULL ||
1846             pkt_dst.s_addr != sin->sin_addr.s_addr) {
1847                 if (ipforward_rt.ro_rt != NULL) {
1848                         RTFREE(ipforward_rt.ro_rt);
1849                         ipforward_rt.ro_rt = NULL;
1850                 }
1851                 sin->sin_family = AF_INET;
1852                 sin->sin_len = sizeof(*sin);
1853                 sin->sin_addr = pkt_dst;
1854
1855                 rtalloc_ign(&ipforward_rt, RTF_PRCLONING);
1856                 if (ipforward_rt.ro_rt == NULL) {
1857                         icmp_error(m, ICMP_UNREACH, ICMP_UNREACH_HOST, dest,
1858                                    NULL);
1859                         return;
1860                 }
1861                 rt = ipforward_rt.ro_rt;
1862         }
1863
1864         /*
1865          * Save the IP header and at most 8 bytes of the payload,
1866          * in case we need to generate an ICMP message to the src.
1867          *
1868          * XXX this can be optimized a lot by saving the data in a local
1869          * buffer on the stack (72 bytes at most), and only allocating the
1870          * mbuf if really necessary. The vast majority of the packets
1871          * are forwarded without having to send an ICMP back (either
1872          * because unnecessary, or because rate limited), so we are
1873          * really we are wasting a lot of work here.
1874          *
1875          * We don't use m_copy() because it might return a reference
1876          * to a shared cluster. Both this function and ip_output()
1877          * assume exclusive access to the IP header in `m', so any
1878          * data in a cluster may change before we reach icmp_error().
1879          */
1880         MGET(mcopy, M_DONTWAIT, m->m_type);
1881         if (mcopy != NULL && !m_dup_pkthdr(mcopy, m, M_DONTWAIT)) {
1882                 /*
1883                  * It's probably ok if the pkthdr dup fails (because
1884                  * the deep copy of the tag chain failed), but for now
1885                  * be conservative and just discard the copy since
1886                  * code below may some day want the tags.
1887                  */
1888                 m_free(mcopy);
1889                 mcopy = NULL;
1890         }
1891         if (mcopy != NULL) {
1892                 mcopy->m_len = imin((IP_VHL_HL(ip->ip_vhl) << 2) + 8,
1893                     (int)ip->ip_len);
1894                 m_copydata(m, 0, mcopy->m_len, mtod(mcopy, caddr_t));
1895         }
1896
1897         if (!ipstealth)
1898                 ip->ip_ttl -= IPTTLDEC;
1899
1900         /*
1901          * If forwarding packet using same interface that it came in on,
1902          * perhaps should send a redirect to sender to shortcut a hop.
1903          * Only send redirect if source is sending directly to us,
1904          * and if packet was not source routed (or has any options).
1905          * Also, don't send redirect if forwarding using a default route
1906          * or a route modified by a redirect.
1907          */
1908         if (rt->rt_ifp == m->m_pkthdr.rcvif &&
1909             !(rt->rt_flags & (RTF_DYNAMIC | RTF_MODIFIED)) &&
1910             satosin(rt_key(rt))->sin_addr.s_addr != INADDR_ANY &&
1911             ipsendredirects && !using_srcrt && next_hop != NULL) {
1912                 u_long src = ntohl(ip->ip_src.s_addr);
1913
1914 #define RTA(rt) ((struct in_ifaddr *)(rt->rt_ifa))
1915                 if (RTA(rt) != NULL &&
1916                     (src & RTA(rt)->ia_subnetmask) == RTA(rt)->ia_subnet) {
1917                         if (rt->rt_flags & RTF_GATEWAY)
1918                                 dest = satosin(rt->rt_gateway)->sin_addr.s_addr;
1919                         else
1920                                 dest = pkt_dst.s_addr;
1921                         /*
1922                          * Router requirements says to only send
1923                          * host redirects.
1924                          */
1925                         type = ICMP_REDIRECT;
1926                         code = ICMP_REDIRECT_HOST;
1927 #ifdef DIAGNOSTIC
1928                         if (ipprintfs)
1929                                 printf("redirect (%d) to %lx\n", code, dest);
1930 #endif
1931                 }
1932         }
1933
1934         if (next_hop) {
1935                 /* Pass IPFORWARD info if available */
1936                 tag.mh_type = MT_TAG;
1937                 tag.mh_flags = PACKET_TAG_IPFORWARD;
1938                 tag.mh_data = (caddr_t)next_hop;
1939                 tag.mh_next = m;
1940                 m = (struct mbuf *)&tag;
1941         }
1942
1943         error = ip_output(m, NULL, &ipforward_rt, IP_FORWARDING, NULL, NULL);
1944
1945         if (error)
1946                 ipstat.ips_cantforward++;
1947         else {
1948                 ipstat.ips_forward++;
1949                 if (type)
1950                         ipstat.ips_redirectsent++;
1951                 else {
1952                         if (mcopy) {
1953                                 ipflow_create(&ipforward_rt, mcopy);
1954                                 m_freem(mcopy);
1955                         }
1956                         return;
1957                 }
1958         }
1959         if (mcopy == NULL)
1960                 return;
1961         destifp = NULL;
1962
1963         switch (error) {
1964
1965         case 0:                         /* forwarded, but need redirect */
1966                 /* type, code set above */
1967                 break;
1968
1969         case ENETUNREACH:               /* shouldn't happen, checked above */
1970         case EHOSTUNREACH:
1971         case ENETDOWN:
1972         case EHOSTDOWN:
1973         default:
1974                 type = ICMP_UNREACH;
1975                 code = ICMP_UNREACH_HOST;
1976                 break;
1977
1978         case EMSGSIZE:
1979                 type = ICMP_UNREACH;
1980                 code = ICMP_UNREACH_NEEDFRAG;
1981 #ifdef IPSEC
1982                 /*
1983                  * If the packet is routed over IPsec tunnel, tell the
1984                  * originator the tunnel MTU.
1985                  *      tunnel MTU = if MTU - sizeof(IP) - ESP/AH hdrsiz
1986                  * XXX quickhack!!!
1987                  */
1988                 if (ipforward_rt.ro_rt != NULL) {
1989                         struct secpolicy *sp = NULL;
1990                         int ipsecerror;
1991                         int ipsechdr;
1992                         struct route *ro;
1993
1994                         sp = ipsec4_getpolicybyaddr(mcopy,
1995                                                     IPSEC_DIR_OUTBOUND,
1996                                                     IP_FORWARDING,
1997                                                     &ipsecerror);
1998
1999                         if (sp == NULL)
2000                                 destifp = ipforward_rt.ro_rt->rt_ifp;
2001                         else {
2002                                 /* count IPsec header size */
2003                                 ipsechdr = ipsec4_hdrsiz(mcopy,
2004                                                          IPSEC_DIR_OUTBOUND,
2005                                                          NULL);
2006
2007                                 /*
2008                                  * find the correct route for outer IPv4
2009                                  * header, compute tunnel MTU.
2010                                  *
2011                                  * XXX BUG ALERT
2012                                  * The "dummyifp" code relies upon the fact
2013                                  * that icmp_error() touches only ifp->if_mtu.
2014                                  */
2015                                 /*XXX*/
2016                                 destifp = NULL;
2017                                 if (sp->req != NULL && sp->req->sav != NULL &&
2018                                     sp->req->sav->sah != NULL) {
2019                                         ro = &sp->req->sav->sah->sa_route;
2020                                         if (ro->ro_rt != NULL &&
2021                                             ro->ro_rt->rt_ifp != NULL) {
2022                                                 dummyifp.if_mtu =
2023                                                     ro->ro_rt->rt_ifp->if_mtu;
2024                                                 dummyifp.if_mtu -= ipsechdr;
2025                                                 destifp = &dummyifp;
2026                                         }
2027                                 }
2028
2029                                 key_freesp(sp);
2030                         }
2031                 }
2032 #elif FAST_IPSEC
2033                 /*
2034                  * If the packet is routed over IPsec tunnel, tell the
2035                  * originator the tunnel MTU.
2036                  *      tunnel MTU = if MTU - sizeof(IP) - ESP/AH hdrsiz
2037                  * XXX quickhack!!!
2038                  */
2039                 if (ipforward_rt.ro_rt != NULL) {
2040                         struct secpolicy *sp = NULL;
2041                         int ipsecerror;
2042                         int ipsechdr;
2043                         struct route *ro;
2044
2045                         sp = ipsec_getpolicybyaddr(mcopy,
2046                                                    IPSEC_DIR_OUTBOUND,
2047                                                    IP_FORWARDING,
2048                                                    &ipsecerror);
2049
2050                         if (sp == NULL)
2051                                 destifp = ipforward_rt.ro_rt->rt_ifp;
2052                         else {
2053                                 /* count IPsec header size */
2054                                 ipsechdr = ipsec4_hdrsiz(mcopy,
2055                                                          IPSEC_DIR_OUTBOUND,
2056                                                          NULL);
2057
2058                                 /*
2059                                  * find the correct route for outer IPv4
2060                                  * header, compute tunnel MTU.
2061                                  *
2062                                  * XXX BUG ALERT
2063                                  * The "dummyifp" code relies upon the fact
2064                                  * that icmp_error() touches only ifp->if_mtu.
2065                                  */
2066                                 /*XXX*/
2067                                 destifp = NULL;
2068                                 if (sp->req != NULL &&
2069                                     sp->req->sav != NULL &&
2070                                     sp->req->sav->sah != NULL) {
2071                                         ro = &sp->req->sav->sah->sa_route;
2072                                         if (ro->ro_rt != NULL &&
2073                                             ro->ro_rt->rt_ifp != NULL) {
2074                                                 dummyifp.if_mtu =
2075                                                     ro->ro_rt->rt_ifp->if_mtu;
2076                                                 dummyifp.if_mtu -= ipsechdr;
2077                                                 destifp = &dummyifp;
2078                                         }
2079                                 }
2080
2081                                 KEY_FREESP(&sp);
2082                         }
2083                 }
2084 #else /* !IPSEC && !FAST_IPSEC */
2085                 if (ipforward_rt.ro_rt != NULL)
2086                         destifp = ipforward_rt.ro_rt->rt_ifp;
2087 #endif /*IPSEC*/
2088                 ipstat.ips_cantfrag++;
2089                 break;
2090
2091         case ENOBUFS:
2092                 /*
2093                  * A router should not generate ICMP_SOURCEQUENCH as
2094                  * required in RFC1812 Requirements for IP Version 4 Routers.
2095                  * Source quench could be a big problem under DoS attacks,
2096                  * or if the underlying interface is rate-limited.
2097                  * Those who need source quench packets may re-enable them
2098                  * via the net.inet.ip.sendsourcequench sysctl.
2099                  */
2100                 if (!ip_sendsourcequench) {
2101                         m_freem(mcopy);
2102                         return;
2103                 } else {
2104                         type = ICMP_SOURCEQUENCH;
2105                         code = 0;
2106                 }
2107                 break;
2108
2109         case EACCES:                    /* ipfw denied packet */
2110                 m_freem(mcopy);
2111                 return;
2112         }
2113         icmp_error(mcopy, type, code, dest, destifp);
2114 }
2115
2116 void
2117 ip_savecontrol(struct inpcb *inp, struct mbuf **mp, struct ip *ip,
2118                struct mbuf *m)
2119 {
2120         if (inp->inp_socket->so_options & SO_TIMESTAMP) {
2121                 struct timeval tv;
2122
2123                 microtime(&tv);
2124                 *mp = sbcreatecontrol((caddr_t) &tv, sizeof(tv),
2125                     SCM_TIMESTAMP, SOL_SOCKET);
2126                 if (*mp)
2127                         mp = &(*mp)->m_next;
2128         }
2129         if (inp->inp_flags & INP_RECVDSTADDR) {
2130                 *mp = sbcreatecontrol((caddr_t) &ip->ip_dst,
2131                     sizeof(struct in_addr), IP_RECVDSTADDR, IPPROTO_IP);
2132                 if (*mp)
2133                         mp = &(*mp)->m_next;
2134         }
2135 #ifdef notyet
2136         /* XXX
2137          * Moving these out of udp_input() made them even more broken
2138          * than they already were.
2139          */
2140         /* options were tossed already */
2141         if (inp->inp_flags & INP_RECVOPTS) {
2142                 *mp = sbcreatecontrol((caddr_t) opts_deleted_above,
2143                     sizeof(struct in_addr), IP_RECVOPTS, IPPROTO_IP);
2144                 if (*mp)
2145                         mp = &(*mp)->m_next;
2146         }
2147         /* ip_srcroute doesn't do what we want here, need to fix */
2148         if (inp->inp_flags & INP_RECVRETOPTS) {
2149                 *mp = sbcreatecontrol((caddr_t) ip_srcroute(),
2150                     sizeof(struct in_addr), IP_RECVRETOPTS, IPPROTO_IP);
2151                 if (*mp)
2152                         mp = &(*mp)->m_next;
2153         }
2154 #endif
2155         if (inp->inp_flags & INP_RECVIF) {
2156                 struct ifnet *ifp;
2157                 struct sdlbuf {
2158                         struct sockaddr_dl sdl;
2159                         u_char  pad[32];
2160                 } sdlbuf;
2161                 struct sockaddr_dl *sdp;
2162                 struct sockaddr_dl *sdl2 = &sdlbuf.sdl;
2163
2164                 if (((ifp = m->m_pkthdr.rcvif)) &&
2165                     ((ifp->if_index != 0) && (ifp->if_index <= if_index))) {
2166                         sdp = (struct sockaddr_dl *)
2167                             ifnet_addrs[ifp->if_index - 1]->ifa_addr;
2168                         /*
2169                          * Change our mind and don't try copy.
2170                          */
2171                         if ((sdp->sdl_family != AF_LINK) ||
2172                             (sdp->sdl_len > sizeof(sdlbuf))) {
2173                                 goto makedummy;
2174                         }
2175                         bcopy(sdp, sdl2, sdp->sdl_len);
2176                 } else {
2177 makedummy:
2178                         sdl2->sdl_len =
2179                             offsetof(struct sockaddr_dl, sdl_data[0]);
2180                         sdl2->sdl_family = AF_LINK;
2181                         sdl2->sdl_index = 0;
2182                         sdl2->sdl_nlen = sdl2->sdl_alen = sdl2->sdl_slen = 0;
2183                 }
2184                 *mp = sbcreatecontrol((caddr_t) sdl2, sdl2->sdl_len,
2185                         IP_RECVIF, IPPROTO_IP);
2186                 if (*mp)
2187                         mp = &(*mp)->m_next;
2188         }
2189 }
2190
2191 /*
2192  * XXX these routines are called from the upper part of the kernel.
2193  *
2194  * They could also be moved to ip_mroute.c, since all the RSVP
2195  *  handling is done there already.
2196  */
2197 int
2198 ip_rsvp_init(struct socket *so)
2199 {
2200         if (so->so_type != SOCK_RAW ||
2201             so->so_proto->pr_protocol != IPPROTO_RSVP)
2202                 return EOPNOTSUPP;
2203
2204         if (ip_rsvpd != NULL)
2205                 return EADDRINUSE;
2206
2207         ip_rsvpd = so;
2208         /*
2209          * This may seem silly, but we need to be sure we don't over-increment
2210          * the RSVP counter, in case something slips up.
2211          */
2212         if (!ip_rsvp_on) {
2213                 ip_rsvp_on = 1;
2214                 rsvp_on++;
2215         }
2216
2217         return 0;
2218 }
2219
2220 int
2221 ip_rsvp_done(void)
2222 {
2223         ip_rsvpd = NULL;
2224         /*
2225          * This may seem silly, but we need to be sure we don't over-decrement
2226          * the RSVP counter, in case something slips up.
2227          */
2228         if (ip_rsvp_on) {
2229                 ip_rsvp_on = 0;
2230                 rsvp_on--;
2231         }
2232         return 0;
2233 }
2234
2235 void
2236 rsvp_input(struct mbuf *m, int off, int proto)  /* XXX must fixup manually */
2237 {
2238         if (rsvp_input_p) { /* call the real one if loaded */
2239                 rsvp_input_p(m, off, proto);
2240                 return;
2241         }
2242
2243         /* Can still get packets with rsvp_on = 0 if there is a local member
2244          * of the group to which the RSVP packet is addressed.  But in this
2245          * case we want to throw the packet away.
2246          */
2247
2248         if (!rsvp_on) {
2249                 m_freem(m);
2250                 return;
2251         }
2252
2253         if (ip_rsvpd != NULL) {
2254                 rip_input(m, off, proto);
2255                 return;
2256         }
2257         /* Drop the packet */
2258         m_freem(m);
2259 }