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