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