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