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