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