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