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