]> CyberLeo.Net >> Repos - FreeBSD/FreeBSD.git/blob - sys/netinet/ip_input.c
MFC of tzdata2009g:
[FreeBSD/FreeBSD.git] / sys / netinet / ip_input.c
1 /*-
2  * Copyright (c) 1982, 1986, 1988, 1993
3  *      The Regents of the University of California.  All rights reserved.
4  *
5  * Redistribution and use in source and binary forms, with or without
6  * modification, are permitted provided that the following conditions
7  * are met:
8  * 1. Redistributions of source code must retain the above copyright
9  *    notice, this list of conditions and the following disclaimer.
10  * 2. Redistributions in binary form must reproduce the above copyright
11  *    notice, this list of conditions and the following disclaimer in the
12  *    documentation and/or other materials provided with the distribution.
13  * 4. Neither the name of the University nor the names of its contributors
14  *    may be used to endorse or promote products derived from this software
15  *    without specific prior written permission.
16  *
17  * THIS SOFTWARE IS PROVIDED BY THE REGENTS AND CONTRIBUTORS ``AS IS'' AND
18  * ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
19  * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE
20  * ARE DISCLAIMED.  IN NO EVENT SHALL THE REGENTS OR CONTRIBUTORS BE LIABLE
21  * FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL
22  * DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS
23  * OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION)
24  * HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT
25  * LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY
26  * OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF
27  * SUCH DAMAGE.
28  *
29  *      @(#)ip_input.c  8.2 (Berkeley) 1/4/94
30  */
31
32 #include <sys/cdefs.h>
33 __FBSDID("$FreeBSD$");
34
35 #include "opt_bootp.h"
36 #include "opt_ipfw.h"
37 #include "opt_ipstealth.h"
38 #include "opt_ipsec.h"
39 #include "opt_route.h"
40 #include "opt_mac.h"
41 #include "opt_carp.h"
42
43 #include <sys/param.h>
44 #include <sys/systm.h>
45 #include <sys/callout.h>
46 #include <sys/mbuf.h>
47 #include <sys/malloc.h>
48 #include <sys/domain.h>
49 #include <sys/protosw.h>
50 #include <sys/socket.h>
51 #include <sys/time.h>
52 #include <sys/kernel.h>
53 #include <sys/lock.h>
54 #include <sys/rwlock.h>
55 #include <sys/syslog.h>
56 #include <sys/sysctl.h>
57 #include <sys/vimage.h>
58
59 #include <net/pfil.h>
60 #include <net/if.h>
61 #include <net/if_types.h>
62 #include <net/if_var.h>
63 #include <net/if_dl.h>
64 #include <net/route.h>
65 #include <net/netisr.h>
66 #include <net/vnet.h>
67 #include <net/flowtable.h>
68
69 #include <netinet/in.h>
70 #include <netinet/in_systm.h>
71 #include <netinet/in_var.h>
72 #include <netinet/ip.h>
73 #include <netinet/in_pcb.h>
74 #include <netinet/ip_var.h>
75 #include <netinet/ip_icmp.h>
76 #include <netinet/ip_options.h>
77 #include <machine/in_cksum.h>
78 #include <netinet/vinet.h>
79 #ifdef DEV_CARP
80 #include <netinet/ip_carp.h>
81 #endif
82 #ifdef IPSEC
83 #include <netinet/ip_ipsec.h>
84 #endif /* IPSEC */
85
86 #include <sys/socketvar.h>
87
88 /* XXX: Temporary until ipfw_ether and ipfw_bridge are converted. */
89 #include <netinet/ip_fw.h>
90 #include <netinet/ip_dummynet.h>
91
92 #include <security/mac/mac_framework.h>
93
94 #ifdef CTASSERT
95 CTASSERT(sizeof(struct ip) == 20);
96 #endif
97
98 #ifndef VIMAGE
99 #ifndef VIMAGE_GLOBALS
100 struct vnet_inet vnet_inet_0;
101 #endif
102 #endif
103
104 #ifdef VIMAGE_GLOBALS
105 static int      ipsendredirects;
106 static int      ip_checkinterface;
107 static int      ip_keepfaith;
108 static int      ip_sendsourcequench;
109 int     ip_defttl;
110 int     ip_do_randomid;
111 int     ipforwarding;
112 struct  in_ifaddrhead in_ifaddrhead;            /* first inet address */
113 struct  in_ifaddrhashhead *in_ifaddrhashtbl;    /* inet addr hash table  */
114 u_long  in_ifaddrhmask;                         /* mask for hash table */
115 struct ipstat ipstat;
116 static int ip_rsvp_on;
117 struct socket *ip_rsvpd;
118 int     rsvp_on;
119 static struct ipqhead ipq[IPREASS_NHASH];
120 static int      maxnipq;        /* Administrative limit on # reass queues. */
121 static int      maxfragsperpacket;
122 int     ipstealth;
123 static int      nipq;   /* Total # of reass queues */
124 #endif
125
126 SYSCTL_V_INT(V_NET, vnet_inet, _net_inet_ip, IPCTL_FORWARDING,
127     forwarding, CTLFLAG_RW, ipforwarding, 0,
128     "Enable IP forwarding between interfaces");
129
130 SYSCTL_V_INT(V_NET, vnet_inet, _net_inet_ip, IPCTL_SENDREDIRECTS,
131     redirect, CTLFLAG_RW, ipsendredirects, 0,
132     "Enable sending IP redirects");
133
134 SYSCTL_V_INT(V_NET, vnet_inet, _net_inet_ip, IPCTL_DEFTTL,
135     ttl, CTLFLAG_RW, ip_defttl, 0, "Maximum TTL on IP packets");
136
137 SYSCTL_V_INT(V_NET, vnet_inet, _net_inet_ip, IPCTL_KEEPFAITH,
138     keepfaith, CTLFLAG_RW, ip_keepfaith,        0,
139     "Enable packet capture for FAITH IPv4->IPv6 translater daemon");
140
141 SYSCTL_V_INT(V_NET, vnet_inet, _net_inet_ip, OID_AUTO,
142     sendsourcequench, CTLFLAG_RW, ip_sendsourcequench, 0,
143     "Enable the transmission of source quench packets");
144
145 SYSCTL_V_INT(V_NET, vnet_inet, _net_inet_ip, OID_AUTO, random_id,
146     CTLFLAG_RW, ip_do_randomid, 0, "Assign random ip_id values");
147
148 /*
149  * XXX - Setting ip_checkinterface mostly implements the receive side of
150  * the Strong ES model described in RFC 1122, but since the routing table
151  * and transmit implementation do not implement the Strong ES model,
152  * setting this to 1 results in an odd hybrid.
153  *
154  * XXX - ip_checkinterface currently must be disabled if you use ipnat
155  * to translate the destination address to another local interface.
156  *
157  * XXX - ip_checkinterface must be disabled if you add IP aliases
158  * to the loopback interface instead of the interface where the
159  * packets for those addresses are received.
160  */
161 SYSCTL_V_INT(V_NET, vnet_inet, _net_inet_ip, OID_AUTO,
162     check_interface, CTLFLAG_RW, ip_checkinterface, 0,
163     "Verify packet arrives on correct interface");
164
165 struct pfil_head inet_pfil_hook;        /* Packet filter hooks */
166
167 static struct   ifqueue ipintrq;
168 static int      ipqmaxlen = IFQ_MAXLEN;
169
170 extern  struct domain inetdomain;
171 extern  struct protosw inetsw[];
172 u_char  ip_protox[IPPROTO_MAX];
173
174 SYSCTL_INT(_net_inet_ip, IPCTL_INTRQMAXLEN, intr_queue_maxlen, CTLFLAG_RW,
175     &ipintrq.ifq_maxlen, 0, "Maximum size of the IP input queue");
176 SYSCTL_INT(_net_inet_ip, IPCTL_INTRQDROPS, intr_queue_drops, CTLFLAG_RD,
177     &ipintrq.ifq_drops, 0,
178     "Number of packets dropped from the IP input queue");
179
180 SYSCTL_V_STRUCT(V_NET, vnet_inet, _net_inet_ip, IPCTL_STATS, stats, CTLFLAG_RW,
181     ipstat, ipstat, "IP statistics (struct ipstat, netinet/ip_var.h)");
182
183 #ifdef VIMAGE_GLOBALS
184 static uma_zone_t ipq_zone;
185 #endif
186 static struct mtx ipqlock;
187
188 #define IPQ_LOCK()      mtx_lock(&ipqlock)
189 #define IPQ_UNLOCK()    mtx_unlock(&ipqlock)
190 #define IPQ_LOCK_INIT() mtx_init(&ipqlock, "ipqlock", NULL, MTX_DEF)
191 #define IPQ_LOCK_ASSERT()       mtx_assert(&ipqlock, MA_OWNED)
192
193 static void     maxnipq_update(void);
194 static void     ipq_zone_change(void *);
195
196 SYSCTL_V_INT(V_NET, vnet_inet, _net_inet_ip, OID_AUTO, fragpackets,
197     CTLFLAG_RD, nipq, 0,
198     "Current number of IPv4 fragment reassembly queue entries");
199
200 SYSCTL_V_INT(V_NET, vnet_inet, _net_inet_ip, OID_AUTO, maxfragsperpacket,
201     CTLFLAG_RW, maxfragsperpacket, 0,
202     "Maximum number of IPv4 fragments allowed per packet");
203
204 struct callout  ipport_tick_callout;
205
206 #ifdef IPCTL_DEFMTU
207 SYSCTL_INT(_net_inet_ip, IPCTL_DEFMTU, mtu, CTLFLAG_RW,
208     &ip_mtu, 0, "Default MTU");
209 #endif
210
211 #ifdef IPSTEALTH
212 SYSCTL_V_INT(V_NET, vnet_inet, _net_inet_ip, OID_AUTO, stealth, CTLFLAG_RW,
213     ipstealth, 0, "IP stealth mode, no TTL decrementation on forwarding");
214 #endif
215 static int ip_output_flowtable_size = 2048;
216 TUNABLE_INT("net.inet.ip.output_flowtable_size", &ip_output_flowtable_size);
217 SYSCTL_V_INT(V_NET, vnet_inet, _net_inet_ip, OID_AUTO, output_flowtable_size,
218     CTLFLAG_RDTUN, ip_output_flowtable_size, 2048,
219     "number of entries in the per-cpu output flow caches");
220
221 /*
222  * ipfw_ether and ipfw_bridge hooks.
223  * XXX: Temporary until those are converted to pfil_hooks as well.
224  */
225 ip_fw_chk_t *ip_fw_chk_ptr = NULL;
226 ip_dn_io_t *ip_dn_io_ptr = NULL;
227 #ifdef VIMAGE_GLOBALS
228 int fw_one_pass;
229 #endif
230 struct flowtable *ip_ft;
231
232 static void     ip_freef(struct ipqhead *, struct ipq *);
233
234 #ifndef VIMAGE_GLOBALS
235 static void vnet_inet_register(void);
236  
237 static const vnet_modinfo_t vnet_inet_modinfo = {
238         .vmi_id         = VNET_MOD_INET,
239         .vmi_name       = "inet",
240 };
241  
242 static void vnet_inet_register()
243 {
244   
245         vnet_mod_register(&vnet_inet_modinfo);
246 }
247  
248 SYSINIT(inet, SI_SUB_PROTO_BEGIN, SI_ORDER_FIRST, vnet_inet_register, 0);
249 #endif
250
251 /*
252  * IP initialization: fill in IP protocol switch table.
253  * All protocols not implemented in kernel go to raw IP protocol handler.
254  */
255 void
256 ip_init(void)
257 {
258         INIT_VNET_INET(curvnet);
259         struct protosw *pr;
260         int i;
261
262         V_ipsendredirects = 1; /* XXX */
263         V_ip_checkinterface = 0;
264         V_ip_keepfaith = 0;
265         V_ip_sendsourcequench = 0;
266         V_rsvp_on = 0;
267         V_ip_defttl = IPDEFTTL;
268         V_ip_do_randomid = 0;
269         V_ip_id = time_second & 0xffff;
270         V_ipforwarding = 0;
271         V_ipstealth = 0;
272         V_nipq = 0;     /* Total # of reass queues */
273
274         V_ipport_lowfirstauto = IPPORT_RESERVED - 1;    /* 1023 */
275         V_ipport_lowlastauto = IPPORT_RESERVEDSTART;    /* 600 */
276         V_ipport_firstauto = IPPORT_EPHEMERALFIRST;     /* 10000 */
277         V_ipport_lastauto = IPPORT_EPHEMERALLAST;       /* 65535 */
278         V_ipport_hifirstauto = IPPORT_HIFIRSTAUTO;      /* 49152 */
279         V_ipport_hilastauto = IPPORT_HILASTAUTO;        /* 65535 */
280         V_ipport_reservedhigh = IPPORT_RESERVED - 1;    /* 1023 */
281         V_ipport_reservedlow = 0;
282         V_ipport_randomized = 1;        /* user controlled via sysctl */
283         V_ipport_randomcps = 10;        /* user controlled via sysctl */
284         V_ipport_randomtime = 45;       /* user controlled via sysctl */
285         V_ipport_stoprandom = 0;        /* toggled by ipport_tick */
286
287         V_fw_one_pass = 1;
288
289 #ifdef NOTYET
290         /* XXX global static but not instantiated in this file */
291         V_ipfastforward_active = 0;
292         V_subnetsarelocal = 0;
293         V_sameprefixcarponly = 0;
294 #endif
295
296         TAILQ_INIT(&V_in_ifaddrhead);
297         V_in_ifaddrhashtbl = hashinit(INADDR_NHASH, M_IFADDR, &V_in_ifaddrhmask);
298
299         /* Initialize IP reassembly queue. */
300         for (i = 0; i < IPREASS_NHASH; i++)
301                 TAILQ_INIT(&V_ipq[i]);
302         V_maxnipq = nmbclusters / 32;
303         V_maxfragsperpacket = 16;
304         V_ipq_zone = uma_zcreate("ipq", sizeof(struct ipq), NULL, NULL, NULL,
305             NULL, UMA_ALIGN_PTR, 0);
306         maxnipq_update();
307
308         /* Skip initialization of globals for non-default instances. */
309         if (!IS_DEFAULT_VNET(curvnet))
310                 return;
311
312         pr = pffindproto(PF_INET, IPPROTO_RAW, SOCK_RAW);
313         if (pr == NULL)
314                 panic("ip_init: PF_INET not found");
315
316         /* Initialize the entire ip_protox[] array to IPPROTO_RAW. */
317         for (i = 0; i < IPPROTO_MAX; i++)
318                 ip_protox[i] = pr - inetsw;
319         /*
320          * Cycle through IP protocols and put them into the appropriate place
321          * in ip_protox[].
322          */
323         for (pr = inetdomain.dom_protosw;
324             pr < inetdomain.dom_protoswNPROTOSW; pr++)
325                 if (pr->pr_domain->dom_family == PF_INET &&
326                     pr->pr_protocol && pr->pr_protocol != IPPROTO_RAW) {
327                         /* Be careful to only index valid IP protocols. */
328                         if (pr->pr_protocol < IPPROTO_MAX)
329                                 ip_protox[pr->pr_protocol] = pr - inetsw;
330                 }
331
332         /* Initialize packet filter hooks. */
333         inet_pfil_hook.ph_type = PFIL_TYPE_AF;
334         inet_pfil_hook.ph_af = AF_INET;
335         if ((i = pfil_head_register(&inet_pfil_hook)) != 0)
336                 printf("%s: WARNING: unable to register pfil hook, "
337                         "error %d\n", __func__, i);
338
339         /* Start ipport_tick. */
340         callout_init(&ipport_tick_callout, CALLOUT_MPSAFE);
341         ipport_tick(NULL);
342         EVENTHANDLER_REGISTER(shutdown_pre_sync, ip_fini, NULL,
343                 SHUTDOWN_PRI_DEFAULT);
344         EVENTHANDLER_REGISTER(nmbclusters_change, ipq_zone_change,
345                 NULL, EVENTHANDLER_PRI_ANY);
346
347         /* Initialize various other remaining things. */
348         IPQ_LOCK_INIT();
349         ipintrq.ifq_maxlen = ipqmaxlen;
350         mtx_init(&ipintrq.ifq_mtx, "ip_inq", NULL, MTX_DEF);
351         netisr_register(NETISR_IP, ip_input, &ipintrq, 0);
352
353         ip_ft = flowtable_alloc(ip_output_flowtable_size, FL_PCPU);
354 }
355
356 void
357 ip_fini(void *xtp)
358 {
359
360         callout_stop(&ipport_tick_callout);
361 }
362
363 /*
364  * Ip input routine.  Checksum and byte swap header.  If fragmented
365  * try to reassemble.  Process options.  Pass to next level.
366  */
367 void
368 ip_input(struct mbuf *m)
369 {
370         INIT_VNET_INET(curvnet);
371         struct ip *ip = NULL;
372         struct in_ifaddr *ia = NULL;
373         struct ifaddr *ifa;
374         struct ifnet *ifp;
375         int    checkif, hlen = 0;
376         u_short sum;
377         int dchg = 0;                           /* dest changed after fw */
378         struct in_addr odst;                    /* original dst address */
379
380         M_ASSERTPKTHDR(m);
381
382         if (m->m_flags & M_FASTFWD_OURS) {
383                 /*
384                  * Firewall or NAT changed destination to local.
385                  * We expect ip_len and ip_off to be in host byte order.
386                  */
387                 m->m_flags &= ~M_FASTFWD_OURS;
388                 /* Set up some basics that will be used later. */
389                 ip = mtod(m, struct ip *);
390                 hlen = ip->ip_hl << 2;
391                 goto ours;
392         }
393
394         IPSTAT_INC(ips_total);
395
396         if (m->m_pkthdr.len < sizeof(struct ip))
397                 goto tooshort;
398
399         if (m->m_len < sizeof (struct ip) &&
400             (m = m_pullup(m, sizeof (struct ip))) == NULL) {
401                 IPSTAT_INC(ips_toosmall);
402                 return;
403         }
404         ip = mtod(m, struct ip *);
405
406         if (ip->ip_v != IPVERSION) {
407                 IPSTAT_INC(ips_badvers);
408                 goto bad;
409         }
410
411         hlen = ip->ip_hl << 2;
412         if (hlen < sizeof(struct ip)) { /* minimum header length */
413                 IPSTAT_INC(ips_badhlen);
414                 goto bad;
415         }
416         if (hlen > m->m_len) {
417                 if ((m = m_pullup(m, hlen)) == NULL) {
418                         IPSTAT_INC(ips_badhlen);
419                         return;
420                 }
421                 ip = mtod(m, struct ip *);
422         }
423
424         /* 127/8 must not appear on wire - RFC1122 */
425         ifp = m->m_pkthdr.rcvif;
426         if ((ntohl(ip->ip_dst.s_addr) >> IN_CLASSA_NSHIFT) == IN_LOOPBACKNET ||
427             (ntohl(ip->ip_src.s_addr) >> IN_CLASSA_NSHIFT) == IN_LOOPBACKNET) {
428                 if ((ifp->if_flags & IFF_LOOPBACK) == 0) {
429                         IPSTAT_INC(ips_badaddr);
430                         goto bad;
431                 }
432         }
433
434         if (m->m_pkthdr.csum_flags & CSUM_IP_CHECKED) {
435                 sum = !(m->m_pkthdr.csum_flags & CSUM_IP_VALID);
436         } else {
437                 if (hlen == sizeof(struct ip)) {
438                         sum = in_cksum_hdr(ip);
439                 } else {
440                         sum = in_cksum(m, hlen);
441                 }
442         }
443         if (sum) {
444                 IPSTAT_INC(ips_badsum);
445                 goto bad;
446         }
447
448 #ifdef ALTQ
449         if (altq_input != NULL && (*altq_input)(m, AF_INET) == 0)
450                 /* packet is dropped by traffic conditioner */
451                 return;
452 #endif
453
454         /*
455          * Convert fields to host representation.
456          */
457         ip->ip_len = ntohs(ip->ip_len);
458         if (ip->ip_len < hlen) {
459                 IPSTAT_INC(ips_badlen);
460                 goto bad;
461         }
462         ip->ip_off = ntohs(ip->ip_off);
463
464         /*
465          * Check that the amount of data in the buffers
466          * is as at least much as the IP header would have us expect.
467          * Trim mbufs if longer than we expect.
468          * Drop packet if shorter than we expect.
469          */
470         if (m->m_pkthdr.len < ip->ip_len) {
471 tooshort:
472                 IPSTAT_INC(ips_tooshort);
473                 goto bad;
474         }
475         if (m->m_pkthdr.len > ip->ip_len) {
476                 if (m->m_len == m->m_pkthdr.len) {
477                         m->m_len = ip->ip_len;
478                         m->m_pkthdr.len = ip->ip_len;
479                 } else
480                         m_adj(m, ip->ip_len - m->m_pkthdr.len);
481         }
482 #ifdef IPSEC
483         /*
484          * Bypass packet filtering for packets from a tunnel (gif).
485          */
486         if (ip_ipsec_filtertunnel(m))
487                 goto passin;
488 #endif /* IPSEC */
489
490         /*
491          * Run through list of hooks for input packets.
492          *
493          * NB: Beware of the destination address changing (e.g.
494          *     by NAT rewriting).  When this happens, tell
495          *     ip_forward to do the right thing.
496          */
497
498         /* Jump over all PFIL processing if hooks are not active. */
499         if (!PFIL_HOOKED(&inet_pfil_hook))
500                 goto passin;
501
502         odst = ip->ip_dst;
503         if (pfil_run_hooks(&inet_pfil_hook, &m, ifp, PFIL_IN, NULL) != 0)
504                 return;
505         if (m == NULL)                  /* consumed by filter */
506                 return;
507
508         ip = mtod(m, struct ip *);
509         dchg = (odst.s_addr != ip->ip_dst.s_addr);
510         ifp = m->m_pkthdr.rcvif;
511
512 #ifdef IPFIREWALL_FORWARD
513         if (m->m_flags & M_FASTFWD_OURS) {
514                 m->m_flags &= ~M_FASTFWD_OURS;
515                 goto ours;
516         }
517         if ((dchg = (m_tag_find(m, PACKET_TAG_IPFORWARD, NULL) != NULL)) != 0) {
518                 /*
519                  * Directly ship on the packet.  This allows to forward packets
520                  * that were destined for us to some other directly connected
521                  * host.
522                  */
523                 ip_forward(m, dchg);
524                 return;
525         }
526 #endif /* IPFIREWALL_FORWARD */
527
528 passin:
529         /*
530          * Process options and, if not destined for us,
531          * ship it on.  ip_dooptions returns 1 when an
532          * error was detected (causing an icmp message
533          * to be sent and the original packet to be freed).
534          */
535         if (hlen > sizeof (struct ip) && ip_dooptions(m, 0))
536                 return;
537
538         /* greedy RSVP, snatches any PATH packet of the RSVP protocol and no
539          * matter if it is destined to another node, or whether it is 
540          * a multicast one, RSVP wants it! and prevents it from being forwarded
541          * anywhere else. Also checks if the rsvp daemon is running before
542          * grabbing the packet.
543          */
544         if (V_rsvp_on && ip->ip_p==IPPROTO_RSVP) 
545                 goto ours;
546
547         /*
548          * Check our list of addresses, to see if the packet is for us.
549          * If we don't have any addresses, assume any unicast packet
550          * we receive might be for us (and let the upper layers deal
551          * with it).
552          */
553         if (TAILQ_EMPTY(&V_in_ifaddrhead) &&
554             (m->m_flags & (M_MCAST|M_BCAST)) == 0)
555                 goto ours;
556
557         /*
558          * Enable a consistency check between the destination address
559          * and the arrival interface for a unicast packet (the RFC 1122
560          * strong ES model) if IP forwarding is disabled and the packet
561          * is not locally generated and the packet is not subject to
562          * 'ipfw fwd'.
563          *
564          * XXX - Checking also should be disabled if the destination
565          * address is ipnat'ed to a different interface.
566          *
567          * XXX - Checking is incompatible with IP aliases added
568          * to the loopback interface instead of the interface where
569          * the packets are received.
570          *
571          * XXX - This is the case for carp vhost IPs as well so we
572          * insert a workaround. If the packet got here, we already
573          * checked with carp_iamatch() and carp_forus().
574          */
575         checkif = V_ip_checkinterface && (V_ipforwarding == 0) && 
576             ifp != NULL && ((ifp->if_flags & IFF_LOOPBACK) == 0) &&
577 #ifdef DEV_CARP
578             !ifp->if_carp &&
579 #endif
580             (dchg == 0);
581
582         /*
583          * Check for exact addresses in the hash bucket.
584          */
585         LIST_FOREACH(ia, INADDR_HASH(ip->ip_dst.s_addr), ia_hash) {
586                 /*
587                  * If the address matches, verify that the packet
588                  * arrived via the correct interface if checking is
589                  * enabled.
590                  */
591                 if (IA_SIN(ia)->sin_addr.s_addr == ip->ip_dst.s_addr && 
592                     (!checkif || ia->ia_ifp == ifp))
593                         goto ours;
594         }
595         /*
596          * Check for broadcast addresses.
597          *
598          * Only accept broadcast packets that arrive via the matching
599          * interface.  Reception of forwarded directed broadcasts would
600          * be handled via ip_forward() and ether_output() with the loopback
601          * into the stack for SIMPLEX interfaces handled by ether_output().
602          */
603         if (ifp != NULL && ifp->if_flags & IFF_BROADCAST) {
604                 IF_ADDR_LOCK(ifp);
605                 TAILQ_FOREACH(ifa, &ifp->if_addrhead, ifa_link) {
606                         if (ifa->ifa_addr->sa_family != AF_INET)
607                                 continue;
608                         ia = ifatoia(ifa);
609                         if (satosin(&ia->ia_broadaddr)->sin_addr.s_addr ==
610                             ip->ip_dst.s_addr) {
611                                 IF_ADDR_UNLOCK(ifp);
612                                 goto ours;
613                         }
614                         if (ia->ia_netbroadcast.s_addr == ip->ip_dst.s_addr) {
615                                 IF_ADDR_UNLOCK(ifp);
616                                 goto ours;
617                         }
618 #ifdef BOOTP_COMPAT
619                         if (IA_SIN(ia)->sin_addr.s_addr == INADDR_ANY) {
620                                 IF_ADDR_UNLOCK(ifp);
621                                 goto ours;
622                         }
623 #endif
624                 }
625                 IF_ADDR_UNLOCK(ifp);
626         }
627         /* RFC 3927 2.7: Do not forward datagrams for 169.254.0.0/16. */
628         if (IN_LINKLOCAL(ntohl(ip->ip_dst.s_addr))) {
629                 IPSTAT_INC(ips_cantforward);
630                 m_freem(m);
631                 return;
632         }
633         if (IN_MULTICAST(ntohl(ip->ip_dst.s_addr))) {
634                 if (V_ip_mrouter) {
635                         /*
636                          * If we are acting as a multicast router, all
637                          * incoming multicast packets are passed to the
638                          * kernel-level multicast forwarding function.
639                          * The packet is returned (relatively) intact; if
640                          * ip_mforward() returns a non-zero value, the packet
641                          * must be discarded, else it may be accepted below.
642                          */
643                         if (ip_mforward && ip_mforward(ip, ifp, m, 0) != 0) {
644                                 IPSTAT_INC(ips_cantforward);
645                                 m_freem(m);
646                                 return;
647                         }
648
649                         /*
650                          * The process-level routing daemon needs to receive
651                          * all multicast IGMP packets, whether or not this
652                          * host belongs to their destination groups.
653                          */
654                         if (ip->ip_p == IPPROTO_IGMP)
655                                 goto ours;
656                         IPSTAT_INC(ips_forward);
657                 }
658                 /*
659                  * Assume the packet is for us, to avoid prematurely taking
660                  * a lock on the in_multi hash. Protocols must perform
661                  * their own filtering and update statistics accordingly.
662                  */
663                 goto ours;
664         }
665         if (ip->ip_dst.s_addr == (u_long)INADDR_BROADCAST)
666                 goto ours;
667         if (ip->ip_dst.s_addr == INADDR_ANY)
668                 goto ours;
669
670         /*
671          * FAITH(Firewall Aided Internet Translator)
672          */
673         if (ifp && ifp->if_type == IFT_FAITH) {
674                 if (V_ip_keepfaith) {
675                         if (ip->ip_p == IPPROTO_TCP || ip->ip_p == IPPROTO_ICMP) 
676                                 goto ours;
677                 }
678                 m_freem(m);
679                 return;
680         }
681
682         /*
683          * Not for us; forward if possible and desirable.
684          */
685         if (V_ipforwarding == 0) {
686                 IPSTAT_INC(ips_cantforward);
687                 m_freem(m);
688         } else {
689 #ifdef IPSEC
690                 if (ip_ipsec_fwd(m))
691                         goto bad;
692 #endif /* IPSEC */
693                 ip_forward(m, dchg);
694         }
695         return;
696
697 ours:
698 #ifdef IPSTEALTH
699         /*
700          * IPSTEALTH: Process non-routing options only
701          * if the packet is destined for us.
702          */
703         if (V_ipstealth && hlen > sizeof (struct ip) &&
704             ip_dooptions(m, 1))
705                 return;
706 #endif /* IPSTEALTH */
707
708         /* Count the packet in the ip address stats */
709         if (ia != NULL) {
710                 ia->ia_ifa.if_ipackets++;
711                 ia->ia_ifa.if_ibytes += m->m_pkthdr.len;
712         }
713
714         /*
715          * Attempt reassembly; if it succeeds, proceed.
716          * ip_reass() will return a different mbuf.
717          */
718         if (ip->ip_off & (IP_MF | IP_OFFMASK)) {
719                 m = ip_reass(m);
720                 if (m == NULL)
721                         return;
722                 ip = mtod(m, struct ip *);
723                 /* Get the header length of the reassembled packet */
724                 hlen = ip->ip_hl << 2;
725         }
726
727         /*
728          * Further protocols expect the packet length to be w/o the
729          * IP header.
730          */
731         ip->ip_len -= hlen;
732
733 #ifdef IPSEC
734         /*
735          * enforce IPsec policy checking if we are seeing last header.
736          * note that we do not visit this with protocols with pcb layer
737          * code - like udp/tcp/raw ip.
738          */
739         if (ip_ipsec_input(m))
740                 goto bad;
741 #endif /* IPSEC */
742
743         /*
744          * Switch out to protocol's input routine.
745          */
746         IPSTAT_INC(ips_delivered);
747
748         (*inetsw[ip_protox[ip->ip_p]].pr_input)(m, hlen);
749         return;
750 bad:
751         m_freem(m);
752 }
753
754 /*
755  * After maxnipq has been updated, propagate the change to UMA.  The UMA zone
756  * max has slightly different semantics than the sysctl, for historical
757  * reasons.
758  */
759 static void
760 maxnipq_update(void)
761 {
762         INIT_VNET_INET(curvnet);
763
764         /*
765          * -1 for unlimited allocation.
766          */
767         if (V_maxnipq < 0)
768                 uma_zone_set_max(V_ipq_zone, 0);
769         /*
770          * Positive number for specific bound.
771          */
772         if (V_maxnipq > 0)
773                 uma_zone_set_max(V_ipq_zone, V_maxnipq);
774         /*
775          * Zero specifies no further fragment queue allocation -- set the
776          * bound very low, but rely on implementation elsewhere to actually
777          * prevent allocation and reclaim current queues.
778          */
779         if (V_maxnipq == 0)
780                 uma_zone_set_max(V_ipq_zone, 1);
781 }
782
783 static void
784 ipq_zone_change(void *tag)
785 {
786         INIT_VNET_INET(curvnet);
787
788         if (V_maxnipq > 0 && V_maxnipq < (nmbclusters / 32)) {
789                 V_maxnipq = nmbclusters / 32;
790                 maxnipq_update();
791         }
792 }
793
794 static int
795 sysctl_maxnipq(SYSCTL_HANDLER_ARGS)
796 {
797         INIT_VNET_INET(curvnet);
798         int error, i;
799
800         i = V_maxnipq;
801         error = sysctl_handle_int(oidp, &i, 0, req);
802         if (error || !req->newptr)
803                 return (error);
804
805         /*
806          * XXXRW: Might be a good idea to sanity check the argument and place
807          * an extreme upper bound.
808          */
809         if (i < -1)
810                 return (EINVAL);
811         V_maxnipq = i;
812         maxnipq_update();
813         return (0);
814 }
815
816 SYSCTL_PROC(_net_inet_ip, OID_AUTO, maxfragpackets, CTLTYPE_INT|CTLFLAG_RW,
817     NULL, 0, sysctl_maxnipq, "I",
818     "Maximum number of IPv4 fragment reassembly queue entries");
819
820 /*
821  * Take incoming datagram fragment and try to reassemble it into
822  * whole datagram.  If the argument is the first fragment or one
823  * in between the function will return NULL and store the mbuf
824  * in the fragment chain.  If the argument is the last fragment
825  * the packet will be reassembled and the pointer to the new
826  * mbuf returned for further processing.  Only m_tags attached
827  * to the first packet/fragment are preserved.
828  * The IP header is *NOT* adjusted out of iplen.
829  */
830 struct mbuf *
831 ip_reass(struct mbuf *m)
832 {
833         INIT_VNET_INET(curvnet);
834         struct ip *ip;
835         struct mbuf *p, *q, *nq, *t;
836         struct ipq *fp = NULL;
837         struct ipqhead *head;
838         int i, hlen, next;
839         u_int8_t ecn, ecn0;
840         u_short hash;
841
842         /* If maxnipq or maxfragsperpacket are 0, never accept fragments. */
843         if (V_maxnipq == 0 || V_maxfragsperpacket == 0) {
844                 IPSTAT_INC(ips_fragments);
845                 IPSTAT_INC(ips_fragdropped);
846                 m_freem(m);
847                 return (NULL);
848         }
849
850         ip = mtod(m, struct ip *);
851         hlen = ip->ip_hl << 2;
852
853         hash = IPREASS_HASH(ip->ip_src.s_addr, ip->ip_id);
854         head = &V_ipq[hash];
855         IPQ_LOCK();
856
857         /*
858          * Look for queue of fragments
859          * of this datagram.
860          */
861         TAILQ_FOREACH(fp, head, ipq_list)
862                 if (ip->ip_id == fp->ipq_id &&
863                     ip->ip_src.s_addr == fp->ipq_src.s_addr &&
864                     ip->ip_dst.s_addr == fp->ipq_dst.s_addr &&
865 #ifdef MAC
866                     mac_ipq_match(m, fp) &&
867 #endif
868                     ip->ip_p == fp->ipq_p)
869                         goto found;
870
871         fp = NULL;
872
873         /*
874          * Attempt to trim the number of allocated fragment queues if it
875          * exceeds the administrative limit.
876          */
877         if ((V_nipq > V_maxnipq) && (V_maxnipq > 0)) {
878                 /*
879                  * drop something from the tail of the current queue
880                  * before proceeding further
881                  */
882                 struct ipq *q = TAILQ_LAST(head, ipqhead);
883                 if (q == NULL) {   /* gak */
884                         for (i = 0; i < IPREASS_NHASH; i++) {
885                                 struct ipq *r = TAILQ_LAST(&V_ipq[i], ipqhead);
886                                 if (r) {
887                                         IPSTAT_ADD(ips_fragtimeout,
888                                             r->ipq_nfrags);
889                                         ip_freef(&V_ipq[i], r);
890                                         break;
891                                 }
892                         }
893                 } else {
894                         IPSTAT_ADD(ips_fragtimeout, q->ipq_nfrags);
895                         ip_freef(head, q);
896                 }
897         }
898
899 found:
900         /*
901          * Adjust ip_len to not reflect header,
902          * convert offset of this to bytes.
903          */
904         ip->ip_len -= hlen;
905         if (ip->ip_off & IP_MF) {
906                 /*
907                  * Make sure that fragments have a data length
908                  * that's a non-zero multiple of 8 bytes.
909                  */
910                 if (ip->ip_len == 0 || (ip->ip_len & 0x7) != 0) {
911                         IPSTAT_INC(ips_toosmall); /* XXX */
912                         goto dropfrag;
913                 }
914                 m->m_flags |= M_FRAG;
915         } else
916                 m->m_flags &= ~M_FRAG;
917         ip->ip_off <<= 3;
918
919
920         /*
921          * Attempt reassembly; if it succeeds, proceed.
922          * ip_reass() will return a different mbuf.
923          */
924         IPSTAT_INC(ips_fragments);
925         m->m_pkthdr.header = ip;
926
927         /* Previous ip_reass() started here. */
928         /*
929          * Presence of header sizes in mbufs
930          * would confuse code below.
931          */
932         m->m_data += hlen;
933         m->m_len -= hlen;
934
935         /*
936          * If first fragment to arrive, create a reassembly queue.
937          */
938         if (fp == NULL) {
939                 fp = uma_zalloc(V_ipq_zone, M_NOWAIT);
940                 if (fp == NULL)
941                         goto dropfrag;
942 #ifdef MAC
943                 if (mac_ipq_init(fp, M_NOWAIT) != 0) {
944                         uma_zfree(V_ipq_zone, fp);
945                         fp = NULL;
946                         goto dropfrag;
947                 }
948                 mac_ipq_create(m, fp);
949 #endif
950                 TAILQ_INSERT_HEAD(head, fp, ipq_list);
951                 V_nipq++;
952                 fp->ipq_nfrags = 1;
953                 fp->ipq_ttl = IPFRAGTTL;
954                 fp->ipq_p = ip->ip_p;
955                 fp->ipq_id = ip->ip_id;
956                 fp->ipq_src = ip->ip_src;
957                 fp->ipq_dst = ip->ip_dst;
958                 fp->ipq_frags = m;
959                 m->m_nextpkt = NULL;
960                 goto done;
961         } else {
962                 fp->ipq_nfrags++;
963 #ifdef MAC
964                 mac_ipq_update(m, fp);
965 #endif
966         }
967
968 #define GETIP(m)        ((struct ip*)((m)->m_pkthdr.header))
969
970         /*
971          * Handle ECN by comparing this segment with the first one;
972          * if CE is set, do not lose CE.
973          * drop if CE and not-ECT are mixed for the same packet.
974          */
975         ecn = ip->ip_tos & IPTOS_ECN_MASK;
976         ecn0 = GETIP(fp->ipq_frags)->ip_tos & IPTOS_ECN_MASK;
977         if (ecn == IPTOS_ECN_CE) {
978                 if (ecn0 == IPTOS_ECN_NOTECT)
979                         goto dropfrag;
980                 if (ecn0 != IPTOS_ECN_CE)
981                         GETIP(fp->ipq_frags)->ip_tos |= IPTOS_ECN_CE;
982         }
983         if (ecn == IPTOS_ECN_NOTECT && ecn0 != IPTOS_ECN_NOTECT)
984                 goto dropfrag;
985
986         /*
987          * Find a segment which begins after this one does.
988          */
989         for (p = NULL, q = fp->ipq_frags; q; p = q, q = q->m_nextpkt)
990                 if (GETIP(q)->ip_off > ip->ip_off)
991                         break;
992
993         /*
994          * If there is a preceding segment, it may provide some of
995          * our data already.  If so, drop the data from the incoming
996          * segment.  If it provides all of our data, drop us, otherwise
997          * stick new segment in the proper place.
998          *
999          * If some of the data is dropped from the the preceding
1000          * segment, then it's checksum is invalidated.
1001          */
1002         if (p) {
1003                 i = GETIP(p)->ip_off + GETIP(p)->ip_len - ip->ip_off;
1004                 if (i > 0) {
1005                         if (i >= ip->ip_len)
1006                                 goto dropfrag;
1007                         m_adj(m, i);
1008                         m->m_pkthdr.csum_flags = 0;
1009                         ip->ip_off += i;
1010                         ip->ip_len -= i;
1011                 }
1012                 m->m_nextpkt = p->m_nextpkt;
1013                 p->m_nextpkt = m;
1014         } else {
1015                 m->m_nextpkt = fp->ipq_frags;
1016                 fp->ipq_frags = m;
1017         }
1018
1019         /*
1020          * While we overlap succeeding segments trim them or,
1021          * if they are completely covered, dequeue them.
1022          */
1023         for (; q != NULL && ip->ip_off + ip->ip_len > GETIP(q)->ip_off;
1024              q = nq) {
1025                 i = (ip->ip_off + ip->ip_len) - GETIP(q)->ip_off;
1026                 if (i < GETIP(q)->ip_len) {
1027                         GETIP(q)->ip_len -= i;
1028                         GETIP(q)->ip_off += i;
1029                         m_adj(q, i);
1030                         q->m_pkthdr.csum_flags = 0;
1031                         break;
1032                 }
1033                 nq = q->m_nextpkt;
1034                 m->m_nextpkt = nq;
1035                 IPSTAT_INC(ips_fragdropped);
1036                 fp->ipq_nfrags--;
1037                 m_freem(q);
1038         }
1039
1040         /*
1041          * Check for complete reassembly and perform frag per packet
1042          * limiting.
1043          *
1044          * Frag limiting is performed here so that the nth frag has
1045          * a chance to complete the packet before we drop the packet.
1046          * As a result, n+1 frags are actually allowed per packet, but
1047          * only n will ever be stored. (n = maxfragsperpacket.)
1048          *
1049          */
1050         next = 0;
1051         for (p = NULL, q = fp->ipq_frags; q; p = q, q = q->m_nextpkt) {
1052                 if (GETIP(q)->ip_off != next) {
1053                         if (fp->ipq_nfrags > V_maxfragsperpacket) {
1054                                 IPSTAT_ADD(ips_fragdropped, fp->ipq_nfrags);
1055                                 ip_freef(head, fp);
1056                         }
1057                         goto done;
1058                 }
1059                 next += GETIP(q)->ip_len;
1060         }
1061         /* Make sure the last packet didn't have the IP_MF flag */
1062         if (p->m_flags & M_FRAG) {
1063                 if (fp->ipq_nfrags > V_maxfragsperpacket) {
1064                         IPSTAT_ADD(ips_fragdropped, fp->ipq_nfrags);
1065                         ip_freef(head, fp);
1066                 }
1067                 goto done;
1068         }
1069
1070         /*
1071          * Reassembly is complete.  Make sure the packet is a sane size.
1072          */
1073         q = fp->ipq_frags;
1074         ip = GETIP(q);
1075         if (next + (ip->ip_hl << 2) > IP_MAXPACKET) {
1076                 IPSTAT_INC(ips_toolong);
1077                 IPSTAT_ADD(ips_fragdropped, fp->ipq_nfrags);
1078                 ip_freef(head, fp);
1079                 goto done;
1080         }
1081
1082         /*
1083          * Concatenate fragments.
1084          */
1085         m = q;
1086         t = m->m_next;
1087         m->m_next = NULL;
1088         m_cat(m, t);
1089         nq = q->m_nextpkt;
1090         q->m_nextpkt = NULL;
1091         for (q = nq; q != NULL; q = nq) {
1092                 nq = q->m_nextpkt;
1093                 q->m_nextpkt = NULL;
1094                 m->m_pkthdr.csum_flags &= q->m_pkthdr.csum_flags;
1095                 m->m_pkthdr.csum_data += q->m_pkthdr.csum_data;
1096                 m_cat(m, q);
1097         }
1098         /*
1099          * In order to do checksumming faster we do 'end-around carry' here
1100          * (and not in for{} loop), though it implies we are not going to
1101          * reassemble more than 64k fragments.
1102          */
1103         m->m_pkthdr.csum_data =
1104             (m->m_pkthdr.csum_data & 0xffff) + (m->m_pkthdr.csum_data >> 16);
1105 #ifdef MAC
1106         mac_ipq_reassemble(fp, m);
1107         mac_ipq_destroy(fp);
1108 #endif
1109
1110         /*
1111          * Create header for new ip packet by modifying header of first
1112          * packet;  dequeue and discard fragment reassembly header.
1113          * Make header visible.
1114          */
1115         ip->ip_len = (ip->ip_hl << 2) + next;
1116         ip->ip_src = fp->ipq_src;
1117         ip->ip_dst = fp->ipq_dst;
1118         TAILQ_REMOVE(head, fp, ipq_list);
1119         V_nipq--;
1120         uma_zfree(V_ipq_zone, fp);
1121         m->m_len += (ip->ip_hl << 2);
1122         m->m_data -= (ip->ip_hl << 2);
1123         /* some debugging cruft by sklower, below, will go away soon */
1124         if (m->m_flags & M_PKTHDR)      /* XXX this should be done elsewhere */
1125                 m_fixhdr(m);
1126         IPSTAT_INC(ips_reassembled);
1127         IPQ_UNLOCK();
1128         return (m);
1129
1130 dropfrag:
1131         IPSTAT_INC(ips_fragdropped);
1132         if (fp != NULL)
1133                 fp->ipq_nfrags--;
1134         m_freem(m);
1135 done:
1136         IPQ_UNLOCK();
1137         return (NULL);
1138
1139 #undef GETIP
1140 }
1141
1142 /*
1143  * Free a fragment reassembly header and all
1144  * associated datagrams.
1145  */
1146 static void
1147 ip_freef(struct ipqhead *fhp, struct ipq *fp)
1148 {
1149         INIT_VNET_INET(curvnet);
1150         struct mbuf *q;
1151
1152         IPQ_LOCK_ASSERT();
1153
1154         while (fp->ipq_frags) {
1155                 q = fp->ipq_frags;
1156                 fp->ipq_frags = q->m_nextpkt;
1157                 m_freem(q);
1158         }
1159         TAILQ_REMOVE(fhp, fp, ipq_list);
1160         uma_zfree(V_ipq_zone, fp);
1161         V_nipq--;
1162 }
1163
1164 /*
1165  * IP timer processing;
1166  * if a timer expires on a reassembly
1167  * queue, discard it.
1168  */
1169 void
1170 ip_slowtimo(void)
1171 {
1172         VNET_ITERATOR_DECL(vnet_iter);
1173         struct ipq *fp;
1174         int i;
1175
1176         IPQ_LOCK();
1177         VNET_LIST_RLOCK();
1178         VNET_FOREACH(vnet_iter) {
1179                 CURVNET_SET(vnet_iter);
1180                 INIT_VNET_INET(vnet_iter);
1181                 for (i = 0; i < IPREASS_NHASH; i++) {
1182                         for(fp = TAILQ_FIRST(&V_ipq[i]); fp;) {
1183                                 struct ipq *fpp;
1184
1185                                 fpp = fp;
1186                                 fp = TAILQ_NEXT(fp, ipq_list);
1187                                 if(--fpp->ipq_ttl == 0) {
1188                                         IPSTAT_ADD(ips_fragtimeout,
1189                                             fpp->ipq_nfrags);
1190                                         ip_freef(&V_ipq[i], fpp);
1191                                 }
1192                         }
1193                 }
1194                 /*
1195                  * If we are over the maximum number of fragments
1196                  * (due to the limit being lowered), drain off
1197                  * enough to get down to the new limit.
1198                  */
1199                 if (V_maxnipq >= 0 && V_nipq > V_maxnipq) {
1200                         for (i = 0; i < IPREASS_NHASH; i++) {
1201                                 while (V_nipq > V_maxnipq &&
1202                                     !TAILQ_EMPTY(&V_ipq[i])) {
1203                                         IPSTAT_ADD(ips_fragdropped,
1204                                             TAILQ_FIRST(&V_ipq[i])->ipq_nfrags);
1205                                         ip_freef(&V_ipq[i],
1206                                             TAILQ_FIRST(&V_ipq[i]));
1207                                 }
1208                         }
1209                 }
1210                 CURVNET_RESTORE();
1211         }
1212         VNET_LIST_RUNLOCK();
1213         IPQ_UNLOCK();
1214 }
1215
1216 /*
1217  * Drain off all datagram fragments.
1218  */
1219 void
1220 ip_drain(void)
1221 {
1222         VNET_ITERATOR_DECL(vnet_iter);
1223         int     i;
1224
1225         IPQ_LOCK();
1226         VNET_LIST_RLOCK();
1227         VNET_FOREACH(vnet_iter) {
1228                 CURVNET_SET(vnet_iter);
1229                 INIT_VNET_INET(vnet_iter);
1230                 for (i = 0; i < IPREASS_NHASH; i++) {
1231                         while(!TAILQ_EMPTY(&V_ipq[i])) {
1232                                 IPSTAT_ADD(ips_fragdropped,
1233                                     TAILQ_FIRST(&V_ipq[i])->ipq_nfrags);
1234                                 ip_freef(&V_ipq[i], TAILQ_FIRST(&V_ipq[i]));
1235                         }
1236                 }
1237                 CURVNET_RESTORE();
1238         }
1239         VNET_LIST_RUNLOCK();
1240         IPQ_UNLOCK();
1241         in_rtqdrain();
1242 }
1243
1244 /*
1245  * The protocol to be inserted into ip_protox[] must be already registered
1246  * in inetsw[], either statically or through pf_proto_register().
1247  */
1248 int
1249 ipproto_register(u_char ipproto)
1250 {
1251         struct protosw *pr;
1252
1253         /* Sanity checks. */
1254         if (ipproto == 0)
1255                 return (EPROTONOSUPPORT);
1256
1257         /*
1258          * The protocol slot must not be occupied by another protocol
1259          * already.  An index pointing to IPPROTO_RAW is unused.
1260          */
1261         pr = pffindproto(PF_INET, IPPROTO_RAW, SOCK_RAW);
1262         if (pr == NULL)
1263                 return (EPFNOSUPPORT);
1264         if (ip_protox[ipproto] != pr - inetsw)  /* IPPROTO_RAW */
1265                 return (EEXIST);
1266
1267         /* Find the protocol position in inetsw[] and set the index. */
1268         for (pr = inetdomain.dom_protosw;
1269              pr < inetdomain.dom_protoswNPROTOSW; pr++) {
1270                 if (pr->pr_domain->dom_family == PF_INET &&
1271                     pr->pr_protocol && pr->pr_protocol == ipproto) {
1272                         /* Be careful to only index valid IP protocols. */
1273                         if (pr->pr_protocol < IPPROTO_MAX) {
1274                                 ip_protox[pr->pr_protocol] = pr - inetsw;
1275                                 return (0);
1276                         } else
1277                                 return (EINVAL);
1278                 }
1279         }
1280         return (EPROTONOSUPPORT);
1281 }
1282
1283 int
1284 ipproto_unregister(u_char ipproto)
1285 {
1286         struct protosw *pr;
1287
1288         /* Sanity checks. */
1289         if (ipproto == 0)
1290                 return (EPROTONOSUPPORT);
1291
1292         /* Check if the protocol was indeed registered. */
1293         pr = pffindproto(PF_INET, IPPROTO_RAW, SOCK_RAW);
1294         if (pr == NULL)
1295                 return (EPFNOSUPPORT);
1296         if (ip_protox[ipproto] == pr - inetsw)  /* IPPROTO_RAW */
1297                 return (ENOENT);
1298
1299         /* Reset the protocol slot to IPPROTO_RAW. */
1300         ip_protox[ipproto] = pr - inetsw;
1301         return (0);
1302 }
1303
1304 /*
1305  * Given address of next destination (final or next hop),
1306  * return internet address info of interface to be used to get there.
1307  */
1308 struct in_ifaddr *
1309 ip_rtaddr(struct in_addr dst, u_int fibnum)
1310 {
1311         struct route sro;
1312         struct sockaddr_in *sin;
1313         struct in_ifaddr *ifa;
1314
1315         bzero(&sro, sizeof(sro));
1316         sin = (struct sockaddr_in *)&sro.ro_dst;
1317         sin->sin_family = AF_INET;
1318         sin->sin_len = sizeof(*sin);
1319         sin->sin_addr = dst;
1320         in_rtalloc_ign(&sro, 0, fibnum);
1321
1322         if (sro.ro_rt == NULL)
1323                 return (NULL);
1324
1325         ifa = ifatoia(sro.ro_rt->rt_ifa);
1326         RTFREE(sro.ro_rt);
1327         return (ifa);
1328 }
1329
1330 u_char inetctlerrmap[PRC_NCMDS] = {
1331         0,              0,              0,              0,
1332         0,              EMSGSIZE,       EHOSTDOWN,      EHOSTUNREACH,
1333         EHOSTUNREACH,   EHOSTUNREACH,   ECONNREFUSED,   ECONNREFUSED,
1334         EMSGSIZE,       EHOSTUNREACH,   0,              0,
1335         0,              0,              EHOSTUNREACH,   0,
1336         ENOPROTOOPT,    ECONNREFUSED
1337 };
1338
1339 /*
1340  * Forward a packet.  If some error occurs return the sender
1341  * an icmp packet.  Note we can't always generate a meaningful
1342  * icmp message because icmp doesn't have a large enough repertoire
1343  * of codes and types.
1344  *
1345  * If not forwarding, just drop the packet.  This could be confusing
1346  * if ipforwarding was zero but some routing protocol was advancing
1347  * us as a gateway to somewhere.  However, we must let the routing
1348  * protocol deal with that.
1349  *
1350  * The srcrt parameter indicates whether the packet is being forwarded
1351  * via a source route.
1352  */
1353 void
1354 ip_forward(struct mbuf *m, int srcrt)
1355 {
1356         INIT_VNET_INET(curvnet);
1357         struct ip *ip = mtod(m, struct ip *);
1358         struct in_ifaddr *ia = NULL;
1359         struct mbuf *mcopy;
1360         struct in_addr dest;
1361         struct route ro;
1362         int error, type = 0, code = 0, mtu = 0;
1363
1364         if (m->m_flags & (M_BCAST|M_MCAST) || in_canforward(ip->ip_dst) == 0) {
1365                 IPSTAT_INC(ips_cantforward);
1366                 m_freem(m);
1367                 return;
1368         }
1369 #ifdef IPSTEALTH
1370         if (!V_ipstealth) {
1371 #endif
1372                 if (ip->ip_ttl <= IPTTLDEC) {
1373                         icmp_error(m, ICMP_TIMXCEED, ICMP_TIMXCEED_INTRANS,
1374                             0, 0);
1375                         return;
1376                 }
1377 #ifdef IPSTEALTH
1378         }
1379 #endif
1380
1381         ia = ip_rtaddr(ip->ip_dst, M_GETFIB(m));
1382         if (!srcrt && ia == NULL) {
1383                 icmp_error(m, ICMP_UNREACH, ICMP_UNREACH_HOST, 0, 0);
1384                 return;
1385         }
1386
1387         /*
1388          * Save the IP header and at most 8 bytes of the payload,
1389          * in case we need to generate an ICMP message to the src.
1390          *
1391          * XXX this can be optimized a lot by saving the data in a local
1392          * buffer on the stack (72 bytes at most), and only allocating the
1393          * mbuf if really necessary. The vast majority of the packets
1394          * are forwarded without having to send an ICMP back (either
1395          * because unnecessary, or because rate limited), so we are
1396          * really we are wasting a lot of work here.
1397          *
1398          * We don't use m_copy() because it might return a reference
1399          * to a shared cluster. Both this function and ip_output()
1400          * assume exclusive access to the IP header in `m', so any
1401          * data in a cluster may change before we reach icmp_error().
1402          */
1403         MGETHDR(mcopy, M_DONTWAIT, m->m_type);
1404         if (mcopy != NULL && !m_dup_pkthdr(mcopy, m, M_DONTWAIT)) {
1405                 /*
1406                  * It's probably ok if the pkthdr dup fails (because
1407                  * the deep copy of the tag chain failed), but for now
1408                  * be conservative and just discard the copy since
1409                  * code below may some day want the tags.
1410                  */
1411                 m_free(mcopy);
1412                 mcopy = NULL;
1413         }
1414         if (mcopy != NULL) {
1415                 mcopy->m_len = min(ip->ip_len, M_TRAILINGSPACE(mcopy));
1416                 mcopy->m_pkthdr.len = mcopy->m_len;
1417                 m_copydata(m, 0, mcopy->m_len, mtod(mcopy, caddr_t));
1418         }
1419
1420 #ifdef IPSTEALTH
1421         if (!V_ipstealth) {
1422 #endif
1423                 ip->ip_ttl -= IPTTLDEC;
1424 #ifdef IPSTEALTH
1425         }
1426 #endif
1427
1428         /*
1429          * If forwarding packet using same interface that it came in on,
1430          * perhaps should send a redirect to sender to shortcut a hop.
1431          * Only send redirect if source is sending directly to us,
1432          * and if packet was not source routed (or has any options).
1433          * Also, don't send redirect if forwarding using a default route
1434          * or a route modified by a redirect.
1435          */
1436         dest.s_addr = 0;
1437         if (!srcrt && V_ipsendredirects && ia->ia_ifp == m->m_pkthdr.rcvif) {
1438                 struct sockaddr_in *sin;
1439                 struct rtentry *rt;
1440
1441                 bzero(&ro, sizeof(ro));
1442                 sin = (struct sockaddr_in *)&ro.ro_dst;
1443                 sin->sin_family = AF_INET;
1444                 sin->sin_len = sizeof(*sin);
1445                 sin->sin_addr = ip->ip_dst;
1446                 in_rtalloc_ign(&ro, 0, M_GETFIB(m));
1447
1448                 rt = ro.ro_rt;
1449
1450                 if (rt && (rt->rt_flags & (RTF_DYNAMIC|RTF_MODIFIED)) == 0 &&
1451                     satosin(rt_key(rt))->sin_addr.s_addr != 0) {
1452 #define RTA(rt) ((struct in_ifaddr *)(rt->rt_ifa))
1453                         u_long src = ntohl(ip->ip_src.s_addr);
1454
1455                         if (RTA(rt) &&
1456                             (src & RTA(rt)->ia_subnetmask) == RTA(rt)->ia_subnet) {
1457                                 if (rt->rt_flags & RTF_GATEWAY)
1458                                         dest.s_addr = satosin(rt->rt_gateway)->sin_addr.s_addr;
1459                                 else
1460                                         dest.s_addr = ip->ip_dst.s_addr;
1461                                 /* Router requirements says to only send host redirects */
1462                                 type = ICMP_REDIRECT;
1463                                 code = ICMP_REDIRECT_HOST;
1464                         }
1465                 }
1466                 if (rt)
1467                         RTFREE(rt);
1468         }
1469
1470         /*
1471          * Try to cache the route MTU from ip_output so we can consider it for
1472          * the ICMP_UNREACH_NEEDFRAG "Next-Hop MTU" field described in RFC1191.
1473          */
1474         bzero(&ro, sizeof(ro));
1475
1476         error = ip_output(m, NULL, &ro, IP_FORWARDING, NULL, NULL);
1477
1478         if (error == EMSGSIZE && ro.ro_rt)
1479                 mtu = ro.ro_rt->rt_rmx.rmx_mtu;
1480         if (ro.ro_rt)
1481                 RTFREE(ro.ro_rt);
1482
1483         if (error)
1484                 IPSTAT_INC(ips_cantforward);
1485         else {
1486                 IPSTAT_INC(ips_forward);
1487                 if (type)
1488                         IPSTAT_INC(ips_redirectsent);
1489                 else {
1490                         if (mcopy)
1491                                 m_freem(mcopy);
1492                         return;
1493                 }
1494         }
1495         if (mcopy == NULL)
1496                 return;
1497
1498         switch (error) {
1499
1500         case 0:                         /* forwarded, but need redirect */
1501                 /* type, code set above */
1502                 break;
1503
1504         case ENETUNREACH:               /* shouldn't happen, checked above */
1505         case EHOSTUNREACH:
1506         case ENETDOWN:
1507         case EHOSTDOWN:
1508         default:
1509                 type = ICMP_UNREACH;
1510                 code = ICMP_UNREACH_HOST;
1511                 break;
1512
1513         case EMSGSIZE:
1514                 type = ICMP_UNREACH;
1515                 code = ICMP_UNREACH_NEEDFRAG;
1516
1517 #ifdef IPSEC
1518                 /* 
1519                  * If IPsec is configured for this path,
1520                  * override any possibly mtu value set by ip_output.
1521                  */ 
1522                 mtu = ip_ipsec_mtu(m, mtu);
1523 #endif /* IPSEC */
1524                 /*
1525                  * If the MTU was set before make sure we are below the
1526                  * interface MTU.
1527                  * If the MTU wasn't set before use the interface mtu or
1528                  * fall back to the next smaller mtu step compared to the
1529                  * current packet size.
1530                  */
1531                 if (mtu != 0) {
1532                         if (ia != NULL)
1533                                 mtu = min(mtu, ia->ia_ifp->if_mtu);
1534                 } else {
1535                         if (ia != NULL)
1536                                 mtu = ia->ia_ifp->if_mtu;
1537                         else
1538                                 mtu = ip_next_mtu(ip->ip_len, 0);
1539                 }
1540                 IPSTAT_INC(ips_cantfrag);
1541                 break;
1542
1543         case ENOBUFS:
1544                 /*
1545                  * A router should not generate ICMP_SOURCEQUENCH as
1546                  * required in RFC1812 Requirements for IP Version 4 Routers.
1547                  * Source quench could be a big problem under DoS attacks,
1548                  * or if the underlying interface is rate-limited.
1549                  * Those who need source quench packets may re-enable them
1550                  * via the net.inet.ip.sendsourcequench sysctl.
1551                  */
1552                 if (V_ip_sendsourcequench == 0) {
1553                         m_freem(mcopy);
1554                         return;
1555                 } else {
1556                         type = ICMP_SOURCEQUENCH;
1557                         code = 0;
1558                 }
1559                 break;
1560
1561         case EACCES:                    /* ipfw denied packet */
1562                 m_freem(mcopy);
1563                 return;
1564         }
1565         icmp_error(mcopy, type, code, dest.s_addr, mtu);
1566 }
1567
1568 void
1569 ip_savecontrol(struct inpcb *inp, struct mbuf **mp, struct ip *ip,
1570     struct mbuf *m)
1571 {
1572         INIT_VNET_NET(inp->inp_vnet);
1573
1574         if (inp->inp_socket->so_options & (SO_BINTIME | SO_TIMESTAMP)) {
1575                 struct bintime bt;
1576
1577                 bintime(&bt);
1578                 if (inp->inp_socket->so_options & SO_BINTIME) {
1579                         *mp = sbcreatecontrol((caddr_t) &bt, sizeof(bt),
1580                         SCM_BINTIME, SOL_SOCKET);
1581                         if (*mp)
1582                                 mp = &(*mp)->m_next;
1583                 }
1584                 if (inp->inp_socket->so_options & SO_TIMESTAMP) {
1585                         struct timeval tv;
1586
1587                         bintime2timeval(&bt, &tv);
1588                         *mp = sbcreatecontrol((caddr_t) &tv, sizeof(tv),
1589                                 SCM_TIMESTAMP, SOL_SOCKET);
1590                         if (*mp)
1591                                 mp = &(*mp)->m_next;
1592                 }
1593         }
1594         if (inp->inp_flags & INP_RECVDSTADDR) {
1595                 *mp = sbcreatecontrol((caddr_t) &ip->ip_dst,
1596                     sizeof(struct in_addr), IP_RECVDSTADDR, IPPROTO_IP);
1597                 if (*mp)
1598                         mp = &(*mp)->m_next;
1599         }
1600         if (inp->inp_flags & INP_RECVTTL) {
1601                 *mp = sbcreatecontrol((caddr_t) &ip->ip_ttl,
1602                     sizeof(u_char), IP_RECVTTL, IPPROTO_IP);
1603                 if (*mp)
1604                         mp = &(*mp)->m_next;
1605         }
1606 #ifdef notyet
1607         /* XXX
1608          * Moving these out of udp_input() made them even more broken
1609          * than they already were.
1610          */
1611         /* options were tossed already */
1612         if (inp->inp_flags & INP_RECVOPTS) {
1613                 *mp = sbcreatecontrol((caddr_t) opts_deleted_above,
1614                     sizeof(struct in_addr), IP_RECVOPTS, IPPROTO_IP);
1615                 if (*mp)
1616                         mp = &(*mp)->m_next;
1617         }
1618         /* ip_srcroute doesn't do what we want here, need to fix */
1619         if (inp->inp_flags & INP_RECVRETOPTS) {
1620                 *mp = sbcreatecontrol((caddr_t) ip_srcroute(m),
1621                     sizeof(struct in_addr), IP_RECVRETOPTS, IPPROTO_IP);
1622                 if (*mp)
1623                         mp = &(*mp)->m_next;
1624         }
1625 #endif
1626         if (inp->inp_flags & INP_RECVIF) {
1627                 struct ifnet *ifp;
1628                 struct sdlbuf {
1629                         struct sockaddr_dl sdl;
1630                         u_char  pad[32];
1631                 } sdlbuf;
1632                 struct sockaddr_dl *sdp;
1633                 struct sockaddr_dl *sdl2 = &sdlbuf.sdl;
1634
1635                 if (((ifp = m->m_pkthdr.rcvif)) 
1636                 && ( ifp->if_index && (ifp->if_index <= V_if_index))) {
1637                         sdp = (struct sockaddr_dl *)ifp->if_addr->ifa_addr;
1638                         /*
1639                          * Change our mind and don't try copy.
1640                          */
1641                         if ((sdp->sdl_family != AF_LINK)
1642                         || (sdp->sdl_len > sizeof(sdlbuf))) {
1643                                 goto makedummy;
1644                         }
1645                         bcopy(sdp, sdl2, sdp->sdl_len);
1646                 } else {
1647 makedummy:      
1648                         sdl2->sdl_len
1649                                 = offsetof(struct sockaddr_dl, sdl_data[0]);
1650                         sdl2->sdl_family = AF_LINK;
1651                         sdl2->sdl_index = 0;
1652                         sdl2->sdl_nlen = sdl2->sdl_alen = sdl2->sdl_slen = 0;
1653                 }
1654                 *mp = sbcreatecontrol((caddr_t) sdl2, sdl2->sdl_len,
1655                         IP_RECVIF, IPPROTO_IP);
1656                 if (*mp)
1657                         mp = &(*mp)->m_next;
1658         }
1659 }
1660
1661 /*
1662  * XXXRW: Multicast routing code in ip_mroute.c is generally MPSAFE, but the
1663  * ip_rsvp and ip_rsvp_on variables need to be interlocked with rsvp_on
1664  * locking.  This code remains in ip_input.c as ip_mroute.c is optionally
1665  * compiled.
1666  */
1667 int
1668 ip_rsvp_init(struct socket *so)
1669 {
1670         INIT_VNET_INET(so->so_vnet);
1671
1672         if (so->so_type != SOCK_RAW ||
1673             so->so_proto->pr_protocol != IPPROTO_RSVP)
1674                 return EOPNOTSUPP;
1675
1676         if (V_ip_rsvpd != NULL)
1677                 return EADDRINUSE;
1678
1679         V_ip_rsvpd = so;
1680         /*
1681          * This may seem silly, but we need to be sure we don't over-increment
1682          * the RSVP counter, in case something slips up.
1683          */
1684         if (!V_ip_rsvp_on) {
1685                 V_ip_rsvp_on = 1;
1686                 V_rsvp_on++;
1687         }
1688
1689         return 0;
1690 }
1691
1692 int
1693 ip_rsvp_done(void)
1694 {
1695         INIT_VNET_INET(curvnet);
1696
1697         V_ip_rsvpd = NULL;
1698         /*
1699          * This may seem silly, but we need to be sure we don't over-decrement
1700          * the RSVP counter, in case something slips up.
1701          */
1702         if (V_ip_rsvp_on) {
1703                 V_ip_rsvp_on = 0;
1704                 V_rsvp_on--;
1705         }
1706         return 0;
1707 }
1708
1709 void
1710 rsvp_input(struct mbuf *m, int off)     /* XXX must fixup manually */
1711 {
1712         INIT_VNET_INET(curvnet);
1713
1714         if (rsvp_input_p) { /* call the real one if loaded */
1715                 rsvp_input_p(m, off);
1716                 return;
1717         }
1718
1719         /* Can still get packets with rsvp_on = 0 if there is a local member
1720          * of the group to which the RSVP packet is addressed.  But in this
1721          * case we want to throw the packet away.
1722          */
1723         
1724         if (!V_rsvp_on) {
1725                 m_freem(m);
1726                 return;
1727         }
1728
1729         if (V_ip_rsvpd != NULL) { 
1730                 rip_input(m, off);
1731                 return;
1732         }
1733         /* Drop the packet */
1734         m_freem(m);
1735 }