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