Fix various grammatical issues in our messages, documentation etc.
[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 than 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          * We must forward the packet to the correct protocol thread if
860          * we are not already in it.
861          *
862          * NOTE: ip_len is now in host form.  ip_len is not adjusted
863          *       further for protocol processing, instead we pass hlen
864          *       to the protosw and let it deal with it.
865          */
866         ipstat.ips_delivered++;
867
868         if ((m->m_flags & M_HASH) == 0) {
869                 m = ip_rehashm(m, hlen);
870                 if (m == NULL)
871                         return;
872                 ip = mtod(m, struct ip *);
873         }
874         port = netisr_hashport(m->m_pkthdr.hash);
875
876         if (port != &curthread->td_msgport) {
877                 ip_transport_redispatch(port, m, hlen);
878         } else {
879 #ifdef RSS_DEBUG
880                 atomic_add_long(&ip_dispatch_fast, 1);
881 #endif
882                 transport_processing_oncpu(m, hlen, ip);
883         }
884         return;
885
886 bad:
887         m_freem(m);
888 }
889
890 struct mbuf *
891 ip_rehashm(struct mbuf *m, int hlen)
892 {
893         struct ip *ip = mtod(m, struct ip *);
894
895 #ifdef RSS_DEBUG
896         atomic_add_long(&ip_rehash_count, 1);
897 #endif
898         ip->ip_len = htons(ip->ip_len + hlen);
899         ip->ip_off = htons(ip->ip_off);
900
901         ip_hashfn(&m, 0);
902         if (m == NULL)
903                 return NULL;
904
905         /* 'm' might be changed by ip_hashfn(). */
906         ip = mtod(m, struct ip *);
907         ip->ip_len = ntohs(ip->ip_len) - hlen;
908         ip->ip_off = ntohs(ip->ip_off);
909         KASSERT(m->m_flags & M_HASH, ("no hash"));
910
911         return (m);
912 }
913
914 void
915 ip_transport_redispatch(struct lwkt_port *port, struct mbuf *m, int hlen)
916 {
917         struct netmsg_packet *pmsg;
918
919 #ifdef RSS_DEBUG
920         atomic_add_long(&ip_dispatch_slow, 1);
921 #endif
922
923         pmsg = &m->m_hdr.mh_netmsg;
924         netmsg_init(&pmsg->base, NULL, &netisr_apanic_rport,
925                     0, transport_processing_handler);
926         pmsg->nm_packet = m;
927         pmsg->base.lmsg.u.ms_result = hlen;
928         lwkt_sendmsg(port, &pmsg->base.lmsg);
929 }
930
931 /*
932  * Take incoming datagram fragment and try to reassemble it into
933  * whole datagram.  If a chain for reassembly of this datagram already
934  * exists, then it is given as fp; otherwise have to make a chain.
935  */
936 struct mbuf *
937 ip_reass(struct mbuf *m)
938 {
939         struct ipfrag_queue *fragq = &ipfrag_queue_pcpu[mycpuid];
940         struct ip *ip = mtod(m, struct ip *);
941         struct mbuf *p = NULL, *q, *nq;
942         struct mbuf *n;
943         struct ipq *fp = NULL;
944         struct ipqhead *head;
945         int hlen = IP_VHL_HL(ip->ip_vhl) << 2;
946         int i, next;
947         u_short sum;
948
949         /* If maxnipq or maxfragsperpacket are 0, never accept fragments. */
950         if (maxnipq == 0 || maxfragsperpacket == 0) {
951                 ipstat.ips_fragments++;
952                 ipstat.ips_fragdropped++;
953                 m_freem(m);
954                 return NULL;
955         }
956
957         sum = IPREASS_HASH(ip->ip_src.s_addr, ip->ip_id);
958         /*
959          * Look for queue of fragments of this datagram.
960          */
961         head = &fragq->ipq[sum];
962         TAILQ_FOREACH(fp, head, ipq_list) {
963                 if (ip->ip_id == fp->ipq_id &&
964                     ip->ip_src.s_addr == fp->ipq_src.s_addr &&
965                     ip->ip_dst.s_addr == fp->ipq_dst.s_addr &&
966                     ip->ip_p == fp->ipq_p)
967                         goto found;
968         }
969
970         fp = NULL;
971
972         /*
973          * Enforce upper bound on number of fragmented packets
974          * for which we attempt reassembly;
975          * If maxnipq is -1, accept all fragments without limitation.
976          */
977         if (fragq->nipq > maxnipq && maxnipq > 0) {
978                 /*
979                  * drop something from the tail of the current queue
980                  * before proceeding further
981                  */
982                 struct ipq *q = TAILQ_LAST(head, ipqhead);
983                 if (q == NULL) {
984                         /*
985                          * The current queue is empty,
986                          * so drop from one of the others.
987                          */
988                         for (i = 0; i < IPREASS_NHASH; i++) {
989                                 struct ipq *r = TAILQ_LAST(&fragq->ipq[i],
990                                     ipqhead);
991                                 if (r) {
992                                         ipstat.ips_fragtimeout += r->ipq_nfrags;
993                                         ip_freef(fragq, &fragq->ipq[i], r);
994                                         break;
995                                 }
996                         }
997                 } else {
998                         ipstat.ips_fragtimeout += q->ipq_nfrags;
999                         ip_freef(fragq, head, q);
1000                 }
1001         }
1002 found:
1003         /*
1004          * Adjust ip_len to not reflect header,
1005          * convert offset of this to bytes.
1006          */
1007         ip->ip_len -= hlen;
1008         if (ip->ip_off & IP_MF) {
1009                 /*
1010                  * Make sure that fragments have a data length
1011                  * that's a non-zero multiple of 8 bytes.
1012                  */
1013                 if (ip->ip_len == 0 || (ip->ip_len & 0x7) != 0) {
1014                         ipstat.ips_toosmall++; /* XXX */
1015                         m_freem(m);
1016                         goto done;
1017                 }
1018                 m->m_flags |= M_FRAG;
1019         } else {
1020                 m->m_flags &= ~M_FRAG;
1021         }
1022         ip->ip_off <<= 3;
1023
1024         ipstat.ips_fragments++;
1025         m->m_pkthdr.header = ip;
1026
1027         /*
1028          * If the hardware has not done csum over this fragment
1029          * then csum_data is not valid at all.
1030          */
1031         if ((m->m_pkthdr.csum_flags & (CSUM_FRAG_NOT_CHECKED | CSUM_DATA_VALID))
1032             == (CSUM_FRAG_NOT_CHECKED | CSUM_DATA_VALID)) {
1033                 m->m_pkthdr.csum_data = 0;
1034                 m->m_pkthdr.csum_flags &= ~(CSUM_DATA_VALID | CSUM_PSEUDO_HDR);
1035         }
1036
1037         /*
1038          * Presence of header sizes in mbufs
1039          * would confuse code below.
1040          */
1041         m->m_data += hlen;
1042         m->m_len -= hlen;
1043
1044         /*
1045          * If first fragment to arrive, create a reassembly queue.
1046          */
1047         if (fp == NULL) {
1048                 if ((fp = mpipe_alloc_nowait(&ipq_mpipe)) == NULL)
1049                         goto dropfrag;
1050                 TAILQ_INSERT_HEAD(head, fp, ipq_list);
1051                 fragq->nipq++;
1052                 fp->ipq_nfrags = 1;
1053                 fp->ipq_ttl = IPFRAGTTL;
1054                 fp->ipq_p = ip->ip_p;
1055                 fp->ipq_id = ip->ip_id;
1056                 fp->ipq_src = ip->ip_src;
1057                 fp->ipq_dst = ip->ip_dst;
1058                 fp->ipq_frags = m;
1059                 m->m_nextpkt = NULL;
1060                 goto inserted;
1061         }
1062         fp->ipq_nfrags++;
1063
1064 #define GETIP(m)        ((struct ip*)((m)->m_pkthdr.header))
1065
1066         /*
1067          * Find a segment which begins after this one does.
1068          */
1069         for (p = NULL, q = fp->ipq_frags; q; p = q, q = q->m_nextpkt) {
1070                 if (GETIP(q)->ip_off > ip->ip_off)
1071                         break;
1072         }
1073
1074         /*
1075          * If there is a preceding segment, it may provide some of
1076          * our data already.  If so, drop the data from the incoming
1077          * segment.  If it provides all of our data, drop us, otherwise
1078          * stick new segment in the proper place.
1079          *
1080          * If some of the data is dropped from the the preceding
1081          * segment, then it's checksum is invalidated.
1082          */
1083         if (p) {
1084                 i = GETIP(p)->ip_off + GETIP(p)->ip_len - ip->ip_off;
1085                 if (i > 0) {
1086                         if (i >= ip->ip_len)
1087                                 goto dropfrag;
1088                         m_adj(m, i);
1089                         m->m_pkthdr.csum_flags = 0;
1090                         ip->ip_off += i;
1091                         ip->ip_len -= i;
1092                 }
1093                 m->m_nextpkt = p->m_nextpkt;
1094                 p->m_nextpkt = m;
1095         } else {
1096                 m->m_nextpkt = fp->ipq_frags;
1097                 fp->ipq_frags = m;
1098         }
1099
1100         /*
1101          * While we overlap succeeding segments trim them or,
1102          * if they are completely covered, dequeue them.
1103          */
1104         for (; q != NULL && ip->ip_off + ip->ip_len > GETIP(q)->ip_off;
1105              q = nq) {
1106                 i = (ip->ip_off + ip->ip_len) - GETIP(q)->ip_off;
1107                 if (i < GETIP(q)->ip_len) {
1108                         GETIP(q)->ip_len -= i;
1109                         GETIP(q)->ip_off += i;
1110                         m_adj(q, i);
1111                         q->m_pkthdr.csum_flags = 0;
1112                         break;
1113                 }
1114                 nq = q->m_nextpkt;
1115                 m->m_nextpkt = nq;
1116                 ipstat.ips_fragdropped++;
1117                 fp->ipq_nfrags--;
1118                 q->m_nextpkt = NULL;
1119                 m_freem(q);
1120         }
1121
1122 inserted:
1123         /*
1124          * Check for complete reassembly and perform frag per packet
1125          * limiting.
1126          *
1127          * Frag limiting is performed here so that the nth frag has
1128          * a chance to complete the packet before we drop the packet.
1129          * As a result, n+1 frags are actually allowed per packet, but
1130          * only n will ever be stored. (n = maxfragsperpacket.)
1131          *
1132          */
1133         next = 0;
1134         for (p = NULL, q = fp->ipq_frags; q; p = q, q = q->m_nextpkt) {
1135                 if (GETIP(q)->ip_off != next) {
1136                         if (fp->ipq_nfrags > maxfragsperpacket) {
1137                                 ipstat.ips_fragdropped += fp->ipq_nfrags;
1138                                 ip_freef(fragq, head, fp);
1139                         }
1140                         goto done;
1141                 }
1142                 next += GETIP(q)->ip_len;
1143         }
1144         /* Make sure the last packet didn't have the IP_MF flag */
1145         if (p->m_flags & M_FRAG) {
1146                 if (fp->ipq_nfrags > maxfragsperpacket) {
1147                         ipstat.ips_fragdropped += fp->ipq_nfrags;
1148                         ip_freef(fragq, head, fp);
1149                 }
1150                 goto done;
1151         }
1152
1153         /*
1154          * Reassembly is complete.  Make sure the packet is a sane size.
1155          */
1156         q = fp->ipq_frags;
1157         ip = GETIP(q);
1158         if (next + (IP_VHL_HL(ip->ip_vhl) << 2) > IP_MAXPACKET) {
1159                 ipstat.ips_toolong++;
1160                 ipstat.ips_fragdropped += fp->ipq_nfrags;
1161                 ip_freef(fragq, head, fp);
1162                 goto done;
1163         }
1164
1165         /*
1166          * Concatenate fragments.
1167          */
1168         m = q;
1169         n = m->m_next;
1170         m->m_next = NULL;
1171         m_cat(m, n);
1172         nq = q->m_nextpkt;
1173         q->m_nextpkt = NULL;
1174         for (q = nq; q != NULL; q = nq) {
1175                 nq = q->m_nextpkt;
1176                 q->m_nextpkt = NULL;
1177                 m->m_pkthdr.csum_flags &= q->m_pkthdr.csum_flags;
1178                 m->m_pkthdr.csum_data += q->m_pkthdr.csum_data;
1179                 m_cat(m, q);
1180         }
1181
1182         /*
1183          * Clean up the 1's complement checksum.  Carry over 16 bits must
1184          * be added back.  This assumes no more then 65535 packet fragments
1185          * were reassembled.  A second carry can also occur (but not a third).
1186          */
1187         m->m_pkthdr.csum_data = (m->m_pkthdr.csum_data & 0xffff) +
1188                                 (m->m_pkthdr.csum_data >> 16);
1189         if (m->m_pkthdr.csum_data > 0xFFFF)
1190                 m->m_pkthdr.csum_data -= 0xFFFF;
1191
1192         /*
1193          * Create header for new ip packet by
1194          * modifying header of first packet;
1195          * dequeue and discard fragment reassembly header.
1196          * Make header visible.
1197          */
1198         ip->ip_len = next;
1199         ip->ip_src = fp->ipq_src;
1200         ip->ip_dst = fp->ipq_dst;
1201         TAILQ_REMOVE(head, fp, ipq_list);
1202         fragq->nipq--;
1203         mpipe_free(&ipq_mpipe, fp);
1204         m->m_len += (IP_VHL_HL(ip->ip_vhl) << 2);
1205         m->m_data -= (IP_VHL_HL(ip->ip_vhl) << 2);
1206         /* some debugging cruft by sklower, below, will go away soon */
1207         if (m->m_flags & M_PKTHDR) { /* XXX this should be done elsewhere */
1208                 int plen = 0;
1209
1210                 for (n = m; n; n = n->m_next)
1211                         plen += n->m_len;
1212                 m->m_pkthdr.len = plen;
1213         }
1214
1215         /*
1216          * Reassembly complete, return the next protocol.
1217          *
1218          * Be sure to clear M_HASH to force the packet
1219          * to be re-characterized.
1220          *
1221          * Clear M_FRAG, we are no longer a fragment.
1222          */
1223         m->m_flags &= ~(M_HASH | M_FRAG);
1224
1225         ipstat.ips_reassembled++;
1226         return (m);
1227
1228 dropfrag:
1229         ipstat.ips_fragdropped++;
1230         if (fp != NULL)
1231                 fp->ipq_nfrags--;
1232         m_freem(m);
1233 done:
1234         return (NULL);
1235
1236 #undef GETIP
1237 }
1238
1239 /*
1240  * Free a fragment reassembly header and all
1241  * associated datagrams.
1242  */
1243 static void
1244 ip_freef(struct ipfrag_queue *fragq, struct ipqhead *fhp, struct ipq *fp)
1245 {
1246         struct mbuf *q;
1247
1248         /*
1249          * Remove first to protect against blocking
1250          */
1251         TAILQ_REMOVE(fhp, fp, ipq_list);
1252
1253         /*
1254          * Clean out at our leisure
1255          */
1256         while (fp->ipq_frags) {
1257                 q = fp->ipq_frags;
1258                 fp->ipq_frags = q->m_nextpkt;
1259                 q->m_nextpkt = NULL;
1260                 m_freem(q);
1261         }
1262         mpipe_free(&ipq_mpipe, fp);
1263         fragq->nipq--;
1264 }
1265
1266 /*
1267  * If a timer expires on a reassembly queue, discard it.
1268  */
1269 static void
1270 ipfrag_timeo_dispatch(netmsg_t nmsg)
1271 {
1272         struct ipfrag_queue *fragq = &ipfrag_queue_pcpu[mycpuid];
1273         struct ipq *fp, *fp_temp;
1274         struct ipqhead *head;
1275         int i;
1276
1277         crit_enter();
1278         netisr_replymsg(&nmsg->base, 0);  /* reply ASAP */
1279         crit_exit();
1280
1281         if (fragq->nipq == 0)
1282                 goto done;
1283
1284         for (i = 0; i < IPREASS_NHASH; i++) {
1285                 head = &fragq->ipq[i];
1286                 TAILQ_FOREACH_MUTABLE(fp, head, ipq_list, fp_temp) {
1287                         if (--fp->ipq_ttl == 0) {
1288                                 ipstat.ips_fragtimeout += fp->ipq_nfrags;
1289                                 ip_freef(fragq, head, fp);
1290                         }
1291                 }
1292         }
1293         /*
1294          * If we are over the maximum number of fragments
1295          * (due to the limit being lowered), drain off
1296          * enough to get down to the new limit.
1297          */
1298         if (maxnipq >= 0 && fragq->nipq > maxnipq) {
1299                 for (i = 0; i < IPREASS_NHASH; i++) {
1300                         head = &fragq->ipq[i];
1301                         while (fragq->nipq > maxnipq && !TAILQ_EMPTY(head)) {
1302                                 ipstat.ips_fragdropped +=
1303                                     TAILQ_FIRST(head)->ipq_nfrags;
1304                                 ip_freef(fragq, head, TAILQ_FIRST(head));
1305                         }
1306                 }
1307         }
1308 done:
1309         callout_reset(&fragq->timeo_ch, IPFRAG_TIMEO, ipfrag_timeo, NULL);
1310 }
1311
1312 static void
1313 ipfrag_timeo(void *dummy __unused)
1314 {
1315         struct netmsg_base *msg = &ipfrag_queue_pcpu[mycpuid].timeo_netmsg;
1316
1317         crit_enter();
1318         if (msg->lmsg.ms_flags & MSGF_DONE)
1319                 netisr_sendmsg_oncpu(msg);
1320         crit_exit();
1321 }
1322
1323 /*
1324  * Drain off all datagram fragments.
1325  */
1326 static void
1327 ipfrag_drain_oncpu(struct ipfrag_queue *fragq)
1328 {
1329         struct ipqhead *head;
1330         int i;
1331
1332         for (i = 0; i < IPREASS_NHASH; i++) {
1333                 head = &fragq->ipq[i];
1334                 while (!TAILQ_EMPTY(head)) {
1335                         ipstat.ips_fragdropped += TAILQ_FIRST(head)->ipq_nfrags;
1336                         ip_freef(fragq, head, TAILQ_FIRST(head));
1337                 }
1338         }
1339 }
1340
1341 static void
1342 ipfrag_drain_dispatch(netmsg_t nmsg)
1343 {
1344         struct ipfrag_queue *fragq = &ipfrag_queue_pcpu[mycpuid];
1345
1346         crit_enter();
1347         lwkt_replymsg(&nmsg->lmsg, 0);  /* reply ASAP */
1348         crit_exit();
1349
1350         ipfrag_drain_oncpu(fragq);
1351         fragq->draining = 0;
1352 }
1353
1354 static void
1355 ipfrag_drain_ipi(void *arg __unused)
1356 {
1357         int cpu = mycpuid;
1358         struct lwkt_msg *msg = &ipfrag_queue_pcpu[cpu].drain_netmsg.lmsg;
1359
1360         crit_enter();
1361         if (msg->ms_flags & MSGF_DONE)
1362                 lwkt_sendmsg_oncpu(netisr_cpuport(cpu), msg);
1363         crit_exit();
1364 }
1365
1366 static void
1367 ipfrag_drain(void)
1368 {
1369         cpumask_t mask;
1370         int cpu;
1371
1372         CPUMASK_ASSBMASK(mask, netisr_ncpus);
1373         CPUMASK_ANDMASK(mask, smp_active_mask);
1374
1375         if (IN_NETISR_NCPUS(mycpuid)) {
1376                 ipfrag_drain_oncpu(&ipfrag_queue_pcpu[mycpuid]);
1377                 CPUMASK_NANDBIT(mask, mycpuid);
1378         }
1379
1380         for (cpu = 0; cpu < netisr_ncpus; ++cpu) {
1381                 struct ipfrag_queue *fragq = &ipfrag_queue_pcpu[cpu];
1382
1383                 if (!CPUMASK_TESTBIT(mask, cpu))
1384                         continue;
1385
1386                 if (fragq->nipq == 0 || fragq->draining) {
1387                         /* No fragments or is draining; skip this cpu. */
1388                         CPUMASK_NANDBIT(mask, cpu);
1389                         continue;
1390                 }
1391                 fragq->draining = 1;
1392         }
1393
1394         if (CPUMASK_TESTNZERO(mask))
1395                 lwkt_send_ipiq_mask(mask, ipfrag_drain_ipi, NULL);
1396 }
1397
1398 void
1399 ip_drain(void)
1400 {
1401         ipfrag_drain();
1402         in_rtqdrain();
1403 }
1404
1405 /*
1406  * Do option processing on a datagram,
1407  * possibly discarding it if bad options are encountered,
1408  * or forwarding it if source-routed.
1409  * The pass argument is used when operating in the IPSTEALTH
1410  * mode to tell what options to process:
1411  * [LS]SRR (pass 0) or the others (pass 1).
1412  * The reason for as many as two passes is that when doing IPSTEALTH,
1413  * non-routing options should be processed only if the packet is for us.
1414  * Returns 1 if packet has been forwarded/freed,
1415  * 0 if the packet should be processed further.
1416  */
1417 static int
1418 ip_dooptions(struct mbuf *m, int pass, struct sockaddr_in *next_hop)
1419 {
1420         struct sockaddr_in ipaddr = { sizeof ipaddr, AF_INET };
1421         struct ip *ip = mtod(m, struct ip *);
1422         u_char *cp;
1423         struct in_ifaddr *ia;
1424         int opt, optlen, cnt, off, code, type = ICMP_PARAMPROB;
1425         boolean_t forward = FALSE;
1426         struct in_addr *sin, dst;
1427         n_time ntime;
1428
1429         dst = ip->ip_dst;
1430         cp = (u_char *)(ip + 1);
1431         cnt = (IP_VHL_HL(ip->ip_vhl) << 2) - sizeof(struct ip);
1432         for (; cnt > 0; cnt -= optlen, cp += optlen) {
1433                 opt = cp[IPOPT_OPTVAL];
1434                 if (opt == IPOPT_EOL)
1435                         break;
1436                 if (opt == IPOPT_NOP)
1437                         optlen = 1;
1438                 else {
1439                         if (cnt < IPOPT_OLEN + sizeof(*cp)) {
1440                                 code = &cp[IPOPT_OLEN] - (u_char *)ip;
1441                                 goto bad;
1442                         }
1443                         optlen = cp[IPOPT_OLEN];
1444                         if (optlen < IPOPT_OLEN + sizeof(*cp) || optlen > cnt) {
1445                                 code = &cp[IPOPT_OLEN] - (u_char *)ip;
1446                                 goto bad;
1447                         }
1448                 }
1449                 switch (opt) {
1450
1451                 default:
1452                         break;
1453
1454                 /*
1455                  * Source routing with record.
1456                  * Find interface with current destination address.
1457                  * If none on this machine then drop if strictly routed,
1458                  * or do nothing if loosely routed.
1459                  * Record interface address and bring up next address
1460                  * component.  If strictly routed make sure next
1461                  * address is on directly accessible net.
1462                  */
1463                 case IPOPT_LSRR:
1464                 case IPOPT_SSRR:
1465                         if (ipstealth && pass > 0)
1466                                 break;
1467                         if (optlen < IPOPT_OFFSET + sizeof(*cp)) {
1468                                 code = &cp[IPOPT_OLEN] - (u_char *)ip;
1469                                 goto bad;
1470                         }
1471                         if ((off = cp[IPOPT_OFFSET]) < IPOPT_MINOFF) {
1472                                 code = &cp[IPOPT_OFFSET] - (u_char *)ip;
1473                                 goto bad;
1474                         }
1475                         ipaddr.sin_addr = ip->ip_dst;
1476                         ia = (struct in_ifaddr *)
1477                                 ifa_ifwithaddr((struct sockaddr *)&ipaddr);
1478                         if (ia == NULL) {
1479                                 if (opt == IPOPT_SSRR) {
1480                                         type = ICMP_UNREACH;
1481                                         code = ICMP_UNREACH_SRCFAIL;
1482                                         goto bad;
1483                                 }
1484                                 if (!ip_dosourceroute)
1485                                         goto nosourcerouting;
1486                                 /*
1487                                  * Loose routing, and not at next destination
1488                                  * yet; nothing to do except forward.
1489                                  */
1490                                 break;
1491                         }
1492                         off--;                  /* 0 origin */
1493                         if (off > optlen - (int)sizeof(struct in_addr)) {
1494                                 /*
1495                                  * End of source route.  Should be for us.
1496                                  */
1497                                 if (!ip_acceptsourceroute)
1498                                         goto nosourcerouting;
1499                                 save_rte(m, cp, ip->ip_src);
1500                                 break;
1501                         }
1502                         if (ipstealth)
1503                                 goto dropit;
1504                         if (!ip_dosourceroute) {
1505                                 if (ipforwarding) {
1506                                         char sbuf[INET_ADDRSTRLEN];
1507                                         char dbuf[INET_ADDRSTRLEN];
1508
1509                                         /*
1510                                          * Acting as a router, so generate ICMP
1511                                          */
1512 nosourcerouting:
1513                                         log(LOG_WARNING,
1514                                             "attempted source route from %s to %s\n",
1515                                             kinet_ntoa(ip->ip_src, sbuf),
1516                                             kinet_ntoa(ip->ip_dst, dbuf));
1517                                         type = ICMP_UNREACH;
1518                                         code = ICMP_UNREACH_SRCFAIL;
1519                                         goto bad;
1520                                 } else {
1521                                         /*
1522                                          * Not acting as a router,
1523                                          * so silently drop.
1524                                          */
1525 dropit:
1526                                         ipstat.ips_cantforward++;
1527                                         m_freem(m);
1528                                         return (1);
1529                                 }
1530                         }
1531
1532                         /*
1533                          * locate outgoing interface
1534                          */
1535                         memcpy(&ipaddr.sin_addr, cp + off,
1536                             sizeof ipaddr.sin_addr);
1537
1538                         if (opt == IPOPT_SSRR) {
1539 #define INA     struct in_ifaddr *
1540 #define SA      struct sockaddr *
1541                                 if ((ia = (INA)ifa_ifwithdstaddr((SA)&ipaddr))
1542                                                                         == NULL)
1543                                         ia = (INA)ifa_ifwithnet((SA)&ipaddr);
1544                         } else {
1545                                 ia = ip_rtaddr(ipaddr.sin_addr, NULL);
1546                         }
1547                         if (ia == NULL) {
1548                                 type = ICMP_UNREACH;
1549                                 code = ICMP_UNREACH_SRCFAIL;
1550                                 goto bad;
1551                         }
1552                         ip->ip_dst = ipaddr.sin_addr;
1553                         memcpy(cp + off, &IA_SIN(ia)->sin_addr,
1554                             sizeof(struct in_addr));
1555                         cp[IPOPT_OFFSET] += sizeof(struct in_addr);
1556                         /*
1557                          * Let ip_intr's mcast routing check handle mcast pkts
1558                          */
1559                         forward = !IN_MULTICAST(ntohl(ip->ip_dst.s_addr));
1560                         break;
1561
1562                 case IPOPT_RR:
1563                         if (ipstealth && pass == 0)
1564                                 break;
1565                         if (optlen < IPOPT_OFFSET + sizeof(*cp)) {
1566                                 code = &cp[IPOPT_OFFSET] - (u_char *)ip;
1567                                 goto bad;
1568                         }
1569                         if ((off = cp[IPOPT_OFFSET]) < IPOPT_MINOFF) {
1570                                 code = &cp[IPOPT_OFFSET] - (u_char *)ip;
1571                                 goto bad;
1572                         }
1573                         /*
1574                          * If no space remains, ignore.
1575                          */
1576                         off--;                  /* 0 origin */
1577                         if (off > optlen - (int)sizeof(struct in_addr))
1578                                 break;
1579                         memcpy(&ipaddr.sin_addr, &ip->ip_dst,
1580                             sizeof ipaddr.sin_addr);
1581                         /*
1582                          * locate outgoing interface; if we're the destination,
1583                          * use the incoming interface (should be same).
1584                          */
1585                         if ((ia = (INA)ifa_ifwithaddr((SA)&ipaddr)) == NULL &&
1586                             (ia = ip_rtaddr(ipaddr.sin_addr, NULL)) == NULL) {
1587                                 type = ICMP_UNREACH;
1588                                 code = ICMP_UNREACH_HOST;
1589                                 goto bad;
1590                         }
1591                         memcpy(cp + off, &IA_SIN(ia)->sin_addr,
1592                             sizeof(struct in_addr));
1593                         cp[IPOPT_OFFSET] += sizeof(struct in_addr);
1594                         break;
1595
1596                 case IPOPT_TS:
1597                         if (ipstealth && pass == 0)
1598                                 break;
1599                         code = cp - (u_char *)ip;
1600                         if (optlen < 4 || optlen > 40) {
1601                                 code = &cp[IPOPT_OLEN] - (u_char *)ip;
1602                                 goto bad;
1603                         }
1604                         if ((off = cp[IPOPT_OFFSET]) < 5) {
1605                                 code = &cp[IPOPT_OLEN] - (u_char *)ip;
1606                                 goto bad;
1607                         }
1608                         if (off > optlen - (int)sizeof(int32_t)) {
1609                                 cp[IPOPT_OFFSET + 1] += (1 << 4);
1610                                 if ((cp[IPOPT_OFFSET + 1] & 0xf0) == 0) {
1611                                         code = &cp[IPOPT_OFFSET] - (u_char *)ip;
1612                                         goto bad;
1613                                 }
1614                                 break;
1615                         }
1616                         off--;                          /* 0 origin */
1617                         sin = (struct in_addr *)(cp + off);
1618                         switch (cp[IPOPT_OFFSET + 1] & 0x0f) {
1619
1620                         case IPOPT_TS_TSONLY:
1621                                 break;
1622
1623                         case IPOPT_TS_TSANDADDR:
1624                                 if (off + sizeof(n_time) +
1625                                     sizeof(struct in_addr) > optlen) {
1626                                         code = &cp[IPOPT_OFFSET] - (u_char *)ip;
1627                                         goto bad;
1628                                 }
1629                                 ipaddr.sin_addr = dst;
1630                                 ia = (INA)ifaof_ifpforaddr((SA)&ipaddr,
1631                                                             m->m_pkthdr.rcvif);
1632                                 if (ia == NULL)
1633                                         continue;
1634                                 memcpy(sin, &IA_SIN(ia)->sin_addr,
1635                                     sizeof(struct in_addr));
1636                                 cp[IPOPT_OFFSET] += sizeof(struct in_addr);
1637                                 off += sizeof(struct in_addr);
1638                                 break;
1639
1640                         case IPOPT_TS_PRESPEC:
1641                                 if (off + sizeof(n_time) +
1642                                     sizeof(struct in_addr) > optlen) {
1643                                         code = &cp[IPOPT_OFFSET] - (u_char *)ip;
1644                                         goto bad;
1645                                 }
1646                                 memcpy(&ipaddr.sin_addr, sin,
1647                                     sizeof(struct in_addr));
1648                                 if (ifa_ifwithaddr((SA)&ipaddr) == NULL)
1649                                         continue;
1650                                 cp[IPOPT_OFFSET] += sizeof(struct in_addr);
1651                                 off += sizeof(struct in_addr);
1652                                 break;
1653
1654                         default:
1655                                 code = &cp[IPOPT_OFFSET + 1] - (u_char *)ip;
1656                                 goto bad;
1657                         }
1658                         ntime = iptime();
1659                         memcpy(cp + off, &ntime, sizeof(n_time));
1660                         cp[IPOPT_OFFSET] += sizeof(n_time);
1661                 }
1662         }
1663         if (forward && ipforwarding) {
1664                 ip_forward(m, TRUE, next_hop);
1665                 return (1);
1666         }
1667         return (0);
1668 bad:
1669         icmp_error(m, type, code, 0, 0);
1670         ipstat.ips_badoptions++;
1671         return (1);
1672 }
1673
1674 /*
1675  * Given address of next destination (final or next hop),
1676  * return internet address info of interface to be used to get there.
1677  */
1678 struct in_ifaddr *
1679 ip_rtaddr(struct in_addr dst, struct route *ro0)
1680 {
1681         struct route sro, *ro;
1682         struct sockaddr_in *sin;
1683         struct in_ifaddr *ia;
1684
1685         if (ro0 != NULL) {
1686                 ro = ro0;
1687         } else {
1688                 bzero(&sro, sizeof(sro));
1689                 ro = &sro;
1690         }
1691
1692         sin = (struct sockaddr_in *)&ro->ro_dst;
1693
1694         if (ro->ro_rt == NULL || dst.s_addr != sin->sin_addr.s_addr) {
1695                 if (ro->ro_rt != NULL) {
1696                         RTFREE(ro->ro_rt);
1697                         ro->ro_rt = NULL;
1698                 }
1699                 sin->sin_family = AF_INET;
1700                 sin->sin_len = sizeof *sin;
1701                 sin->sin_addr = dst;
1702                 rtalloc_ign(ro, RTF_PRCLONING);
1703         }
1704
1705         if (ro->ro_rt == NULL)
1706                 return (NULL);
1707
1708         ia = ifatoia(ro->ro_rt->rt_ifa);
1709
1710         if (ro == &sro)
1711                 RTFREE(ro->ro_rt);
1712         return ia;
1713 }
1714
1715 /*
1716  * Save incoming source route for use in replies,
1717  * to be picked up later by ip_srcroute if the receiver is interested.
1718  */
1719 static void
1720 save_rte(struct mbuf *m, u_char *option, struct in_addr dst)
1721 {
1722         struct m_tag *mtag;
1723         struct ip_srcrt_opt *opt;
1724         unsigned olen;
1725
1726         mtag = m_tag_get(PACKET_TAG_IPSRCRT, sizeof(*opt), M_NOWAIT);
1727         if (mtag == NULL)
1728                 return;
1729         opt = m_tag_data(mtag);
1730
1731         olen = option[IPOPT_OLEN];
1732 #ifdef DIAGNOSTIC
1733         if (ipprintfs)
1734                 kprintf("save_rte: olen %d\n", olen);
1735 #endif
1736         if (olen > sizeof(opt->ip_srcrt) - (1 + sizeof(dst))) {
1737                 m_tag_free(mtag);
1738                 return;
1739         }
1740         bcopy(option, opt->ip_srcrt.srcopt, olen);
1741         opt->ip_nhops = (olen - IPOPT_OFFSET - 1) / sizeof(struct in_addr);
1742         opt->ip_srcrt.dst = dst;
1743         m_tag_prepend(m, mtag);
1744 }
1745
1746 /*
1747  * Retrieve incoming source route for use in replies,
1748  * in the same form used by setsockopt.
1749  * The first hop is placed before the options, will be removed later.
1750  */
1751 struct mbuf *
1752 ip_srcroute(struct mbuf *m0)
1753 {
1754         struct in_addr *p, *q;
1755         struct mbuf *m;
1756         struct m_tag *mtag;
1757         struct ip_srcrt_opt *opt;
1758
1759         if (m0 == NULL)
1760                 return NULL;
1761
1762         mtag = m_tag_find(m0, PACKET_TAG_IPSRCRT, NULL);
1763         if (mtag == NULL)
1764                 return NULL;
1765         opt = m_tag_data(mtag);
1766
1767         if (opt->ip_nhops == 0)
1768                 return (NULL);
1769         m = m_get(M_NOWAIT, MT_HEADER);
1770         if (m == NULL)
1771                 return (NULL);
1772
1773 #define OPTSIZ  (sizeof(opt->ip_srcrt.nop) + sizeof(opt->ip_srcrt.srcopt))
1774
1775         /* length is (nhops+1)*sizeof(addr) + sizeof(nop + srcrt header) */
1776         m->m_len = opt->ip_nhops * sizeof(struct in_addr) +
1777                    sizeof(struct in_addr) + OPTSIZ;
1778 #ifdef DIAGNOSTIC
1779         if (ipprintfs) {
1780                 kprintf("ip_srcroute: nhops %d mlen %d",
1781                         opt->ip_nhops, m->m_len);
1782         }
1783 #endif
1784
1785         /*
1786          * First save first hop for return route
1787          */
1788         p = &opt->ip_srcrt.route[opt->ip_nhops - 1];
1789         *(mtod(m, struct in_addr *)) = *p--;
1790 #ifdef DIAGNOSTIC
1791         if (ipprintfs)
1792                 kprintf(" hops %x", ntohl(mtod(m, struct in_addr *)->s_addr));
1793 #endif
1794
1795         /*
1796          * Copy option fields and padding (nop) to mbuf.
1797          */
1798         opt->ip_srcrt.nop = IPOPT_NOP;
1799         opt->ip_srcrt.srcopt[IPOPT_OFFSET] = IPOPT_MINOFF;
1800         memcpy(mtod(m, caddr_t) + sizeof(struct in_addr), &opt->ip_srcrt.nop,
1801             OPTSIZ);
1802         q = (struct in_addr *)(mtod(m, caddr_t) +
1803             sizeof(struct in_addr) + OPTSIZ);
1804 #undef OPTSIZ
1805         /*
1806          * Record return path as an IP source route,
1807          * reversing the path (pointers are now aligned).
1808          */
1809         while (p >= opt->ip_srcrt.route) {
1810 #ifdef DIAGNOSTIC
1811                 if (ipprintfs)
1812                         kprintf(" %x", ntohl(q->s_addr));
1813 #endif
1814                 *q++ = *p--;
1815         }
1816         /*
1817          * Last hop goes to final destination.
1818          */
1819         *q = opt->ip_srcrt.dst;
1820         m_tag_delete(m0, mtag);
1821 #ifdef DIAGNOSTIC
1822         if (ipprintfs)
1823                 kprintf(" %x\n", ntohl(q->s_addr));
1824 #endif
1825         return (m);
1826 }
1827
1828 /*
1829  * Strip out IP options.
1830  */
1831 void
1832 ip_stripoptions(struct mbuf *m)
1833 {
1834         int datalen;
1835         struct ip *ip = mtod(m, struct ip *);
1836         caddr_t opts;
1837         int optlen;
1838
1839         optlen = (IP_VHL_HL(ip->ip_vhl) << 2) - sizeof(struct ip);
1840         opts = (caddr_t)(ip + 1);
1841         datalen = m->m_len - (sizeof(struct ip) + optlen);
1842         bcopy(opts + optlen, opts, datalen);
1843         m->m_len -= optlen;
1844         if (m->m_flags & M_PKTHDR)
1845                 m->m_pkthdr.len -= optlen;
1846         ip->ip_vhl = IP_MAKE_VHL(IPVERSION, sizeof(struct ip) >> 2);
1847 }
1848
1849 u_char inetctlerrmap[PRC_NCMDS] = {
1850         0,              0,              0,              0,
1851         0,              EMSGSIZE,       EHOSTDOWN,      EHOSTUNREACH,
1852         EHOSTUNREACH,   EHOSTUNREACH,   ECONNREFUSED,   ECONNREFUSED,
1853         EMSGSIZE,       EHOSTUNREACH,   0,              0,
1854         0,              0,              0,              0,
1855         ENOPROTOOPT,    ECONNREFUSED
1856 };
1857
1858 /*
1859  * Forward a packet.  If some error occurs return the sender
1860  * an icmp packet.  Note we can't always generate a meaningful
1861  * icmp message because icmp doesn't have a large enough repertoire
1862  * of codes and types.
1863  *
1864  * If not forwarding, just drop the packet.  This could be confusing
1865  * if ipforwarding was zero but some routing protocol was advancing
1866  * us as a gateway to somewhere.  However, we must let the routing
1867  * protocol deal with that.
1868  *
1869  * The using_srcrt parameter indicates whether the packet is being forwarded
1870  * via a source route.
1871  */
1872 void
1873 ip_forward(struct mbuf *m, boolean_t using_srcrt, struct sockaddr_in *next_hop)
1874 {
1875         struct ip *ip = mtod(m, struct ip *);
1876         struct rtentry *rt;
1877         struct route fwd_ro;
1878         int error, type = 0, code = 0, destmtu = 0;
1879         struct mbuf *mcopy, *mtemp = NULL;
1880         n_long dest;
1881         struct in_addr pkt_dst;
1882
1883         dest = INADDR_ANY;
1884         /*
1885          * Cache the destination address of the packet; this may be
1886          * changed by use of 'ipfw fwd'.
1887          */
1888         pkt_dst = (next_hop != NULL) ? next_hop->sin_addr : ip->ip_dst;
1889
1890 #ifdef DIAGNOSTIC
1891         if (ipprintfs)
1892                 kprintf("forward: src %x dst %x ttl %x\n",
1893                        ip->ip_src.s_addr, pkt_dst.s_addr, ip->ip_ttl);
1894 #endif
1895
1896         if (m->m_flags & (M_BCAST | M_MCAST) || !in_canforward(pkt_dst)) {
1897                 ipstat.ips_cantforward++;
1898                 m_freem(m);
1899                 return;
1900         }
1901         if (!ipstealth && ip->ip_ttl <= IPTTLDEC) {
1902                 icmp_error(m, ICMP_TIMXCEED, ICMP_TIMXCEED_INTRANS, dest, 0);
1903                 return;
1904         }
1905
1906         bzero(&fwd_ro, sizeof(fwd_ro));
1907         ip_rtaddr(pkt_dst, &fwd_ro);
1908         if (fwd_ro.ro_rt == NULL) {
1909                 icmp_error(m, ICMP_UNREACH, ICMP_UNREACH_HOST, dest, 0);
1910                 return;
1911         }
1912         rt = fwd_ro.ro_rt;
1913
1914         if (curthread->td_type == TD_TYPE_NETISR) {
1915                 /*
1916                  * Save the IP header and at most 8 bytes of the payload,
1917                  * in case we need to generate an ICMP message to the src.
1918                  */
1919                 mtemp = ipforward_mtemp[mycpuid];
1920                 KASSERT((mtemp->m_flags & M_EXT) == 0 &&
1921                     mtemp->m_data == mtemp->m_pktdat &&
1922                     m_tag_first(mtemp) == NULL,
1923                     ("ip_forward invalid mtemp1"));
1924
1925                 if (!m_dup_pkthdr(mtemp, m, M_NOWAIT)) {
1926                         /*
1927                          * It's probably ok if the pkthdr dup fails (because
1928                          * the deep copy of the tag chain failed), but for now
1929                          * be conservative and just discard the copy since
1930                          * code below may some day want the tags.
1931                          */
1932                         mtemp = NULL;
1933                 } else {
1934                         mtemp->m_type = m->m_type;
1935                         mtemp->m_len = imin((IP_VHL_HL(ip->ip_vhl) << 2) + 8,
1936                             (int)ip->ip_len);
1937                         mtemp->m_pkthdr.len = mtemp->m_len;
1938                         m_copydata(m, 0, mtemp->m_len, mtod(mtemp, caddr_t));
1939                 }
1940         }
1941
1942         if (!ipstealth)
1943                 ip->ip_ttl -= IPTTLDEC;
1944
1945         /*
1946          * If forwarding packet using same interface that it came in on,
1947          * perhaps should send a redirect to sender to shortcut a hop.
1948          * Only send redirect if source is sending directly to us,
1949          * and if packet was not source routed (or has any options).
1950          * Also, don't send redirect if forwarding using a default route
1951          * or a route modified by a redirect.
1952          */
1953         if (rt->rt_ifp == m->m_pkthdr.rcvif &&
1954             !(rt->rt_flags & (RTF_DYNAMIC | RTF_MODIFIED)) &&
1955             satosin(rt_key(rt))->sin_addr.s_addr != INADDR_ANY &&
1956             ipsendredirects && !using_srcrt && next_hop == NULL) {
1957                 u_long src = ntohl(ip->ip_src.s_addr);
1958                 struct in_ifaddr *rt_ifa = (struct in_ifaddr *)rt->rt_ifa;
1959
1960                 if (rt_ifa != NULL &&
1961                     (src & rt_ifa->ia_subnetmask) == rt_ifa->ia_subnet) {
1962                         if (rt->rt_flags & RTF_GATEWAY)
1963                                 dest = satosin(rt->rt_gateway)->sin_addr.s_addr;
1964                         else
1965                                 dest = pkt_dst.s_addr;
1966                         /*
1967                          * Router requirements says to only send
1968                          * host redirects.
1969                          */
1970                         type = ICMP_REDIRECT;
1971                         code = ICMP_REDIRECT_HOST;
1972 #ifdef DIAGNOSTIC
1973                         if (ipprintfs)
1974                                 kprintf("redirect (%d) to %x\n", code, dest);
1975 #endif
1976                 }
1977         }
1978
1979         error = ip_output(m, NULL, &fwd_ro, IP_FORWARDING, NULL, NULL);
1980         if (error == 0) {
1981                 ipstat.ips_forward++;
1982                 if (type == 0) {
1983                         if (mtemp)
1984                                 ipflow_create(&fwd_ro, mtemp);
1985                         goto done;
1986                 }
1987                 ipstat.ips_redirectsent++;
1988         } else {
1989                 ipstat.ips_cantforward++;
1990         }
1991
1992         if (mtemp == NULL)
1993                 goto done;
1994
1995         /*
1996          * Errors that do not require generating ICMP message
1997          */
1998         switch (error) {
1999         case ENOBUFS:
2000                 /*
2001                  * A router should not generate ICMP_SOURCEQUENCH as
2002                  * required in RFC1812 Requirements for IP Version 4 Routers.
2003                  * Source quench could be a big problem under DoS attacks,
2004                  * or if the underlying interface is rate-limited.
2005                  * Those who need source quench packets may re-enable them
2006                  * via the net.inet.ip.sendsourcequench sysctl.
2007                  */
2008                 if (!ip_sendsourcequench)
2009                         goto done;
2010                 break;
2011
2012         case EACCES:                    /* ipfw denied packet */
2013                 goto done;
2014         }
2015
2016         KASSERT((mtemp->m_flags & M_EXT) == 0 &&
2017             mtemp->m_data == mtemp->m_pktdat,
2018             ("ip_forward invalid mtemp2"));
2019         mcopy = m_copym(mtemp, 0, mtemp->m_len, M_NOWAIT);
2020         if (mcopy == NULL)
2021                 goto done;
2022
2023         /*
2024          * Send ICMP message.
2025          */
2026         switch (error) {
2027         case 0:                         /* forwarded, but need redirect */
2028                 /* type, code set above */
2029                 break;
2030
2031         case ENETUNREACH:               /* shouldn't happen, checked above */
2032         case EHOSTUNREACH:
2033         case ENETDOWN:
2034         case EHOSTDOWN:
2035         default:
2036                 type = ICMP_UNREACH;
2037                 code = ICMP_UNREACH_HOST;
2038                 break;
2039
2040         case EMSGSIZE:
2041                 type = ICMP_UNREACH;
2042                 code = ICMP_UNREACH_NEEDFRAG;
2043                 if (fwd_ro.ro_rt != NULL)
2044                         destmtu = fwd_ro.ro_rt->rt_ifp->if_mtu;
2045                 ipstat.ips_cantfrag++;
2046                 break;
2047
2048         case ENOBUFS:
2049                 type = ICMP_SOURCEQUENCH;
2050                 code = 0;
2051                 break;
2052
2053         case EACCES:                    /* ipfw denied packet */
2054                 panic("ip_forward EACCES should not reach");
2055         }
2056         icmp_error(mcopy, type, code, dest, destmtu);
2057 done:
2058         if (mtemp != NULL)
2059                 m_tag_delete_chain(mtemp);
2060         if (fwd_ro.ro_rt != NULL)
2061                 RTFREE(fwd_ro.ro_rt);
2062 }
2063
2064 void
2065 ip_savecontrol(struct inpcb *inp, struct mbuf **mp, struct ip *ip,
2066                struct mbuf *m)
2067 {
2068         if (inp->inp_socket->so_options & SO_TIMESTAMP) {
2069                 struct timeval tv;
2070
2071                 microtime(&tv);
2072                 *mp = sbcreatecontrol((caddr_t) &tv, sizeof(tv),
2073                     SCM_TIMESTAMP, SOL_SOCKET);
2074                 if (*mp)
2075                         mp = &(*mp)->m_next;
2076         }
2077         if (inp->inp_flags & INP_RECVDSTADDR) {
2078                 *mp = sbcreatecontrol((caddr_t) &ip->ip_dst,
2079                     sizeof(struct in_addr), IP_RECVDSTADDR, IPPROTO_IP);
2080                 if (*mp)
2081                         mp = &(*mp)->m_next;
2082         }
2083         if (inp->inp_flags & INP_RECVTTL) {
2084                 *mp = sbcreatecontrol((caddr_t) &ip->ip_ttl,
2085                     sizeof(u_char), IP_RECVTTL, IPPROTO_IP);
2086                 if (*mp)
2087                         mp = &(*mp)->m_next;
2088         }
2089 #ifdef notyet
2090         /* XXX
2091          * Moving these out of udp_input() made them even more broken
2092          * than they already were.
2093          */
2094         /* options were tossed already */
2095         if (inp->inp_flags & INP_RECVOPTS) {
2096                 *mp = sbcreatecontrol((caddr_t) opts_deleted_above,
2097                     sizeof(struct in_addr), IP_RECVOPTS, IPPROTO_IP);
2098                 if (*mp)
2099                         mp = &(*mp)->m_next;
2100         }
2101         /* ip_srcroute doesn't do what we want here, need to fix */
2102         if (inp->inp_flags & INP_RECVRETOPTS) {
2103                 *mp = sbcreatecontrol((caddr_t) ip_srcroute(m),
2104                     sizeof(struct in_addr), IP_RECVRETOPTS, IPPROTO_IP);
2105                 if (*mp)
2106                         mp = &(*mp)->m_next;
2107         }
2108 #endif
2109         if (inp->inp_flags & INP_RECVIF) {
2110                 struct ifnet *ifp;
2111                 struct sdlbuf {
2112                         struct sockaddr_dl sdl;
2113                         u_char  pad[32];
2114                 } sdlbuf;
2115                 struct sockaddr_dl *sdp;
2116                 struct sockaddr_dl *sdl2 = &sdlbuf.sdl;
2117
2118                 if (((ifp = m->m_pkthdr.rcvif)) &&
2119                     ((ifp->if_index != 0) && (ifp->if_index <= if_index))) {
2120                         sdp = IF_LLSOCKADDR(ifp);
2121                         /*
2122                          * Change our mind and don't try copy.
2123                          */
2124                         if ((sdp->sdl_family != AF_LINK) ||
2125                             (sdp->sdl_len > sizeof(sdlbuf))) {
2126                                 goto makedummy;
2127                         }
2128                         bcopy(sdp, sdl2, sdp->sdl_len);
2129                 } else {
2130 makedummy:
2131                         sdl2->sdl_len =
2132                             offsetof(struct sockaddr_dl, sdl_data[0]);
2133                         sdl2->sdl_family = AF_LINK;
2134                         sdl2->sdl_index = 0;
2135                         sdl2->sdl_nlen = sdl2->sdl_alen = sdl2->sdl_slen = 0;
2136                 }
2137                 *mp = sbcreatecontrol((caddr_t) sdl2, sdl2->sdl_len,
2138                         IP_RECVIF, IPPROTO_IP);
2139                 if (*mp)
2140                         mp = &(*mp)->m_next;
2141         }
2142 }
2143
2144 /*
2145  * XXX these routines are called from the upper part of the kernel.
2146  *
2147  * They could also be moved to ip_mroute.c, since all the RSVP
2148  *  handling is done there already.
2149  */
2150 int
2151 ip_rsvp_init(struct socket *so)
2152 {
2153         if (so->so_type != SOCK_RAW ||
2154             so->so_proto->pr_protocol != IPPROTO_RSVP)
2155                 return EOPNOTSUPP;
2156
2157         if (ip_rsvpd != NULL)
2158                 return EADDRINUSE;
2159
2160         ip_rsvpd = so;
2161         /*
2162          * This may seem silly, but we need to be sure we don't over-increment
2163          * the RSVP counter, in case something slips up.
2164          */
2165         if (!ip_rsvp_on) {
2166                 ip_rsvp_on = 1;
2167                 rsvp_on++;
2168         }
2169
2170         return 0;
2171 }
2172
2173 int
2174 ip_rsvp_done(void)
2175 {
2176         ip_rsvpd = NULL;
2177         /*
2178          * This may seem silly, but we need to be sure we don't over-decrement
2179          * the RSVP counter, in case something slips up.
2180          */
2181         if (ip_rsvp_on) {
2182                 ip_rsvp_on = 0;
2183                 rsvp_on--;
2184         }
2185         return 0;
2186 }
2187
2188 int
2189 rsvp_input(struct mbuf **mp, int *offp, int proto)
2190 {
2191         struct mbuf *m = *mp;
2192
2193         *mp = NULL;
2194
2195         if (rsvp_input_p) { /* call the real one if loaded */
2196                 *mp = m;
2197                 rsvp_input_p(mp, offp, proto);
2198                 return(IPPROTO_DONE);
2199         }
2200
2201         /* Can still get packets with rsvp_on = 0 if there is a local member
2202          * of the group to which the RSVP packet is addressed.  But in this
2203          * case we want to throw the packet away.
2204          */
2205
2206         if (!rsvp_on) {
2207                 m_freem(m);
2208                 return(IPPROTO_DONE);
2209         }
2210
2211         if (ip_rsvpd != NULL) {
2212                 *mp = m;
2213                 rip_input(mp, offp, proto);
2214                 return(IPPROTO_DONE);
2215         }
2216         /* Drop the packet */
2217         m_freem(m);
2218         return(IPPROTO_DONE);
2219 }