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