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