Change mbug allocation flags from M_ to MB_ to avoid confusion with malloc
[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.27 2004/06/02 14:43:01 eirikn 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         if (pfil_has_hooks(&inet_pfil_hook)) {
568                 odst = ip->ip_dst;
569                 if (pfil_run_hooks(&inet_pfil_hook, &m, 
570                     m->m_pkthdr.rcvif, PFIL_IN)) {
571                         return;
572                 }
573                 if (m == NULL)                  /* consumed by filter */
574                         return;
575                 ip = mtod(m, struct ip *);
576                 using_srcrt = (odst.s_addr != ip->ip_dst.s_addr);
577         }
578 #endif
579
580         if (fw_enable && IPFW_LOADED) {
581                 /*
582                  * If we've been forwarded from the output side, then
583                  * skip the firewall a second time
584                  */
585                 if (args.next_hop)
586                         goto ours;
587
588                 args.m = m;
589                 i = ip_fw_chk_ptr(&args);
590                 m = args.m;
591
592                 if ( (i & IP_FW_PORT_DENY_FLAG) || m == NULL) { /* drop */
593                         if (m)
594                                 m_freem(m);
595                         return;
596                 }
597                 ip = mtod(m, struct ip *); /* just in case m changed */
598                 if (i == 0 && args.next_hop == NULL)    /* common case */
599                         goto pass;
600                 if (DUMMYNET_LOADED && (i & IP_FW_PORT_DYNT_FLAG)) {
601                         /* Send packet to the appropriate pipe */
602                         ip_dn_io_ptr(m, i&0xffff, DN_TO_IP_IN, &args);
603                         return;
604                 }
605 #ifdef IPDIVERT
606                 if (i != 0 && !(i & IP_FW_PORT_DYNT_FLAG)) {
607                         /* Divert or tee packet */
608                         divert_info = i;
609                         goto ours;
610                 }
611 #endif
612                 if (i == 0 && args.next_hop != NULL)
613                         goto pass;
614                 /*
615                  * if we get here, the packet must be dropped
616                  */
617                 m_freem(m);
618                 return;
619         }
620 pass:
621
622         /*
623          * Process options and, if not destined for us,
624          * ship it on.  ip_dooptions returns 1 when an
625          * error was detected (causing an icmp message
626          * to be sent and the original packet to be freed).
627          */
628         ip_nhops = 0;           /* for source routed packets */
629         if (hlen > sizeof(struct ip) && ip_dooptions(m, 0, args.next_hop))
630                 return;
631
632         /* greedy RSVP, snatches any PATH packet of the RSVP protocol and no
633          * matter if it is destined to another node, or whether it is
634          * a multicast one, RSVP wants it! and prevents it from being forwarded
635          * anywhere else. Also checks if the rsvp daemon is running before
636          * grabbing the packet.
637          */
638         if (rsvp_on && ip->ip_p == IPPROTO_RSVP)
639                 goto ours;
640
641         /*
642          * Check our list of addresses, to see if the packet is for us.
643          * If we don't have any addresses, assume any unicast packet
644          * we receive might be for us (and let the upper layers deal
645          * with it).
646          */
647         if (TAILQ_EMPTY(&in_ifaddrhead) && !(m->m_flags & (M_MCAST | M_BCAST)))
648                 goto ours;
649
650         /*
651          * Cache the destination address of the packet; this may be
652          * changed by use of 'ipfw fwd'.
653          */
654         pkt_dst = args.next_hop ? args.next_hop->sin_addr : ip->ip_dst;
655
656         /*
657          * Enable a consistency check between the destination address
658          * and the arrival interface for a unicast packet (the RFC 1122
659          * strong ES model) if IP forwarding is disabled and the packet
660          * is not locally generated and the packet is not subject to
661          * 'ipfw fwd'.
662          *
663          * XXX - Checking also should be disabled if the destination
664          * address is ipnat'ed to a different interface.
665          *
666          * XXX - Checking is incompatible with IP aliases added
667          * to the loopback interface instead of the interface where
668          * the packets are received.
669          */
670         checkif = ip_checkinterface &&
671                   !ipforwarding &&
672                   m->m_pkthdr.rcvif != NULL &&
673                   !(m->m_pkthdr.rcvif->if_flags & IFF_LOOPBACK) &&
674                   (args.next_hop == NULL);
675
676         /*
677          * Check for exact addresses in the hash bucket.
678          */
679         LIST_FOREACH(ia, INADDR_HASH(pkt_dst.s_addr), ia_hash) {
680                 /*
681                  * If the address matches, verify that the packet
682                  * arrived via the correct interface if checking is
683                  * enabled.
684                  */
685                 if (IA_SIN(ia)->sin_addr.s_addr == pkt_dst.s_addr &&
686                     (!checkif || ia->ia_ifp == m->m_pkthdr.rcvif))
687                         goto ours;
688         }
689         /*
690          * Check for broadcast addresses.
691          *
692          * Only accept broadcast packets that arrive via the matching
693          * interface.  Reception of forwarded directed broadcasts would
694          * be handled via ip_forward() and ether_output() with the loopback
695          * into the stack for SIMPLEX interfaces handled by ether_output().
696          */
697         if (m->m_pkthdr.rcvif->if_flags & IFF_BROADCAST) {
698                 TAILQ_FOREACH(ifa, &m->m_pkthdr.rcvif->if_addrhead, ifa_link) {
699                         if (ifa->ifa_addr->sa_family != AF_INET)
700                                 continue;
701                         ia = ifatoia(ifa);
702                         if (satosin(&ia->ia_broadaddr)->sin_addr.s_addr ==
703                                                                 pkt_dst.s_addr)
704                                 goto ours;
705                         if (ia->ia_netbroadcast.s_addr == pkt_dst.s_addr)
706                                 goto ours;
707 #ifdef BOOTP_COMPAT
708                         if (IA_SIN(ia)->sin_addr.s_addr == INADDR_ANY)
709                                 goto ours;
710 #endif
711                 }
712         }
713         if (IN_MULTICAST(ntohl(ip->ip_dst.s_addr))) {
714                 struct in_multi *inm;
715                 if (ip_mrouter) {
716                         /*
717                          * If we are acting as a multicast router, all
718                          * incoming multicast packets are passed to the
719                          * kernel-level multicast forwarding function.
720                          * The packet is returned (relatively) intact; if
721                          * ip_mforward() returns a non-zero value, the packet
722                          * must be discarded, else it may be accepted below.
723                          */
724                         if (ip_mforward &&
725                             ip_mforward(ip, m->m_pkthdr.rcvif, m, NULL) != 0) {
726                                 ipstat.ips_cantforward++;
727                                 m_freem(m);
728                                 return;
729                         }
730
731                         /*
732                          * The process-level routing daemon needs to receive
733                          * all multicast IGMP packets, whether or not this
734                          * host belongs to their destination groups.
735                          */
736                         if (ip->ip_p == IPPROTO_IGMP)
737                                 goto ours;
738                         ipstat.ips_forward++;
739                 }
740                 /*
741                  * See if we belong to the destination multicast group on the
742                  * arrival interface.
743                  */
744                 IN_LOOKUP_MULTI(ip->ip_dst, m->m_pkthdr.rcvif, inm);
745                 if (inm == NULL) {
746                         ipstat.ips_notmember++;
747                         m_freem(m);
748                         return;
749                 }
750                 goto ours;
751         }
752         if (ip->ip_dst.s_addr == INADDR_BROADCAST)
753                 goto ours;
754         if (ip->ip_dst.s_addr == INADDR_ANY)
755                 goto ours;
756
757         /*
758          * FAITH(Firewall Aided Internet Translator)
759          */
760         if (m->m_pkthdr.rcvif && m->m_pkthdr.rcvif->if_type == IFT_FAITH) {
761                 if (ip_keepfaith) {
762                         if (ip->ip_p == IPPROTO_TCP || ip->ip_p == IPPROTO_ICMP)
763                                 goto ours;
764                 }
765                 m_freem(m);
766                 return;
767         }
768
769         /*
770          * Not for us; forward if possible and desirable.
771          */
772         if (!ipforwarding) {
773                 ipstat.ips_cantforward++;
774                 m_freem(m);
775         } else {
776 #ifdef IPSEC
777                 /*
778                  * Enforce inbound IPsec SPD.
779                  */
780                 if (ipsec4_in_reject(m, NULL)) {
781                         ipsecstat.in_polvio++;
782                         goto bad;
783                 }
784 #endif
785 #ifdef FAST_IPSEC
786                 mtag = m_tag_find(m, PACKET_TAG_IPSEC_IN_DONE, NULL);
787                 s = splnet();
788                 if (mtag != NULL) {
789                         tdbi = (struct tdb_ident *)(mtag + 1);
790                         sp = ipsec_getpolicy(tdbi, IPSEC_DIR_INBOUND);
791                 } else {
792                         sp = ipsec_getpolicybyaddr(m, IPSEC_DIR_INBOUND,
793                                                    IP_FORWARDING, &error);
794                 }
795                 if (sp == NULL) {       /* NB: can happen if error */
796                         splx(s);
797                         /*XXX error stat???*/
798                         DPRINTF(("ip_input: no SP for forwarding\n"));  /*XXX*/
799                         goto bad;
800                 }
801
802                 /*
803                  * Check security policy against packet attributes.
804                  */
805                 error = ipsec_in_reject(sp, m);
806                 KEY_FREESP(&sp);
807                 splx(s);
808                 if (error) {
809                         ipstat.ips_cantforward++;
810                         goto bad;
811                 }
812 #endif
813                 ip_forward(m, using_srcrt, args.next_hop);
814         }
815         return;
816
817 ours:
818
819         /*
820          * IPSTEALTH: Process non-routing options only
821          * if the packet is destined for us.
822          */
823         if (ipstealth &&
824             hlen > sizeof(struct ip) &&
825             ip_dooptions(m, 1, args.next_hop))
826                 return;
827
828         /* Count the packet in the ip address stats */
829         if (ia != NULL) {
830                 ia->ia_ifa.if_ipackets++;
831                 ia->ia_ifa.if_ibytes += m->m_pkthdr.len;
832         }
833
834         /*
835          * If offset or IP_MF are set, must reassemble.
836          * Otherwise, nothing need be done.
837          * (We could look in the reassembly queue to see
838          * if the packet was previously fragmented,
839          * but it's not worth the time; just let them time out.)
840          */
841         if (ip->ip_off & (IP_MF | IP_OFFMASK)) {
842
843                 /* If maxnipq is 0, never accept fragments. */
844                 if (maxnipq == 0) {
845                         ipstat.ips_fragments++;
846                         ipstat.ips_fragdropped++;
847                         goto bad;
848                 }
849
850                 sum = IPREASS_HASH(ip->ip_src.s_addr, ip->ip_id);
851                 /*
852                  * Look for queue of fragments
853                  * of this datagram.
854                  */
855                 for (fp = ipq[sum].next; fp != &ipq[sum]; fp = fp->next)
856                         if (ip->ip_id == fp->ipq_id &&
857                             ip->ip_src.s_addr == fp->ipq_src.s_addr &&
858                             ip->ip_dst.s_addr == fp->ipq_dst.s_addr &&
859                             ip->ip_p == fp->ipq_p)
860                                 goto found;
861
862                 fp = NULL;
863
864                 /*
865                  * Enforce upper bound on number of fragmented packets
866                  * for which we attempt reassembly;
867                  * If maxnipq is -1, accept all fragments without limitation.
868                  */
869                 if ((nipq > maxnipq) && (maxnipq > 0)) {
870                         /*
871                          * drop something from the tail of the current queue
872                          * before proceeding further
873                          */
874                         if (ipq[sum].prev == &ipq[sum]) {   /* gak */
875                                 for (i = 0; i < IPREASS_NHASH; i++) {
876                                         if (ipq[i].prev != &ipq[i]) {
877                                                 ipstat.ips_fragtimeout +=
878                                                     ipq[i].prev->ipq_nfrags;
879                                                 ip_freef(ipq[i].prev);
880                                                 break;
881                                         }
882                                 }
883                         } else {
884                                 ipstat.ips_fragtimeout +=
885                                     ipq[sum].prev->ipq_nfrags;
886                                 ip_freef(ipq[sum].prev);
887                         }
888                 }
889 found:
890                 /*
891                  * Adjust ip_len to not reflect header,
892                  * convert offset of this to bytes.
893                  */
894                 ip->ip_len -= hlen;
895                 if (ip->ip_off & IP_MF) {
896                         /*
897                          * Make sure that fragments have a data length
898                          * that's a non-zero multiple of 8 bytes.
899                          */
900                         if (ip->ip_len == 0 || (ip->ip_len & 0x7) != 0) {
901                                 ipstat.ips_toosmall++; /* XXX */
902                                 goto bad;
903                         }
904                         m->m_flags |= M_FRAG;
905                 } else
906                         m->m_flags &= ~M_FRAG;
907                 ip->ip_off <<= 3;
908
909                 /*
910                  * Attempt reassembly; if it succeeds, proceed.
911                  * ip_reass() will return a different mbuf, and update
912                  * the divert info in divert_info and args.divert_rule.
913                  */
914                 ipstat.ips_fragments++;
915                 m->m_pkthdr.header = ip;
916                 m = ip_reass(m, fp, &ipq[sum], &divert_info, &args.divert_rule);
917                 if (m == NULL)
918                         return;
919                 ipstat.ips_reassembled++;
920                 needredispatch = TRUE;
921                 ip = mtod(m, struct ip *);
922                 /* Get the header length of the reassembled packet */
923                 hlen = IP_VHL_HL(ip->ip_vhl) << 2;
924 #ifdef IPDIVERT
925                 /* Restore original checksum before diverting packet */
926                 if (divert_info != 0) {
927                         ip->ip_len += hlen;
928                         ip->ip_len = htons(ip->ip_len);
929                         ip->ip_off = htons(ip->ip_off);
930                         ip->ip_sum = 0;
931                         if (hlen == sizeof(struct ip))
932                                 ip->ip_sum = in_cksum_hdr(ip);
933                         else
934                                 ip->ip_sum = in_cksum(m, hlen);
935                         ip->ip_off = ntohs(ip->ip_off);
936                         ip->ip_len = ntohs(ip->ip_len);
937                         ip->ip_len -= hlen;
938                 }
939 #endif
940         } else {
941                 ip->ip_len -= hlen;
942         }
943
944 #ifdef IPDIVERT
945         /*
946          * Divert or tee packet to the divert protocol if required.
947          */
948         if (divert_info != 0) {
949                 struct mbuf *clone = NULL;
950
951                 /* Clone packet if we're doing a 'tee' */
952                 if ((divert_info & IP_FW_PORT_TEE_FLAG) != 0)
953                         clone = m_dup(m, MB_DONTWAIT);
954
955                 /* Restore packet header fields to original values */
956                 ip->ip_len += hlen;
957                 ip->ip_len = htons(ip->ip_len);
958                 ip->ip_off = htons(ip->ip_off);
959
960                 /* Deliver packet to divert input routine */
961                 divert_packet(m, 1, divert_info & 0xffff, args.divert_rule);
962                 ipstat.ips_delivered++;
963
964                 /* If 'tee', continue with original packet */
965                 if (clone == NULL)
966                         return;
967                 m = clone;
968                 ip = mtod(m, struct ip *);
969                 ip->ip_len += hlen;
970                 /*
971                  * Jump backwards to complete processing of the
972                  * packet. But first clear divert_info to avoid
973                  * entering this block again.
974                  * We do not need to clear args.divert_rule
975                  * or args.next_hop as they will not be used.
976                  */
977                 divert_info = 0;
978                 goto pass;
979         }
980 #endif
981
982 #ifdef IPSEC
983         /*
984          * enforce IPsec policy checking if we are seeing last header.
985          * note that we do not visit this with protocols with pcb layer
986          * code - like udp/tcp/raw ip.
987          */
988         if ((inetsw[ip_protox[ip->ip_p]].pr_flags & PR_LASTHDR) &&
989             ipsec4_in_reject(m, NULL)) {
990                 ipsecstat.in_polvio++;
991                 goto bad;
992         }
993 #endif
994 #if FAST_IPSEC
995         /*
996          * enforce IPsec policy checking if we are seeing last header.
997          * note that we do not visit this with protocols with pcb layer
998          * code - like udp/tcp/raw ip.
999          */
1000         if (inetsw[ip_protox[ip->ip_p]].pr_flags & PR_LASTHDR) {
1001                 /*
1002                  * Check if the packet has already had IPsec processing
1003                  * done.  If so, then just pass it along.  This tag gets
1004                  * set during AH, ESP, etc. input handling, before the
1005                  * packet is returned to the ip input queue for delivery.
1006                  */
1007                 mtag = m_tag_find(m, PACKET_TAG_IPSEC_IN_DONE, NULL);
1008                 s = splnet();
1009                 if (mtag != NULL) {
1010                         tdbi = (struct tdb_ident *)(mtag + 1);
1011                         sp = ipsec_getpolicy(tdbi, IPSEC_DIR_INBOUND);
1012                 } else {
1013                         sp = ipsec_getpolicybyaddr(m, IPSEC_DIR_INBOUND,
1014                                                    IP_FORWARDING, &error);
1015                 }
1016                 if (sp != NULL) {
1017                         /*
1018                          * Check security policy against packet attributes.
1019                          */
1020                         error = ipsec_in_reject(sp, m);
1021                         KEY_FREESP(&sp);
1022                 } else {
1023                         /* XXX error stat??? */
1024                         error = EINVAL;
1025 DPRINTF(("ip_input: no SP, packet discarded\n"));/*XXX*/
1026                         goto bad;
1027                 }
1028                 splx(s);
1029                 if (error)
1030                         goto bad;
1031         }
1032 #endif /* FAST_IPSEC */
1033
1034         ipstat.ips_delivered++;
1035         if (needredispatch) {
1036                 struct netmsg_transport_packet *msg;
1037                 lwkt_port_t port;
1038
1039                 msg = malloc(sizeof(struct netmsg_transport_packet),
1040                                 M_LWKTMSG, M_INTWAIT | M_NULLOK);
1041                 if (msg == NULL)
1042                         goto bad;
1043
1044                 lwkt_initmsg(&msg->nm_lmsg, &netisr_afree_rport, 0,
1045                         lwkt_cmd_func(transport_processing_handler),
1046                         lwkt_cmd_op_none);
1047                 msg->nm_mbuf = m;
1048                 msg->nm_hlen = hlen;
1049                 msg->nm_hasnexthop = (args.next_hop != NULL);
1050                 if (msg->nm_hasnexthop)
1051                         msg->nm_nexthop = *args.next_hop;  /* structure copy */
1052
1053                 ip->ip_off = htons(ip->ip_off);
1054                 ip->ip_len = htons(ip->ip_len);
1055                 port = ip_mport(m);
1056                 if (port == NULL)
1057                         goto bad;
1058                 ip->ip_len = ntohs(ip->ip_len);
1059                 ip->ip_off = ntohs(ip->ip_off);
1060
1061                 lwkt_sendmsg(port, &msg->nm_lmsg);
1062         } else {
1063                 transport_processing_oncpu(m, hlen, ip, args.next_hop);
1064         }
1065         return;
1066
1067 bad:
1068         m_freem(m);
1069 }
1070
1071 /*
1072  * Take incoming datagram fragment and try to reassemble it into
1073  * whole datagram.  If a chain for reassembly of this datagram already
1074  * exists, then it is given as fp; otherwise have to make a chain.
1075  *
1076  * When IPDIVERT enabled, keep additional state with each packet that
1077  * tells us if we need to divert or tee the packet we're building.
1078  * In particular, *divinfo includes the port and TEE flag,
1079  * *divert_rule is the number of the matching rule.
1080  */
1081
1082 static struct mbuf *
1083 ip_reass(struct mbuf *m, struct ipq *fp, struct ipq *where,
1084          u_int32_t *divinfo, u_int16_t *divert_rule)
1085 {
1086         struct ip *ip = mtod(m, struct ip *);
1087         struct mbuf *p = NULL, *q, *nq;
1088         struct mbuf *t;
1089         int hlen = IP_VHL_HL(ip->ip_vhl) << 2;
1090         int i, next;
1091
1092         /*
1093          * Presence of header sizes in mbufs
1094          * would confuse code below.
1095          */
1096         m->m_data += hlen;
1097         m->m_len -= hlen;
1098
1099         /*
1100          * If first fragment to arrive, create a reassembly queue.
1101          */
1102         if (fp == NULL) {
1103                 if ((t = m_get(MB_DONTWAIT, MT_FTABLE)) == NULL)
1104                         goto dropfrag;
1105                 fp = mtod(t, struct ipq *);
1106                 insque(fp, where);
1107                 nipq++;
1108                 fp->ipq_nfrags = 1;
1109                 fp->ipq_ttl = IPFRAGTTL;
1110                 fp->ipq_p = ip->ip_p;
1111                 fp->ipq_id = ip->ip_id;
1112                 fp->ipq_src = ip->ip_src;
1113                 fp->ipq_dst = ip->ip_dst;
1114                 fp->ipq_frags = m;
1115                 m->m_nextpkt = NULL;
1116 #ifdef IPDIVERT
1117                 fp->ipq_div_info = 0;
1118                 fp->ipq_div_cookie = 0;
1119 #endif
1120                 goto inserted;
1121         } else {
1122                 fp->ipq_nfrags++;
1123         }
1124
1125 #define GETIP(m)        ((struct ip*)((m)->m_pkthdr.header))
1126
1127         /*
1128          * Find a segment which begins after this one does.
1129          */
1130         for (p = NULL, q = fp->ipq_frags; q; p = q, q = q->m_nextpkt)
1131                 if (GETIP(q)->ip_off > ip->ip_off)
1132                         break;
1133
1134         /*
1135          * If there is a preceding segment, it may provide some of
1136          * our data already.  If so, drop the data from the incoming
1137          * segment.  If it provides all of our data, drop us, otherwise
1138          * stick new segment in the proper place.
1139          *
1140          * If some of the data is dropped from the the preceding
1141          * segment, then it's checksum is invalidated.
1142          */
1143         if (p) {
1144                 i = GETIP(p)->ip_off + GETIP(p)->ip_len - ip->ip_off;
1145                 if (i > 0) {
1146                         if (i >= ip->ip_len)
1147                                 goto dropfrag;
1148                         m_adj(m, i);
1149                         m->m_pkthdr.csum_flags = 0;
1150                         ip->ip_off += i;
1151                         ip->ip_len -= i;
1152                 }
1153                 m->m_nextpkt = p->m_nextpkt;
1154                 p->m_nextpkt = m;
1155         } else {
1156                 m->m_nextpkt = fp->ipq_frags;
1157                 fp->ipq_frags = m;
1158         }
1159
1160         /*
1161          * While we overlap succeeding segments trim them or,
1162          * if they are completely covered, dequeue them.
1163          */
1164         for (; q != NULL && ip->ip_off + ip->ip_len > GETIP(q)->ip_off;
1165              q = nq) {
1166                 i = (ip->ip_off + ip->ip_len) - GETIP(q)->ip_off;
1167                 if (i < GETIP(q)->ip_len) {
1168                         GETIP(q)->ip_len -= i;
1169                         GETIP(q)->ip_off += i;
1170                         m_adj(q, i);
1171                         q->m_pkthdr.csum_flags = 0;
1172                         break;
1173                 }
1174                 nq = q->m_nextpkt;
1175                 m->m_nextpkt = nq;
1176                 ipstat.ips_fragdropped++;
1177                 fp->ipq_nfrags--;
1178                 m_freem(q);
1179         }
1180
1181 inserted:
1182
1183 #ifdef IPDIVERT
1184         /*
1185          * Transfer firewall instructions to the fragment structure.
1186          * Only trust info in the fragment at offset 0.
1187          */
1188         if (ip->ip_off == 0) {
1189                 fp->ipq_div_info = *divinfo;
1190                 fp->ipq_div_cookie = *divert_rule;
1191         }
1192         *divinfo = 0;
1193         *divert_rule = 0;
1194 #endif
1195
1196         /*
1197          * Check for complete reassembly and perform frag per packet
1198          * limiting.
1199          *
1200          * Frag limiting is performed here so that the nth frag has
1201          * a chance to complete the packet before we drop the packet.
1202          * As a result, n+1 frags are actually allowed per packet, but
1203          * only n will ever be stored. (n = maxfragsperpacket.)
1204          *
1205          */
1206         next = 0;
1207         for (p = NULL, q = fp->ipq_frags; q; p = q, q = q->m_nextpkt) {
1208                 if (GETIP(q)->ip_off != next) {
1209                         if (fp->ipq_nfrags > maxfragsperpacket) {
1210                                 ipstat.ips_fragdropped += fp->ipq_nfrags;
1211                                 ip_freef(fp);
1212                         }
1213                         return (NULL);
1214                 }
1215                 next += GETIP(q)->ip_len;
1216         }
1217         /* Make sure the last packet didn't have the IP_MF flag */
1218         if (p->m_flags & M_FRAG) {
1219                 if (fp->ipq_nfrags > maxfragsperpacket) {
1220                         ipstat.ips_fragdropped += fp->ipq_nfrags;
1221                         ip_freef(fp);
1222                 }
1223                 return (NULL);
1224         }
1225
1226         /*
1227          * Reassembly is complete.  Make sure the packet is a sane size.
1228          */
1229         q = fp->ipq_frags;
1230         ip = GETIP(q);
1231         if (next + (IP_VHL_HL(ip->ip_vhl) << 2) > IP_MAXPACKET) {
1232                 ipstat.ips_toolong++;
1233                 ipstat.ips_fragdropped += fp->ipq_nfrags;
1234                 ip_freef(fp);
1235                 return (NULL);
1236         }
1237
1238         /*
1239          * Concatenate fragments.
1240          */
1241         m = q;
1242         t = m->m_next;
1243         m->m_next = NULL;
1244         m_cat(m, t);
1245         nq = q->m_nextpkt;
1246         q->m_nextpkt = NULL;
1247         for (q = nq; q != NULL; q = nq) {
1248                 nq = q->m_nextpkt;
1249                 q->m_nextpkt = NULL;
1250                 m->m_pkthdr.csum_flags &= q->m_pkthdr.csum_flags;
1251                 m->m_pkthdr.csum_data += q->m_pkthdr.csum_data;
1252                 m_cat(m, q);
1253         }
1254
1255 #ifdef IPDIVERT
1256         /*
1257          * Extract firewall instructions from the fragment structure.
1258          */
1259         *divinfo = fp->ipq_div_info;
1260         *divert_rule = fp->ipq_div_cookie;
1261 #endif
1262
1263         /*
1264          * Create header for new ip packet by
1265          * modifying header of first packet;
1266          * dequeue and discard fragment reassembly header.
1267          * Make header visible.
1268          */
1269         ip->ip_len = next;
1270         ip->ip_src = fp->ipq_src;
1271         ip->ip_dst = fp->ipq_dst;
1272         remque(fp);
1273         nipq--;
1274         (void) m_free(dtom(fp));
1275         m->m_len += (IP_VHL_HL(ip->ip_vhl) << 2);
1276         m->m_data -= (IP_VHL_HL(ip->ip_vhl) << 2);
1277         /* some debugging cruft by sklower, below, will go away soon */
1278         if (m->m_flags & M_PKTHDR) { /* XXX this should be done elsewhere */
1279                 int plen = 0;
1280
1281                 for (t = m; t; t = t->m_next)
1282                         plen += t->m_len;
1283                 m->m_pkthdr.len = plen;
1284         }
1285         return (m);
1286
1287 dropfrag:
1288 #ifdef IPDIVERT
1289         *divinfo = 0;
1290         *divert_rule = 0;
1291 #endif
1292         ipstat.ips_fragdropped++;
1293         if (fp != NULL)
1294                 fp->ipq_nfrags--;
1295         m_freem(m);
1296         return (NULL);
1297
1298 #undef GETIP
1299 }
1300
1301 /*
1302  * Free a fragment reassembly header and all
1303  * associated datagrams.
1304  */
1305 static void
1306 ip_freef(struct ipq *fp)
1307 {
1308         struct mbuf *q;
1309
1310         while (fp->ipq_frags) {
1311                 q = fp->ipq_frags;
1312                 fp->ipq_frags = q->m_nextpkt;
1313                 m_freem(q);
1314         }
1315         remque(fp);
1316         (void) m_free(dtom(fp));
1317         nipq--;
1318 }
1319
1320 /*
1321  * IP timer processing;
1322  * if a timer expires on a reassembly
1323  * queue, discard it.
1324  */
1325 void
1326 ip_slowtimo()
1327 {
1328         struct ipq *fp;
1329         int s = splnet();
1330         int i;
1331
1332         for (i = 0; i < IPREASS_NHASH; i++) {
1333                 fp = ipq[i].next;
1334                 if (fp == NULL)
1335                         continue;
1336                 while (fp != &ipq[i]) {
1337                         --fp->ipq_ttl;
1338                         fp = fp->next;
1339                         if (fp->prev->ipq_ttl == 0) {
1340                                 ipstat.ips_fragtimeout += fp->prev->ipq_nfrags;
1341                                 ip_freef(fp->prev);
1342                         }
1343                 }
1344         }
1345         /*
1346          * If we are over the maximum number of fragments
1347          * (due to the limit being lowered), drain off
1348          * enough to get down to the new limit.
1349          */
1350         if (maxnipq >= 0 && nipq > maxnipq) {
1351                 for (i = 0; i < IPREASS_NHASH; i++) {
1352                         while (nipq > maxnipq &&
1353                                 (ipq[i].next != &ipq[i])) {
1354                                 ipstat.ips_fragdropped +=
1355                                     ipq[i].next->ipq_nfrags;
1356                                 ip_freef(ipq[i].next);
1357                         }
1358                 }
1359         }
1360         ipflow_slowtimo();
1361         splx(s);
1362 }
1363
1364 /*
1365  * Drain off all datagram fragments.
1366  */
1367 void
1368 ip_drain()
1369 {
1370         int i;
1371
1372         for (i = 0; i < IPREASS_NHASH; i++) {
1373                 while (ipq[i].next != &ipq[i]) {
1374                         ipstat.ips_fragdropped += ipq[i].next->ipq_nfrags;
1375                         ip_freef(ipq[i].next);
1376                 }
1377         }
1378         in_rtqdrain();
1379 }
1380
1381 /*
1382  * Do option processing on a datagram,
1383  * possibly discarding it if bad options are encountered,
1384  * or forwarding it if source-routed.
1385  * The pass argument is used when operating in the IPSTEALTH
1386  * mode to tell what options to process:
1387  * [LS]SRR (pass 0) or the others (pass 1).
1388  * The reason for as many as two passes is that when doing IPSTEALTH,
1389  * non-routing options should be processed only if the packet is for us.
1390  * Returns 1 if packet has been forwarded/freed,
1391  * 0 if the packet should be processed further.
1392  */
1393 static int
1394 ip_dooptions(struct mbuf *m, int pass, struct sockaddr_in *next_hop)
1395 {
1396         struct ip *ip = mtod(m, struct ip *);
1397         u_char *cp;
1398         struct in_ifaddr *ia;
1399         int opt, optlen, cnt, off, code, type = ICMP_PARAMPROB;
1400         boolean_t forward = FALSE;
1401         struct in_addr *sin, dst;
1402         n_time ntime;
1403
1404         dst = ip->ip_dst;
1405         cp = (u_char *)(ip + 1);
1406         cnt = (IP_VHL_HL(ip->ip_vhl) << 2) - sizeof(struct ip);
1407         for (; cnt > 0; cnt -= optlen, cp += optlen) {
1408                 opt = cp[IPOPT_OPTVAL];
1409                 if (opt == IPOPT_EOL)
1410                         break;
1411                 if (opt == IPOPT_NOP)
1412                         optlen = 1;
1413                 else {
1414                         if (cnt < IPOPT_OLEN + sizeof(*cp)) {
1415                                 code = &cp[IPOPT_OLEN] - (u_char *)ip;
1416                                 goto bad;
1417                         }
1418                         optlen = cp[IPOPT_OLEN];
1419                         if (optlen < IPOPT_OLEN + sizeof(*cp) || optlen > cnt) {
1420                                 code = &cp[IPOPT_OLEN] - (u_char *)ip;
1421                                 goto bad;
1422                         }
1423                 }
1424                 switch (opt) {
1425
1426                 default:
1427                         break;
1428
1429                 /*
1430                  * Source routing with record.
1431                  * Find interface with current destination address.
1432                  * If none on this machine then drop if strictly routed,
1433                  * or do nothing if loosely routed.
1434                  * Record interface address and bring up next address
1435                  * component.  If strictly routed make sure next
1436                  * address is on directly accessible net.
1437                  */
1438                 case IPOPT_LSRR:
1439                 case IPOPT_SSRR:
1440                         if (ipstealth && pass > 0)
1441                                 break;
1442                         if (optlen < IPOPT_OFFSET + sizeof(*cp)) {
1443                                 code = &cp[IPOPT_OLEN] - (u_char *)ip;
1444                                 goto bad;
1445                         }
1446                         if ((off = cp[IPOPT_OFFSET]) < IPOPT_MINOFF) {
1447                                 code = &cp[IPOPT_OFFSET] - (u_char *)ip;
1448                                 goto bad;
1449                         }
1450                         ipaddr.sin_addr = ip->ip_dst;
1451                         ia = (struct in_ifaddr *)
1452                                 ifa_ifwithaddr((struct sockaddr *)&ipaddr);
1453                         if (ia == NULL) {
1454                                 if (opt == IPOPT_SSRR) {
1455                                         type = ICMP_UNREACH;
1456                                         code = ICMP_UNREACH_SRCFAIL;
1457                                         goto bad;
1458                                 }
1459                                 if (!ip_dosourceroute)
1460                                         goto nosourcerouting;
1461                                 /*
1462                                  * Loose routing, and not at next destination
1463                                  * yet; nothing to do except forward.
1464                                  */
1465                                 break;
1466                         }
1467                         off--;                  /* 0 origin */
1468                         if (off > optlen - (int)sizeof(struct in_addr)) {
1469                                 /*
1470                                  * End of source route.  Should be for us.
1471                                  */
1472                                 if (!ip_acceptsourceroute)
1473                                         goto nosourcerouting;
1474                                 save_rte(cp, ip->ip_src);
1475                                 break;
1476                         }
1477                         if (ipstealth)
1478                                 goto dropit;
1479                         if (!ip_dosourceroute) {
1480                                 if (ipforwarding) {
1481                                         char buf[16]; /* aaa.bbb.ccc.ddd\0 */
1482                                         /*
1483                                          * Acting as a router, so generate ICMP
1484                                          */
1485 nosourcerouting:
1486                                         strcpy(buf, inet_ntoa(ip->ip_dst));
1487                                         log(LOG_WARNING,
1488                                             "attempted source route from %s to %s\n",
1489                                             inet_ntoa(ip->ip_src), buf);
1490                                         type = ICMP_UNREACH;
1491                                         code = ICMP_UNREACH_SRCFAIL;
1492                                         goto bad;
1493                                 } else {
1494                                         /*
1495                                          * Not acting as a router,
1496                                          * so silently drop.
1497                                          */
1498 dropit:
1499                                         ipstat.ips_cantforward++;
1500                                         m_freem(m);
1501                                         return (1);
1502                                 }
1503                         }
1504
1505                         /*
1506                          * locate outgoing interface
1507                          */
1508                         (void)memcpy(&ipaddr.sin_addr, cp + off,
1509                             sizeof(ipaddr.sin_addr));
1510
1511                         if (opt == IPOPT_SSRR) {
1512 #define INA     struct in_ifaddr *
1513 #define SA      struct sockaddr *
1514                                 if ((ia = (INA)ifa_ifwithdstaddr((SA)&ipaddr))
1515                                                                         == NULL)
1516                                         ia = (INA)ifa_ifwithnet((SA)&ipaddr);
1517                         } else
1518                                 ia = ip_rtaddr(ipaddr.sin_addr, &ipforward_rt);
1519                         if (ia == NULL) {
1520                                 type = ICMP_UNREACH;
1521                                 code = ICMP_UNREACH_SRCFAIL;
1522                                 goto bad;
1523                         }
1524                         ip->ip_dst = ipaddr.sin_addr;
1525                         (void)memcpy(cp + off, &(IA_SIN(ia)->sin_addr),
1526                             sizeof(struct in_addr));
1527                         cp[IPOPT_OFFSET] += sizeof(struct in_addr);
1528                         /*
1529                          * Let ip_intr's mcast routing check handle mcast pkts
1530                          */
1531                         forward = !IN_MULTICAST(ntohl(ip->ip_dst.s_addr));
1532                         break;
1533
1534                 case IPOPT_RR:
1535                         if (ipstealth && pass == 0)
1536                                 break;
1537                         if (optlen < IPOPT_OFFSET + sizeof(*cp)) {
1538                                 code = &cp[IPOPT_OFFSET] - (u_char *)ip;
1539                                 goto bad;
1540                         }
1541                         if ((off = cp[IPOPT_OFFSET]) < IPOPT_MINOFF) {
1542                                 code = &cp[IPOPT_OFFSET] - (u_char *)ip;
1543                                 goto bad;
1544                         }
1545                         /*
1546                          * If no space remains, ignore.
1547                          */
1548                         off--;                  /* 0 origin */
1549                         if (off > optlen - (int)sizeof(struct in_addr))
1550                                 break;
1551                         (void)memcpy(&ipaddr.sin_addr, &ip->ip_dst,
1552                             sizeof(ipaddr.sin_addr));
1553                         /*
1554                          * locate outgoing interface; if we're the destination,
1555                          * use the incoming interface (should be same).
1556                          */
1557                         if ((ia = (INA)ifa_ifwithaddr((SA)&ipaddr)) == NULL &&
1558                             (ia = ip_rtaddr(ipaddr.sin_addr, &ipforward_rt))
1559                                                                      == NULL) {
1560                                 type = ICMP_UNREACH;
1561                                 code = ICMP_UNREACH_HOST;
1562                                 goto bad;
1563                         }
1564                         (void)memcpy(cp + off, &(IA_SIN(ia)->sin_addr),
1565                             sizeof(struct in_addr));
1566                         cp[IPOPT_OFFSET] += sizeof(struct in_addr);
1567                         break;
1568
1569                 case IPOPT_TS:
1570                         if (ipstealth && pass == 0)
1571                                 break;
1572                         code = cp - (u_char *)ip;
1573                         if (optlen < 4 || optlen > 40) {
1574                                 code = &cp[IPOPT_OLEN] - (u_char *)ip;
1575                                 goto bad;
1576                         }
1577                         if ((off = cp[IPOPT_OFFSET]) < 5) {
1578                                 code = &cp[IPOPT_OLEN] - (u_char *)ip;
1579                                 goto bad;
1580                         }
1581                         if (off > optlen - (int)sizeof(int32_t)) {
1582                                 cp[IPOPT_OFFSET + 1] += (1 << 4);
1583                                 if ((cp[IPOPT_OFFSET + 1] & 0xf0) == 0) {
1584                                         code = &cp[IPOPT_OFFSET] - (u_char *)ip;
1585                                         goto bad;
1586                                 }
1587                                 break;
1588                         }
1589                         off--;                          /* 0 origin */
1590                         sin = (struct in_addr *)(cp + off);
1591                         switch (cp[IPOPT_OFFSET + 1] & 0x0f) {
1592
1593                         case IPOPT_TS_TSONLY:
1594                                 break;
1595
1596                         case IPOPT_TS_TSANDADDR:
1597                                 if (off + sizeof(n_time) +
1598                                     sizeof(struct in_addr) > optlen) {
1599                                         code = &cp[IPOPT_OFFSET] - (u_char *)ip;
1600                                         goto bad;
1601                                 }
1602                                 ipaddr.sin_addr = dst;
1603                                 ia = (INA)ifaof_ifpforaddr((SA)&ipaddr,
1604                                                             m->m_pkthdr.rcvif);
1605                                 if (ia == NULL)
1606                                         continue;
1607                                 (void)memcpy(sin, &IA_SIN(ia)->sin_addr,
1608                                     sizeof(struct in_addr));
1609                                 cp[IPOPT_OFFSET] += sizeof(struct in_addr);
1610                                 off += sizeof(struct in_addr);
1611                                 break;
1612
1613                         case IPOPT_TS_PRESPEC:
1614                                 if (off + sizeof(n_time) +
1615                                     sizeof(struct in_addr) > optlen) {
1616                                         code = &cp[IPOPT_OFFSET] - (u_char *)ip;
1617                                         goto bad;
1618                                 }
1619                                 (void)memcpy(&ipaddr.sin_addr, sin,
1620                                     sizeof(struct in_addr));
1621                                 if (ifa_ifwithaddr((SA)&ipaddr) == NULL)
1622                                         continue;
1623                                 cp[IPOPT_OFFSET] += sizeof(struct in_addr);
1624                                 off += sizeof(struct in_addr);
1625                                 break;
1626
1627                         default:
1628                                 code = &cp[IPOPT_OFFSET + 1] - (u_char *)ip;
1629                                 goto bad;
1630                         }
1631                         ntime = iptime();
1632                         (void)memcpy(cp + off, &ntime, sizeof(n_time));
1633                         cp[IPOPT_OFFSET] += sizeof(n_time);
1634                 }
1635         }
1636         if (forward && ipforwarding) {
1637                 ip_forward(m, 1, next_hop);
1638                 return (1);
1639         }
1640         return (0);
1641 bad:
1642         icmp_error(m, type, code, 0, NULL);
1643         ipstat.ips_badoptions++;
1644         return (1);
1645 }
1646
1647 /*
1648  * Given address of next destination (final or next hop),
1649  * return internet address info of interface to be used to get there.
1650  */
1651 struct in_ifaddr *
1652 ip_rtaddr(struct in_addr dst, struct route *rt)
1653 {
1654         struct sockaddr_in *sin;
1655
1656         sin = (struct sockaddr_in *)&rt->ro_dst;
1657
1658         if (rt->ro_rt == NULL || dst.s_addr != sin->sin_addr.s_addr) {
1659                 if (rt->ro_rt != NULL) {
1660                         RTFREE(rt->ro_rt);
1661                         rt->ro_rt = NULL;
1662                 }
1663                 sin->sin_family = AF_INET;
1664                 sin->sin_len = sizeof(*sin);
1665                 sin->sin_addr = dst;
1666                 rtalloc_ign(rt, RTF_PRCLONING);
1667         }
1668
1669         if (rt->ro_rt == NULL)
1670                 return (NULL);
1671
1672         return (ifatoia(rt->ro_rt->rt_ifa));
1673 }
1674
1675 /*
1676  * Save incoming source route for use in replies,
1677  * to be picked up later by ip_srcroute if the receiver is interested.
1678  */
1679 void
1680 save_rte(u_char *option, struct in_addr dst)
1681 {
1682         unsigned olen;
1683
1684         olen = option[IPOPT_OLEN];
1685 #ifdef DIAGNOSTIC
1686         if (ipprintfs)
1687                 printf("save_rte: olen %d\n", olen);
1688 #endif
1689         if (olen > sizeof(ip_srcrt) - (1 + sizeof(dst)))
1690                 return;
1691         bcopy(option, ip_srcrt.srcopt, olen);
1692         ip_nhops = (olen - IPOPT_OFFSET - 1) / sizeof(struct in_addr);
1693         ip_srcrt.dst = dst;
1694 }
1695
1696 /*
1697  * Retrieve incoming source route for use in replies,
1698  * in the same form used by setsockopt.
1699  * The first hop is placed before the options, will be removed later.
1700  */
1701 struct mbuf *
1702 ip_srcroute()
1703 {
1704         struct in_addr *p, *q;
1705         struct mbuf *m;
1706
1707         if (ip_nhops == 0)
1708                 return (NULL);
1709         m = m_get(MB_DONTWAIT, MT_HEADER);
1710         if (m == NULL)
1711                 return (NULL);
1712
1713 #define OPTSIZ  (sizeof(ip_srcrt.nop) + sizeof(ip_srcrt.srcopt))
1714
1715         /* length is (nhops+1)*sizeof(addr) + sizeof(nop + srcrt header) */
1716         m->m_len = ip_nhops * sizeof(struct in_addr) + sizeof(struct in_addr) +
1717             OPTSIZ;
1718 #ifdef DIAGNOSTIC
1719         if (ipprintfs)
1720                 printf("ip_srcroute: nhops %d mlen %d", ip_nhops, m->m_len);
1721 #endif
1722
1723         /*
1724          * First save first hop for return route
1725          */
1726         p = &ip_srcrt.route[ip_nhops - 1];
1727         *(mtod(m, struct in_addr *)) = *p--;
1728 #ifdef DIAGNOSTIC
1729         if (ipprintfs)
1730                 printf(" hops %lx", ntohl(mtod(m, struct in_addr *)->s_addr));
1731 #endif
1732
1733         /*
1734          * Copy option fields and padding (nop) to mbuf.
1735          */
1736         ip_srcrt.nop = IPOPT_NOP;
1737         ip_srcrt.srcopt[IPOPT_OFFSET] = IPOPT_MINOFF;
1738         (void)memcpy(mtod(m, caddr_t) + sizeof(struct in_addr), &ip_srcrt.nop,
1739             OPTSIZ);
1740         q = (struct in_addr *)(mtod(m, caddr_t) +
1741             sizeof(struct in_addr) + OPTSIZ);
1742 #undef OPTSIZ
1743         /*
1744          * Record return path as an IP source route,
1745          * reversing the path (pointers are now aligned).
1746          */
1747         while (p >= ip_srcrt.route) {
1748 #ifdef DIAGNOSTIC
1749                 if (ipprintfs)
1750                         printf(" %lx", ntohl(q->s_addr));
1751 #endif
1752                 *q++ = *p--;
1753         }
1754         /*
1755          * Last hop goes to final destination.
1756          */
1757         *q = ip_srcrt.dst;
1758 #ifdef DIAGNOSTIC
1759         if (ipprintfs)
1760                 printf(" %lx\n", ntohl(q->s_addr));
1761 #endif
1762         return (m);
1763 }
1764
1765 /*
1766  * Strip out IP options.
1767  */
1768 void
1769 ip_stripoptions(struct mbuf *m)
1770 {
1771         int datalen;
1772         struct ip *ip = mtod(m, struct ip *);
1773         caddr_t opts;
1774         int optlen;
1775
1776         optlen = (IP_VHL_HL(ip->ip_vhl) << 2) - sizeof(struct ip);
1777         opts = (caddr_t)(ip + 1);
1778         datalen = m->m_len - (sizeof(struct ip) + optlen);
1779         bcopy(opts + optlen, opts, datalen);
1780         m->m_len -= optlen;
1781         if (m->m_flags & M_PKTHDR)
1782                 m->m_pkthdr.len -= optlen;
1783         ip->ip_vhl = IP_MAKE_VHL(IPVERSION, sizeof(struct ip) >> 2);
1784 }
1785
1786 u_char inetctlerrmap[PRC_NCMDS] = {
1787         0,              0,              0,              0,
1788         0,              EMSGSIZE,       EHOSTDOWN,      EHOSTUNREACH,
1789         EHOSTUNREACH,   EHOSTUNREACH,   ECONNREFUSED,   ECONNREFUSED,
1790         EMSGSIZE,       EHOSTUNREACH,   0,              0,
1791         0,              0,              0,              0,
1792         ENOPROTOOPT,    ECONNREFUSED
1793 };
1794
1795 /*
1796  * Forward a packet.  If some error occurs return the sender
1797  * an icmp packet.  Note we can't always generate a meaningful
1798  * icmp message because icmp doesn't have a large enough repertoire
1799  * of codes and types.
1800  *
1801  * If not forwarding, just drop the packet.  This could be confusing
1802  * if ipforwarding was zero but some routing protocol was advancing
1803  * us as a gateway to somewhere.  However, we must let the routing
1804  * protocol deal with that.
1805  *
1806  * The using_srcrt parameter indicates whether the packet is being forwarded
1807  * via a source route.
1808  */
1809 static void
1810 ip_forward(struct mbuf *m, int using_srcrt, struct sockaddr_in *next_hop)
1811 {
1812         struct ip *ip = mtod(m, struct ip *);
1813         struct sockaddr_in *sin;
1814         struct rtentry *rt;
1815         int error, type = 0, code = 0;
1816         struct mbuf *mcopy;
1817         n_long dest;
1818         struct in_addr pkt_dst;
1819         struct ifnet *destifp;
1820         struct m_hdr tag;
1821 #if defined(IPSEC) || defined(FAST_IPSEC)
1822         struct ifnet dummyifp;
1823 #endif
1824
1825         dest = 0;
1826         /*
1827          * Cache the destination address of the packet; this may be
1828          * changed by use of 'ipfw fwd'.
1829          */
1830         pkt_dst = next_hop ? next_hop->sin_addr : ip->ip_dst;
1831
1832 #ifdef DIAGNOSTIC
1833         if (ipprintfs)
1834                 printf("forward: src %x dst %x ttl %x\n",
1835                        ip->ip_src.s_addr, pkt_dst.s_addr, ip->ip_ttl);
1836 #endif
1837
1838         if (m->m_flags & (M_BCAST | M_MCAST) || !in_canforward(pkt_dst)) {
1839                 ipstat.ips_cantforward++;
1840                 m_freem(m);
1841                 return;
1842         }
1843         if (!ipstealth && ip->ip_ttl <= IPTTLDEC) {
1844                 icmp_error(m, ICMP_TIMXCEED, ICMP_TIMXCEED_INTRANS, dest, NULL);
1845                 return;
1846         }
1847
1848         sin = (struct sockaddr_in *)&ipforward_rt.ro_dst;
1849         if ((rt = ipforward_rt.ro_rt) == NULL ||
1850             pkt_dst.s_addr != sin->sin_addr.s_addr) {
1851                 if (ipforward_rt.ro_rt != NULL) {
1852                         RTFREE(ipforward_rt.ro_rt);
1853                         ipforward_rt.ro_rt = NULL;
1854                 }
1855                 sin->sin_family = AF_INET;
1856                 sin->sin_len = sizeof(*sin);
1857                 sin->sin_addr = pkt_dst;
1858
1859                 rtalloc_ign(&ipforward_rt, RTF_PRCLONING);
1860                 if (ipforward_rt.ro_rt == NULL) {
1861                         icmp_error(m, ICMP_UNREACH, ICMP_UNREACH_HOST, dest,
1862                                    NULL);
1863                         return;
1864                 }
1865                 rt = ipforward_rt.ro_rt;
1866         }
1867
1868         /*
1869          * Save the IP header and at most 8 bytes of the payload,
1870          * in case we need to generate an ICMP message to the src.
1871          *
1872          * XXX this can be optimized a lot by saving the data in a local
1873          * buffer on the stack (72 bytes at most), and only allocating the
1874          * mbuf if really necessary. The vast majority of the packets
1875          * are forwarded without having to send an ICMP back (either
1876          * because unnecessary, or because rate limited), so we are
1877          * really we are wasting a lot of work here.
1878          *
1879          * We don't use m_copy() because it might return a reference
1880          * to a shared cluster. Both this function and ip_output()
1881          * assume exclusive access to the IP header in `m', so any
1882          * data in a cluster may change before we reach icmp_error().
1883          */
1884         MGET(mcopy, MB_DONTWAIT, m->m_type);
1885         if (mcopy != NULL && !m_dup_pkthdr(mcopy, m, MB_DONTWAIT)) {
1886                 /*
1887                  * It's probably ok if the pkthdr dup fails (because
1888                  * the deep copy of the tag chain failed), but for now
1889                  * be conservative and just discard the copy since
1890                  * code below may some day want the tags.
1891                  */
1892                 m_free(mcopy);
1893                 mcopy = NULL;
1894         }
1895         if (mcopy != NULL) {
1896                 mcopy->m_len = imin((IP_VHL_HL(ip->ip_vhl) << 2) + 8,
1897                     (int)ip->ip_len);
1898                 m_copydata(m, 0, mcopy->m_len, mtod(mcopy, caddr_t));
1899         }
1900
1901         if (!ipstealth)
1902                 ip->ip_ttl -= IPTTLDEC;
1903
1904         /*
1905          * If forwarding packet using same interface that it came in on,
1906          * perhaps should send a redirect to sender to shortcut a hop.
1907          * Only send redirect if source is sending directly to us,
1908          * and if packet was not source routed (or has any options).
1909          * Also, don't send redirect if forwarding using a default route
1910          * or a route modified by a redirect.
1911          */
1912         if (rt->rt_ifp == m->m_pkthdr.rcvif &&
1913             !(rt->rt_flags & (RTF_DYNAMIC | RTF_MODIFIED)) &&
1914             satosin(rt_key(rt))->sin_addr.s_addr != INADDR_ANY &&
1915             ipsendredirects && !using_srcrt && next_hop != NULL) {
1916                 u_long src = ntohl(ip->ip_src.s_addr);
1917
1918 #define RTA(rt) ((struct in_ifaddr *)(rt->rt_ifa))
1919                 if (RTA(rt) != NULL &&
1920                     (src & RTA(rt)->ia_subnetmask) == RTA(rt)->ia_subnet) {
1921                         if (rt->rt_flags & RTF_GATEWAY)
1922                                 dest = satosin(rt->rt_gateway)->sin_addr.s_addr;
1923                         else
1924                                 dest = pkt_dst.s_addr;
1925                         /*
1926                          * Router requirements says to only send
1927                          * host redirects.
1928                          */
1929                         type = ICMP_REDIRECT;
1930                         code = ICMP_REDIRECT_HOST;
1931 #ifdef DIAGNOSTIC
1932                         if (ipprintfs)
1933                                 printf("redirect (%d) to %x\n", code, dest);
1934 #endif
1935                 }
1936         }
1937
1938         if (next_hop) {
1939                 /* Pass IPFORWARD info if available */
1940                 tag.mh_type = MT_TAG;
1941                 tag.mh_flags = PACKET_TAG_IPFORWARD;
1942                 tag.mh_data = (caddr_t)next_hop;
1943                 tag.mh_next = m;
1944                 m = (struct mbuf *)&tag;
1945         }
1946
1947         error = ip_output(m, NULL, &ipforward_rt, IP_FORWARDING, NULL, NULL);
1948
1949         if (error)
1950                 ipstat.ips_cantforward++;
1951         else {
1952                 ipstat.ips_forward++;
1953                 if (type)
1954                         ipstat.ips_redirectsent++;
1955                 else {
1956                         if (mcopy) {
1957                                 ipflow_create(&ipforward_rt, mcopy);
1958                                 m_freem(mcopy);
1959                         }
1960                         return;
1961                 }
1962         }
1963         if (mcopy == NULL)
1964                 return;
1965         destifp = NULL;
1966
1967         switch (error) {
1968
1969         case 0:                         /* forwarded, but need redirect */
1970                 /* type, code set above */
1971                 break;
1972
1973         case ENETUNREACH:               /* shouldn't happen, checked above */
1974         case EHOSTUNREACH:
1975         case ENETDOWN:
1976         case EHOSTDOWN:
1977         default:
1978                 type = ICMP_UNREACH;
1979                 code = ICMP_UNREACH_HOST;
1980                 break;
1981
1982         case EMSGSIZE:
1983                 type = ICMP_UNREACH;
1984                 code = ICMP_UNREACH_NEEDFRAG;
1985 #ifdef IPSEC
1986                 /*
1987                  * If the packet is routed over IPsec tunnel, tell the
1988                  * originator the tunnel MTU.
1989                  *      tunnel MTU = if MTU - sizeof(IP) - ESP/AH hdrsiz
1990                  * XXX quickhack!!!
1991                  */
1992                 if (ipforward_rt.ro_rt != NULL) {
1993                         struct secpolicy *sp = NULL;
1994                         int ipsecerror;
1995                         int ipsechdr;
1996                         struct route *ro;
1997
1998                         sp = ipsec4_getpolicybyaddr(mcopy,
1999                                                     IPSEC_DIR_OUTBOUND,
2000                                                     IP_FORWARDING,
2001                                                     &ipsecerror);
2002
2003                         if (sp == NULL)
2004                                 destifp = ipforward_rt.ro_rt->rt_ifp;
2005                         else {
2006                                 /* count IPsec header size */
2007                                 ipsechdr = ipsec4_hdrsiz(mcopy,
2008                                                          IPSEC_DIR_OUTBOUND,
2009                                                          NULL);
2010
2011                                 /*
2012                                  * find the correct route for outer IPv4
2013                                  * header, compute tunnel MTU.
2014                                  *
2015                                  * XXX BUG ALERT
2016                                  * The "dummyifp" code relies upon the fact
2017                                  * that icmp_error() touches only ifp->if_mtu.
2018                                  */
2019                                 /*XXX*/
2020                                 destifp = NULL;
2021                                 if (sp->req != NULL && sp->req->sav != NULL &&
2022                                     sp->req->sav->sah != NULL) {
2023                                         ro = &sp->req->sav->sah->sa_route;
2024                                         if (ro->ro_rt != NULL &&
2025                                             ro->ro_rt->rt_ifp != NULL) {
2026                                                 dummyifp.if_mtu =
2027                                                     ro->ro_rt->rt_ifp->if_mtu;
2028                                                 dummyifp.if_mtu -= ipsechdr;
2029                                                 destifp = &dummyifp;
2030                                         }
2031                                 }
2032
2033                                 key_freesp(sp);
2034                         }
2035                 }
2036 #elif FAST_IPSEC
2037                 /*
2038                  * If the packet is routed over IPsec tunnel, tell the
2039                  * originator the tunnel MTU.
2040                  *      tunnel MTU = if MTU - sizeof(IP) - ESP/AH hdrsiz
2041                  * XXX quickhack!!!
2042                  */
2043                 if (ipforward_rt.ro_rt != NULL) {
2044                         struct secpolicy *sp = NULL;
2045                         int ipsecerror;
2046                         int ipsechdr;
2047                         struct route *ro;
2048
2049                         sp = ipsec_getpolicybyaddr(mcopy,
2050                                                    IPSEC_DIR_OUTBOUND,
2051                                                    IP_FORWARDING,
2052                                                    &ipsecerror);
2053
2054                         if (sp == NULL)
2055                                 destifp = ipforward_rt.ro_rt->rt_ifp;
2056                         else {
2057                                 /* count IPsec header size */
2058                                 ipsechdr = ipsec4_hdrsiz(mcopy,
2059                                                          IPSEC_DIR_OUTBOUND,
2060                                                          NULL);
2061
2062                                 /*
2063                                  * find the correct route for outer IPv4
2064                                  * header, compute tunnel MTU.
2065                                  *
2066                                  * XXX BUG ALERT
2067                                  * The "dummyifp" code relies upon the fact
2068                                  * that icmp_error() touches only ifp->if_mtu.
2069                                  */
2070                                 /*XXX*/
2071                                 destifp = NULL;
2072                                 if (sp->req != NULL &&
2073                                     sp->req->sav != NULL &&
2074                                     sp->req->sav->sah != NULL) {
2075                                         ro = &sp->req->sav->sah->sa_route;
2076                                         if (ro->ro_rt != NULL &&
2077                                             ro->ro_rt->rt_ifp != NULL) {
2078                                                 dummyifp.if_mtu =
2079                                                     ro->ro_rt->rt_ifp->if_mtu;
2080                                                 dummyifp.if_mtu -= ipsechdr;
2081                                                 destifp = &dummyifp;
2082                                         }
2083                                 }
2084
2085                                 KEY_FREESP(&sp);
2086                         }
2087                 }
2088 #else /* !IPSEC && !FAST_IPSEC */
2089                 if (ipforward_rt.ro_rt != NULL)
2090                         destifp = ipforward_rt.ro_rt->rt_ifp;
2091 #endif /*IPSEC*/
2092                 ipstat.ips_cantfrag++;
2093                 break;
2094
2095         case ENOBUFS:
2096                 /*
2097                  * A router should not generate ICMP_SOURCEQUENCH as
2098                  * required in RFC1812 Requirements for IP Version 4 Routers.
2099                  * Source quench could be a big problem under DoS attacks,
2100                  * or if the underlying interface is rate-limited.
2101                  * Those who need source quench packets may re-enable them
2102                  * via the net.inet.ip.sendsourcequench sysctl.
2103                  */
2104                 if (!ip_sendsourcequench) {
2105                         m_freem(mcopy);
2106                         return;
2107                 } else {
2108                         type = ICMP_SOURCEQUENCH;
2109                         code = 0;
2110                 }
2111                 break;
2112
2113         case EACCES:                    /* ipfw denied packet */
2114                 m_freem(mcopy);
2115                 return;
2116         }
2117         icmp_error(mcopy, type, code, dest, destifp);
2118 }
2119
2120 void
2121 ip_savecontrol(struct inpcb *inp, struct mbuf **mp, struct ip *ip,
2122                struct mbuf *m)
2123 {
2124         if (inp->inp_socket->so_options & SO_TIMESTAMP) {
2125                 struct timeval tv;
2126
2127                 microtime(&tv);
2128                 *mp = sbcreatecontrol((caddr_t) &tv, sizeof(tv),
2129                     SCM_TIMESTAMP, SOL_SOCKET);
2130                 if (*mp)
2131                         mp = &(*mp)->m_next;
2132         }
2133         if (inp->inp_flags & INP_RECVDSTADDR) {
2134                 *mp = sbcreatecontrol((caddr_t) &ip->ip_dst,
2135                     sizeof(struct in_addr), IP_RECVDSTADDR, IPPROTO_IP);
2136                 if (*mp)
2137                         mp = &(*mp)->m_next;
2138         }
2139 #ifdef notyet
2140         /* XXX
2141          * Moving these out of udp_input() made them even more broken
2142          * than they already were.
2143          */
2144         /* options were tossed already */
2145         if (inp->inp_flags & INP_RECVOPTS) {
2146                 *mp = sbcreatecontrol((caddr_t) opts_deleted_above,
2147                     sizeof(struct in_addr), IP_RECVOPTS, IPPROTO_IP);
2148                 if (*mp)
2149                         mp = &(*mp)->m_next;
2150         }
2151         /* ip_srcroute doesn't do what we want here, need to fix */
2152         if (inp->inp_flags & INP_RECVRETOPTS) {
2153                 *mp = sbcreatecontrol((caddr_t) ip_srcroute(),
2154                     sizeof(struct in_addr), IP_RECVRETOPTS, IPPROTO_IP);
2155                 if (*mp)
2156                         mp = &(*mp)->m_next;
2157         }
2158 #endif
2159         if (inp->inp_flags & INP_RECVIF) {
2160                 struct ifnet *ifp;
2161                 struct sdlbuf {
2162                         struct sockaddr_dl sdl;
2163                         u_char  pad[32];
2164                 } sdlbuf;
2165                 struct sockaddr_dl *sdp;
2166                 struct sockaddr_dl *sdl2 = &sdlbuf.sdl;
2167
2168                 if (((ifp = m->m_pkthdr.rcvif)) &&
2169                     ((ifp->if_index != 0) && (ifp->if_index <= if_index))) {
2170                         sdp = (struct sockaddr_dl *)
2171                             ifnet_addrs[ifp->if_index - 1]->ifa_addr;
2172                         /*
2173                          * Change our mind and don't try copy.
2174                          */
2175                         if ((sdp->sdl_family != AF_LINK) ||
2176                             (sdp->sdl_len > sizeof(sdlbuf))) {
2177                                 goto makedummy;
2178                         }
2179                         bcopy(sdp, sdl2, sdp->sdl_len);
2180                 } else {
2181 makedummy:
2182                         sdl2->sdl_len =
2183                             offsetof(struct sockaddr_dl, sdl_data[0]);
2184                         sdl2->sdl_family = AF_LINK;
2185                         sdl2->sdl_index = 0;
2186                         sdl2->sdl_nlen = sdl2->sdl_alen = sdl2->sdl_slen = 0;
2187                 }
2188                 *mp = sbcreatecontrol((caddr_t) sdl2, sdl2->sdl_len,
2189                         IP_RECVIF, IPPROTO_IP);
2190                 if (*mp)
2191                         mp = &(*mp)->m_next;
2192         }
2193 }
2194
2195 /*
2196  * XXX these routines are called from the upper part of the kernel.
2197  *
2198  * They could also be moved to ip_mroute.c, since all the RSVP
2199  *  handling is done there already.
2200  */
2201 int
2202 ip_rsvp_init(struct socket *so)
2203 {
2204         if (so->so_type != SOCK_RAW ||
2205             so->so_proto->pr_protocol != IPPROTO_RSVP)
2206                 return EOPNOTSUPP;
2207
2208         if (ip_rsvpd != NULL)
2209                 return EADDRINUSE;
2210
2211         ip_rsvpd = so;
2212         /*
2213          * This may seem silly, but we need to be sure we don't over-increment
2214          * the RSVP counter, in case something slips up.
2215          */
2216         if (!ip_rsvp_on) {
2217                 ip_rsvp_on = 1;
2218                 rsvp_on++;
2219         }
2220
2221         return 0;
2222 }
2223
2224 int
2225 ip_rsvp_done(void)
2226 {
2227         ip_rsvpd = NULL;
2228         /*
2229          * This may seem silly, but we need to be sure we don't over-decrement
2230          * the RSVP counter, in case something slips up.
2231          */
2232         if (ip_rsvp_on) {
2233                 ip_rsvp_on = 0;
2234                 rsvp_on--;
2235         }
2236         return 0;
2237 }
2238
2239 void
2240 rsvp_input(struct mbuf *m, int off, int proto)  /* XXX must fixup manually */
2241 {
2242         if (rsvp_input_p) { /* call the real one if loaded */
2243                 rsvp_input_p(m, off, proto);
2244                 return;
2245         }
2246
2247         /* Can still get packets with rsvp_on = 0 if there is a local member
2248          * of the group to which the RSVP packet is addressed.  But in this
2249          * case we want to throw the packet away.
2250          */
2251
2252         if (!rsvp_on) {
2253                 m_freem(m);
2254                 return;
2255         }
2256
2257         if (ip_rsvpd != NULL) {
2258                 rip_input(m, off, proto);
2259                 return;
2260         }
2261         /* Drop the packet */
2262         m_freem(m);
2263 }