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