ip_input.c revision 1.370
1/*	$NetBSD: ip_input.c,v 1.370 2018/02/05 14:52:42 maxv Exp $	*/
2
3/*
4 * Copyright (C) 1995, 1996, 1997, and 1998 WIDE Project.
5 * All rights reserved.
6 *
7 * Redistribution and use in source and binary forms, with or without
8 * modification, are permitted provided that the following conditions
9 * are met:
10 * 1. Redistributions of source code must retain the above copyright
11 *    notice, this list of conditions and the following disclaimer.
12 * 2. Redistributions in binary form must reproduce the above copyright
13 *    notice, this list of conditions and the following disclaimer in the
14 *    documentation and/or other materials provided with the distribution.
15 * 3. Neither the name of the project nor the names of its contributors
16 *    may be used to endorse or promote products derived from this software
17 *    without specific prior written permission.
18 *
19 * THIS SOFTWARE IS PROVIDED BY THE PROJECT AND CONTRIBUTORS ``AS IS'' AND
20 * ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
21 * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE
22 * ARE DISCLAIMED.  IN NO EVENT SHALL THE PROJECT OR CONTRIBUTORS BE LIABLE
23 * FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL
24 * DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS
25 * OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION)
26 * HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT
27 * LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY
28 * OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF
29 * SUCH DAMAGE.
30 */
31
32/*
33 * Copyright (c) 1998 The NetBSD Foundation, Inc.
34 * All rights reserved.
35 *
36 * This code is derived from software contributed to The NetBSD Foundation
37 * by Public Access Networks Corporation ("Panix").  It was developed under
38 * contract to Panix by Eric Haszlakiewicz and Thor Lancelot Simon.
39 *
40 * Redistribution and use in source and binary forms, with or without
41 * modification, are permitted provided that the following conditions
42 * are met:
43 * 1. Redistributions of source code must retain the above copyright
44 *    notice, this list of conditions and the following disclaimer.
45 * 2. Redistributions in binary form must reproduce the above copyright
46 *    notice, this list of conditions and the following disclaimer in the
47 *    documentation and/or other materials provided with the distribution.
48 *
49 * THIS SOFTWARE IS PROVIDED BY THE NETBSD FOUNDATION, INC. AND CONTRIBUTORS
50 * ``AS IS'' AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED
51 * TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR
52 * PURPOSE ARE DISCLAIMED.  IN NO EVENT SHALL THE FOUNDATION OR CONTRIBUTORS
53 * BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR
54 * CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF
55 * SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS
56 * INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN
57 * CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE)
58 * ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE
59 * POSSIBILITY OF SUCH DAMAGE.
60 */
61
62/*
63 * Copyright (c) 1982, 1986, 1988, 1993
64 *	The Regents of the University of California.  All rights reserved.
65 *
66 * Redistribution and use in source and binary forms, with or without
67 * modification, are permitted provided that the following conditions
68 * are met:
69 * 1. Redistributions of source code must retain the above copyright
70 *    notice, this list of conditions and the following disclaimer.
71 * 2. Redistributions in binary form must reproduce the above copyright
72 *    notice, this list of conditions and the following disclaimer in the
73 *    documentation and/or other materials provided with the distribution.
74 * 3. Neither the name of the University nor the names of its contributors
75 *    may be used to endorse or promote products derived from this software
76 *    without specific prior written permission.
77 *
78 * THIS SOFTWARE IS PROVIDED BY THE REGENTS AND CONTRIBUTORS ``AS IS'' AND
79 * ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
80 * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE
81 * ARE DISCLAIMED.  IN NO EVENT SHALL THE REGENTS OR CONTRIBUTORS BE LIABLE
82 * FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL
83 * DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS
84 * OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION)
85 * HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT
86 * LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY
87 * OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF
88 * SUCH DAMAGE.
89 *
90 *	@(#)ip_input.c	8.2 (Berkeley) 1/4/94
91 */
92
93#include <sys/cdefs.h>
94__KERNEL_RCSID(0, "$NetBSD: ip_input.c,v 1.370 2018/02/05 14:52:42 maxv Exp $");
95
96#ifdef _KERNEL_OPT
97#include "opt_inet.h"
98#include "opt_gateway.h"
99#include "opt_ipsec.h"
100#include "opt_mrouting.h"
101#include "opt_mbuftrace.h"
102#include "opt_inet_csum.h"
103#include "opt_net_mpsafe.h"
104#endif
105
106#include "arp.h"
107
108#include <sys/param.h>
109#include <sys/systm.h>
110#include <sys/cpu.h>
111#include <sys/mbuf.h>
112#include <sys/domain.h>
113#include <sys/protosw.h>
114#include <sys/socket.h>
115#include <sys/socketvar.h>
116#include <sys/errno.h>
117#include <sys/time.h>
118#include <sys/kernel.h>
119#include <sys/pool.h>
120#include <sys/sysctl.h>
121#include <sys/kauth.h>
122
123#include <net/if.h>
124#include <net/if_dl.h>
125#include <net/route.h>
126#include <net/pktqueue.h>
127#include <net/pfil.h>
128
129#include <netinet/in.h>
130#include <netinet/in_systm.h>
131#include <netinet/ip.h>
132#include <netinet/in_pcb.h>
133#include <netinet/in_proto.h>
134#include <netinet/in_var.h>
135#include <netinet/ip_var.h>
136#include <netinet/ip_private.h>
137#include <netinet/ip_icmp.h>
138/* just for gif_ttl */
139#include <netinet/in_gif.h>
140#include "gif.h"
141#include <net/if_gre.h>
142#include "gre.h"
143
144#ifdef MROUTING
145#include <netinet/ip_mroute.h>
146#endif
147#include <netinet/portalgo.h>
148
149#ifdef IPSEC
150#include <netipsec/ipsec.h>
151#endif
152
153#ifndef	IPFORWARDING
154#ifdef GATEWAY
155#define	IPFORWARDING	1	/* forward IP packets not for us */
156#else
157#define	IPFORWARDING	0	/* don't forward IP packets not for us */
158#endif
159#endif
160
161#ifndef	IPSENDREDIRECTS
162#define	IPSENDREDIRECTS	1
163#endif
164
165#ifndef IPMTUDISCTIMEOUT
166#define IPMTUDISCTIMEOUT (10 * 60)	/* as per RFC 1191 */
167#endif
168
169#ifdef DIRECTED_BROADCAST
170#define IPDIRECTEDBCAST	1
171#else
172#define	IPDIRECTEDBCAST	0
173#endif
174
175int ipforwarding = IPFORWARDING;
176int ipsendredirects = IPSENDREDIRECTS;
177int ip_defttl = IPDEFTTL;
178int ip_forwsrcrt = 0;
179int ip_directedbcast = IPDIRECTEDBCAST;
180int ip_allowsrcrt = 0;
181int ip_mtudisc = 1;
182int ip_mtudisc_timeout = IPMTUDISCTIMEOUT;
183int ip_do_randomid = 0;
184
185/*
186 * XXX - Setting ip_checkinterface mostly implements the receive side of
187 * the Strong ES model described in RFC 1122, but since the routing table
188 * and transmit implementation do not implement the Strong ES model,
189 * setting this to 1 results in an odd hybrid.
190 *
191 * XXX - ip_checkinterface currently must be disabled if you use ipnat
192 * to translate the destination address to another local interface.
193 *
194 * XXX - ip_checkinterface must be disabled if you add IP aliases
195 * to the loopback interface instead of the interface where the
196 * packets for those addresses are received.
197 */
198static int		ip_checkinterface	__read_mostly = 0;
199
200struct rttimer_queue *ip_mtudisc_timeout_q = NULL;
201
202pktqueue_t *		ip_pktq			__read_mostly;
203pfil_head_t *		inet_pfil_hook		__read_mostly;
204ipid_state_t *		ip_ids			__read_mostly;
205percpu_t *		ipstat_percpu		__read_mostly;
206
207static percpu_t		*ipforward_rt_percpu	__cacheline_aligned;
208
209uint16_t ip_id;
210
211#ifdef INET_CSUM_COUNTERS
212#include <sys/device.h>
213
214struct evcnt ip_hwcsum_bad = EVCNT_INITIALIZER(EVCNT_TYPE_MISC,
215    NULL, "inet", "hwcsum bad");
216struct evcnt ip_hwcsum_ok = EVCNT_INITIALIZER(EVCNT_TYPE_MISC,
217    NULL, "inet", "hwcsum ok");
218struct evcnt ip_swcsum = EVCNT_INITIALIZER(EVCNT_TYPE_MISC,
219    NULL, "inet", "swcsum");
220
221#define	INET_CSUM_COUNTER_INCR(ev)	(ev)->ev_count++
222
223EVCNT_ATTACH_STATIC(ip_hwcsum_bad);
224EVCNT_ATTACH_STATIC(ip_hwcsum_ok);
225EVCNT_ATTACH_STATIC(ip_swcsum);
226
227#else
228
229#define	INET_CSUM_COUNTER_INCR(ev)	/* nothing */
230
231#endif /* INET_CSUM_COUNTERS */
232
233/*
234 * Used to save the IP options in case a protocol wants to respond
235 * to an incoming packet over the same route if the packet got here
236 * using IP source routing.  This allows connection establishment and
237 * maintenance when the remote end is on a network that is not known
238 * to us.
239 */
240struct ip_srcrt {
241	int		isr_nhops;		   /* number of hops */
242	struct in_addr	isr_dst;		   /* final destination */
243	char		isr_nop;		   /* one NOP to align */
244	char		isr_hdr[IPOPT_OFFSET + 1]; /* OPTVAL, OLEN & OFFSET */
245	struct in_addr	isr_routes[MAX_IPOPTLEN/sizeof(struct in_addr)];
246};
247
248static int ip_drainwanted;
249
250static void save_rte(struct mbuf *, u_char *, struct in_addr);
251
252#ifdef MBUFTRACE
253struct mowner ip_rx_mowner = MOWNER_INIT("internet", "rx");
254struct mowner ip_tx_mowner = MOWNER_INIT("internet", "tx");
255#endif
256
257static void		ipintr(void *);
258static void		ip_input(struct mbuf *);
259static void		ip_forward(struct mbuf *, int, struct ifnet *);
260static bool		ip_dooptions(struct mbuf *);
261static struct in_ifaddr *ip_rtaddr(struct in_addr, struct psref *);
262static void		sysctl_net_inet_ip_setup(struct sysctllog **);
263
264static struct in_ifaddr	*ip_match_our_address(struct ifnet *, struct ip *,
265			    int *);
266static struct in_ifaddr	*ip_match_our_address_broadcast(struct ifnet *,
267			    struct ip *);
268
269#ifdef NET_MPSAFE
270#define	SOFTNET_LOCK()		mutex_enter(softnet_lock)
271#define	SOFTNET_UNLOCK()	mutex_exit(softnet_lock)
272#else
273#define	SOFTNET_LOCK()		KASSERT(mutex_owned(softnet_lock))
274#define	SOFTNET_UNLOCK()	KASSERT(mutex_owned(softnet_lock))
275#endif
276
277/*
278 * IP initialization: fill in IP protocol switch table.
279 * All protocols not implemented in kernel go to raw IP protocol handler.
280 */
281void
282ip_init(void)
283{
284	const struct protosw *pr;
285
286	in_init();
287	sysctl_net_inet_ip_setup(NULL);
288
289	pr = pffindproto(PF_INET, IPPROTO_RAW, SOCK_RAW);
290	KASSERT(pr != NULL);
291
292	ip_pktq = pktq_create(IFQ_MAXLEN, ipintr, NULL);
293	KASSERT(ip_pktq != NULL);
294
295	for (u_int i = 0; i < IPPROTO_MAX; i++) {
296		ip_protox[i] = pr - inetsw;
297	}
298	for (pr = inetdomain.dom_protosw;
299	    pr < inetdomain.dom_protoswNPROTOSW; pr++)
300		if (pr->pr_domain->dom_family == PF_INET &&
301		    pr->pr_protocol && pr->pr_protocol != IPPROTO_RAW)
302			ip_protox[pr->pr_protocol] = pr - inetsw;
303
304	ip_reass_init();
305
306	ip_ids = ip_id_init();
307	ip_id = time_uptime & 0xfffff;
308
309#ifdef GATEWAY
310	ipflow_init();
311#endif
312
313	/* Register our Packet Filter hook. */
314	inet_pfil_hook = pfil_head_create(PFIL_TYPE_AF, (void *)AF_INET);
315	KASSERT(inet_pfil_hook != NULL);
316
317#ifdef MBUFTRACE
318	MOWNER_ATTACH(&ip_tx_mowner);
319	MOWNER_ATTACH(&ip_rx_mowner);
320#endif /* MBUFTRACE */
321
322	ipstat_percpu = percpu_alloc(sizeof(uint64_t) * IP_NSTATS);
323	ipforward_rt_percpu = percpu_alloc(sizeof(struct route));
324	ip_mtudisc_timeout_q = rt_timer_queue_create(ip_mtudisc_timeout);
325}
326
327static struct in_ifaddr *
328ip_match_our_address(struct ifnet *ifp, struct ip *ip, int *downmatch)
329{
330	struct in_ifaddr *ia = NULL;
331	int checkif;
332
333	/*
334	 * Enable a consistency check between the destination address
335	 * and the arrival interface for a unicast packet (the RFC 1122
336	 * strong ES model) if IP forwarding is disabled and the packet
337	 * is not locally generated.
338	 *
339	 * XXX - Checking also should be disabled if the destination
340	 * address is ipnat'ed to a different interface.
341	 *
342	 * XXX - Checking is incompatible with IP aliases added
343	 * to the loopback interface instead of the interface where
344	 * the packets are received.
345	 *
346	 * XXX - We need to add a per ifaddr flag for this so that
347	 * we get finer grain control.
348	 */
349	checkif = ip_checkinterface && (ipforwarding == 0) &&
350	    (ifp->if_flags & IFF_LOOPBACK) == 0;
351
352	IN_ADDRHASH_READER_FOREACH(ia, ip->ip_dst.s_addr) {
353		if (in_hosteq(ia->ia_addr.sin_addr, ip->ip_dst)) {
354			if (ia->ia4_flags & IN_IFF_NOTREADY)
355				continue;
356			if (checkif && ia->ia_ifp != ifp)
357				continue;
358			if ((ia->ia_ifp->if_flags & IFF_UP) == 0) {
359				(*downmatch)++;
360				continue;
361			}
362			if (ia->ia4_flags & IN_IFF_DETACHED &&
363			    (ifp->if_flags & IFF_LOOPBACK) == 0)
364				continue;
365			break;
366		}
367	}
368
369	return ia;
370}
371
372static struct in_ifaddr *
373ip_match_our_address_broadcast(struct ifnet *ifp, struct ip *ip)
374{
375	struct in_ifaddr *ia = NULL;
376	struct ifaddr *ifa;
377
378	IFADDR_READER_FOREACH(ifa, ifp) {
379		if (ifa->ifa_addr->sa_family != AF_INET)
380			continue;
381		ia = ifatoia(ifa);
382		if (ia->ia4_flags & IN_IFF_NOTREADY)
383			continue;
384		if (ia->ia4_flags & IN_IFF_DETACHED &&
385		    (ifp->if_flags & IFF_LOOPBACK) == 0)
386			continue;
387		if (in_hosteq(ip->ip_dst, ia->ia_broadaddr.sin_addr) ||
388		    in_hosteq(ip->ip_dst, ia->ia_netbroadcast) ||
389		    /*
390		     * Look for all-0's host part (old broadcast addr),
391		     * either for subnet or net.
392		     */
393		    ip->ip_dst.s_addr == ia->ia_subnet ||
394		    ip->ip_dst.s_addr == ia->ia_net)
395			goto matched;
396		/*
397		 * An interface with IP address zero accepts
398		 * all packets that arrive on that interface.
399		 */
400		if (in_nullhost(ia->ia_addr.sin_addr))
401			goto matched;
402	}
403	ia = NULL;
404
405matched:
406	return ia;
407}
408
409/*
410 * IP software interrupt routine.
411 */
412static void
413ipintr(void *arg __unused)
414{
415	struct mbuf *m;
416
417	KASSERT(cpu_softintr_p());
418
419	SOFTNET_LOCK_UNLESS_NET_MPSAFE();
420	while ((m = pktq_dequeue(ip_pktq)) != NULL) {
421		ip_input(m);
422	}
423	SOFTNET_UNLOCK_UNLESS_NET_MPSAFE();
424}
425
426/*
427 * IP input routine.  Checksum and byte swap header.  If fragmented
428 * try to reassemble.  Process options.  Pass to next level.
429 */
430static void
431ip_input(struct mbuf *m)
432{
433	struct ip *ip = NULL;
434	struct in_ifaddr *ia = NULL;
435	int hlen = 0, len;
436	int downmatch;
437	int srcrt = 0;
438	ifnet_t *ifp;
439	struct psref psref;
440	int s;
441
442	KASSERTMSG(cpu_softintr_p(), "ip_input: not in the software "
443	    "interrupt handler; synchronization assumptions violated");
444
445	MCLAIM(m, &ip_rx_mowner);
446	KASSERT((m->m_flags & M_PKTHDR) != 0);
447
448	ifp = m_get_rcvif_psref(m, &psref);
449	if (__predict_false(ifp == NULL))
450		goto out;
451
452	/*
453	 * If no IP addresses have been set yet but the interfaces
454	 * are receiving, can't do anything with incoming packets yet.
455	 * Note: we pre-check without locks held.
456	 */
457	if (IN_ADDRLIST_READER_EMPTY())
458		goto out;
459	IP_STATINC(IP_STAT_TOTAL);
460
461	/*
462	 * If the IP header is not aligned, slurp it up into a new
463	 * mbuf with space for link headers, in the event we forward
464	 * it.  Otherwise, if it is aligned, make sure the entire
465	 * base IP header is in the first mbuf of the chain.
466	 */
467	if (IP_HDR_ALIGNED_P(mtod(m, void *)) == 0) {
468		if ((m = m_copyup(m, sizeof(struct ip),
469		    (max_linkhdr + 3) & ~3)) == NULL) {
470			/* XXXJRT new stat, please */
471			IP_STATINC(IP_STAT_TOOSMALL);
472			goto out;
473		}
474	} else if (__predict_false(m->m_len < sizeof(struct ip))) {
475		if ((m = m_pullup(m, sizeof(struct ip))) == NULL) {
476			IP_STATINC(IP_STAT_TOOSMALL);
477			goto out;
478		}
479	}
480	ip = mtod(m, struct ip *);
481	if (ip->ip_v != IPVERSION) {
482		IP_STATINC(IP_STAT_BADVERS);
483		goto out;
484	}
485	hlen = ip->ip_hl << 2;
486	if (hlen < sizeof(struct ip)) {	/* minimum header length */
487		IP_STATINC(IP_STAT_BADHLEN);
488		goto out;
489	}
490	if (hlen > m->m_len) {
491		if ((m = m_pullup(m, hlen)) == NULL) {
492			IP_STATINC(IP_STAT_BADHLEN);
493			goto out;
494		}
495		ip = mtod(m, struct ip *);
496	}
497
498	/*
499	 * RFC1122: packets with a multicast source address are
500	 * not allowed.
501	 */
502	if (IN_MULTICAST(ip->ip_src.s_addr)) {
503		IP_STATINC(IP_STAT_BADADDR);
504		goto out;
505	}
506
507	/* 127/8 must not appear on wire - RFC1122 */
508	if ((ntohl(ip->ip_dst.s_addr) >> IN_CLASSA_NSHIFT) == IN_LOOPBACKNET ||
509	    (ntohl(ip->ip_src.s_addr) >> IN_CLASSA_NSHIFT) == IN_LOOPBACKNET) {
510		if ((ifp->if_flags & IFF_LOOPBACK) == 0) {
511			IP_STATINC(IP_STAT_BADADDR);
512			goto out;
513		}
514	}
515
516	switch (m->m_pkthdr.csum_flags &
517		((ifp->if_csum_flags_rx & M_CSUM_IPv4) | M_CSUM_IPv4_BAD)) {
518	case M_CSUM_IPv4|M_CSUM_IPv4_BAD:
519		INET_CSUM_COUNTER_INCR(&ip_hwcsum_bad);
520		IP_STATINC(IP_STAT_BADSUM);
521		goto out;
522
523	case M_CSUM_IPv4:
524		/* Checksum was okay. */
525		INET_CSUM_COUNTER_INCR(&ip_hwcsum_ok);
526		break;
527
528	default:
529		/*
530		 * Must compute it ourselves.  Maybe skip checksum on
531		 * loopback interfaces.
532		 */
533		if (__predict_true(!(ifp->if_flags & IFF_LOOPBACK) ||
534		    ip_do_loopback_cksum)) {
535			INET_CSUM_COUNTER_INCR(&ip_swcsum);
536			if (in_cksum(m, hlen) != 0) {
537				IP_STATINC(IP_STAT_BADSUM);
538				goto out;
539			}
540		}
541		break;
542	}
543
544	/* Retrieve the packet length. */
545	len = ntohs(ip->ip_len);
546
547	/*
548	 * Check for additional length bogosity
549	 */
550	if (len < hlen) {
551		IP_STATINC(IP_STAT_BADLEN);
552		goto out;
553	}
554
555	/*
556	 * Check that the amount of data in the buffers is at least as much
557	 * as the IP header would have us expect. Trim mbufs if longer than
558	 * we expect. Drop packet if shorter than we expect.
559	 */
560	if (m->m_pkthdr.len < len) {
561		IP_STATINC(IP_STAT_TOOSHORT);
562		goto out;
563	}
564	if (m->m_pkthdr.len > len) {
565		if (m->m_len == m->m_pkthdr.len) {
566			m->m_len = len;
567			m->m_pkthdr.len = len;
568		} else
569			m_adj(m, len - m->m_pkthdr.len);
570	}
571
572	/*
573	 * Assume that we can create a fast-forward IP flow entry
574	 * based on this packet.
575	 */
576	m->m_flags |= M_CANFASTFWD;
577
578	/*
579	 * Run through list of hooks for input packets.  If there are any
580	 * filters which require that additional packets in the flow are
581	 * not fast-forwarded, they must clear the M_CANFASTFWD flag.
582	 * Note that filters must _never_ set this flag, as another filter
583	 * in the list may have previously cleared it.
584	 */
585#if defined(IPSEC)
586	if (!ipsec_used || !ipsec_indone(m))
587#else
588	if (1)
589#endif
590	{
591		struct in_addr odst = ip->ip_dst;
592		bool freed;
593
594		freed = pfil_run_hooks(inet_pfil_hook, &m, ifp, PFIL_IN) != 0;
595		if (freed || m == NULL) {
596			m = NULL;
597			goto out;
598		}
599		ip = mtod(m, struct ip *);
600		hlen = ip->ip_hl << 2;
601
602		/*
603		 * XXX The setting of "srcrt" here is to prevent ip_forward()
604		 * from generating ICMP redirects for packets that have
605		 * been redirected by a hook back out on to the same LAN that
606		 * they came from and is not an indication that the packet
607		 * is being inffluenced by source routing options.  This
608		 * allows things like
609		 * "rdr tlp0 0/0 port 80 -> 1.1.1.200 3128 tcp"
610		 * where tlp0 is both on the 1.1.1.0/24 network and is the
611		 * default route for hosts on 1.1.1.0/24.  Of course this
612		 * also requires a "map tlp0 ..." to complete the story.
613		 * One might argue whether or not this kind of network config.
614		 * should be supported in this manner...
615		 */
616		srcrt = (odst.s_addr != ip->ip_dst.s_addr);
617	}
618
619#ifdef ALTQ
620	/* XXX Temporary until ALTQ is changed to use a pfil hook */
621	if (altq_input) {
622		SOFTNET_LOCK();
623		if ((*altq_input)(m, AF_INET) == 0) {
624			/* Packet dropped by traffic conditioner. */
625			SOFTNET_UNLOCK();
626			m = NULL;
627			goto out;
628		}
629		SOFTNET_UNLOCK();
630	}
631#endif
632
633	/*
634	 * Process options and, if not destined for us,
635	 * ship it on.  ip_dooptions returns 1 when an
636	 * error was detected (causing an icmp message
637	 * to be sent and the original packet to be freed).
638	 */
639	if (hlen > sizeof(struct ip) && ip_dooptions(m)) {
640		m = NULL;
641		goto out;
642	}
643
644	/*
645	 * Check our list of addresses, to see if the packet is for us.
646	 *
647	 * Traditional 4.4BSD did not consult IFF_UP at all.
648	 * The behavior here is to treat addresses on !IFF_UP interface
649	 * or IN_IFF_NOTREADY addresses as not mine.
650	 */
651	downmatch = 0;
652	s = pserialize_read_enter();
653	ia = ip_match_our_address(ifp, ip, &downmatch);
654	if (ia != NULL) {
655		pserialize_read_exit(s);
656		goto ours;
657	}
658
659	if (ifp->if_flags & IFF_BROADCAST) {
660		ia = ip_match_our_address_broadcast(ifp, ip);
661		if (ia != NULL) {
662			pserialize_read_exit(s);
663			goto ours;
664		}
665	}
666	pserialize_read_exit(s);
667
668	if (IN_MULTICAST(ip->ip_dst.s_addr)) {
669#ifdef MROUTING
670		extern struct socket *ip_mrouter;
671
672		if (ip_mrouter) {
673			/*
674			 * If we are acting as a multicast router, all
675			 * incoming multicast packets are passed to the
676			 * kernel-level multicast forwarding function.
677			 * The packet is returned (relatively) intact; if
678			 * ip_mforward() returns a non-zero value, the packet
679			 * must be discarded, else it may be accepted below.
680			 *
681			 * (The IP ident field is put in the same byte order
682			 * as expected when ip_mforward() is called from
683			 * ip_output().)
684			 */
685			SOFTNET_LOCK();
686			if (ip_mforward(m, ifp) != 0) {
687				SOFTNET_UNLOCK();
688				IP_STATINC(IP_STAT_CANTFORWARD);
689				goto out;
690			}
691			SOFTNET_UNLOCK();
692
693			/*
694			 * The process-level routing demon needs to receive
695			 * all multicast IGMP packets, whether or not this
696			 * host belongs to their destination groups.
697			 */
698			if (ip->ip_p == IPPROTO_IGMP) {
699				goto ours;
700			}
701			IP_STATINC(IP_STAT_CANTFORWARD);
702		}
703#endif
704		/*
705		 * See if we belong to the destination multicast group on the
706		 * arrival interface.
707		 */
708		if (!in_multi_group(ip->ip_dst, ifp, 0)) {
709			IP_STATINC(IP_STAT_CANTFORWARD);
710			goto out;
711		}
712		goto ours;
713	}
714	if (ip->ip_dst.s_addr == INADDR_BROADCAST ||
715	    in_nullhost(ip->ip_dst))
716		goto ours;
717
718	/*
719	 * Not for us; forward if possible and desirable.
720	 */
721	if (ipforwarding == 0) {
722		m_put_rcvif_psref(ifp, &psref);
723		IP_STATINC(IP_STAT_CANTFORWARD);
724		m_freem(m);
725	} else {
726		/*
727		 * If ip_dst matched any of my address on !IFF_UP interface,
728		 * and there's no IFF_UP interface that matches ip_dst,
729		 * send icmp unreach.  Forwarding it will result in in-kernel
730		 * forwarding loop till TTL goes to 0.
731		 */
732		if (downmatch) {
733			m_put_rcvif_psref(ifp, &psref);
734			icmp_error(m, ICMP_UNREACH, ICMP_UNREACH_HOST, 0, 0);
735			IP_STATINC(IP_STAT_CANTFORWARD);
736			return;
737		}
738#ifdef IPSEC
739		/* Check the security policy (SP) for the packet */
740		if (ipsec_used) {
741			if (ipsec4_input(m, IP_FORWARDING |
742			    (ip_directedbcast ? IP_ALLOWBROADCAST : 0)) != 0) {
743				goto out;
744			}
745		}
746#endif
747		ip_forward(m, srcrt, ifp);
748		m_put_rcvif_psref(ifp, &psref);
749	}
750	return;
751
752ours:
753	m_put_rcvif_psref(ifp, &psref);
754	ifp = NULL;
755
756	/*
757	 * If offset or IP_MF are set, must reassemble.
758	 */
759	if (ip->ip_off & ~htons(IP_DF|IP_RF)) {
760		/*
761		 * Pass to IP reassembly mechanism.
762		 */
763		if (ip_reass_packet(&m, ip) != 0) {
764			/* Failed; invalid fragment(s) or packet. */
765			goto out;
766		}
767		if (m == NULL) {
768			/* More fragments should come; silently return. */
769			goto out;
770		}
771		/*
772		 * Reassembly is done, we have the final packet.
773		 * Update cached data in local variable(s).
774		 */
775		ip = mtod(m, struct ip *);
776		hlen = ip->ip_hl << 2;
777	}
778
779#ifdef IPSEC
780	/*
781	 * Enforce IPsec policy checking if we are seeing last header.
782	 * Note that we do not visit this with protocols with PCB layer
783	 * code - like UDP/TCP/raw IP.
784	 */
785	if (ipsec_used &&
786	    (inetsw[ip_protox[ip->ip_p]].pr_flags & PR_LASTHDR) != 0) {
787		if (ipsec4_input(m, 0) != 0) {
788			goto out;
789		}
790	}
791#endif
792
793	/*
794	 * Switch out to protocol's input routine.
795	 */
796#if IFA_STATS
797	if (ia && ip) {
798		struct in_ifaddr *_ia;
799		/*
800		 * Keep a reference from ip_match_our_address with psref
801		 * is expensive, so explore ia here again.
802		 */
803		s = pserialize_read_enter();
804		_ia = in_get_ia(ip->ip_dst);
805		_ia->ia_ifa.ifa_data.ifad_inbytes += ntohs(ip->ip_len);
806		pserialize_read_exit(s);
807	}
808#endif
809	IP_STATINC(IP_STAT_DELIVERED);
810
811	const int off = hlen, nh = ip->ip_p;
812
813	(*inetsw[ip_protox[nh]].pr_input)(m, off, nh);
814	return;
815
816out:
817	m_put_rcvif_psref(ifp, &psref);
818	if (m != NULL)
819		m_freem(m);
820}
821
822/*
823 * IP timer processing.
824 */
825void
826ip_slowtimo(void)
827{
828
829	SOFTNET_KERNEL_LOCK_UNLESS_NET_MPSAFE();
830
831	ip_reass_slowtimo();
832
833	SOFTNET_KERNEL_UNLOCK_UNLESS_NET_MPSAFE();
834}
835
836/*
837 * IP drain processing.
838 */
839void
840ip_drain(void)
841{
842
843	KERNEL_LOCK(1, NULL);
844	ip_reass_drain();
845	KERNEL_UNLOCK_ONE(NULL);
846}
847
848/*
849 * ip_dooptions: perform option processing on a datagram, possibly discarding
850 * it if bad options are encountered, or forwarding it if source-routed.
851 *
852 * => Returns true if packet has been forwarded/freed.
853 * => Returns false if the packet should be processed further.
854 */
855static bool
856ip_dooptions(struct mbuf *m)
857{
858	struct ip *ip = mtod(m, struct ip *);
859	u_char *cp, *cp0;
860	struct ip_timestamp *ipt;
861	struct in_ifaddr *ia;
862	int opt, optlen, cnt, off, code, type = ICMP_PARAMPROB, forward = 0;
863	int srr_present, rr_present, ts_present;
864	struct in_addr dst;
865	n_time ntime;
866	struct ifaddr *ifa = NULL;
867	int s;
868
869	srr_present = 0;
870	rr_present = 0;
871	ts_present = 0;
872
873	dst = ip->ip_dst;
874	cp = (u_char *)(ip + 1);
875	cnt = (ip->ip_hl << 2) - sizeof(struct ip);
876	for (; cnt > 0; cnt -= optlen, cp += optlen) {
877		opt = cp[IPOPT_OPTVAL];
878		if (opt == IPOPT_EOL)
879			break;
880		if (opt == IPOPT_NOP)
881			optlen = 1;
882		else {
883			if (cnt < IPOPT_OLEN + sizeof(*cp)) {
884				code = &cp[IPOPT_OLEN] - (u_char *)ip;
885				goto bad;
886			}
887			optlen = cp[IPOPT_OLEN];
888			if (optlen < IPOPT_OLEN + sizeof(*cp) || optlen > cnt) {
889				code = &cp[IPOPT_OLEN] - (u_char *)ip;
890				goto bad;
891			}
892		}
893		switch (opt) {
894
895		default:
896			break;
897
898		/*
899		 * Source routing with record.
900		 * Find interface with current destination address.
901		 * If none on this machine then drop if strictly routed,
902		 * or do nothing if loosely routed.
903		 * Record interface address and bring up next address
904		 * component.  If strictly routed make sure next
905		 * address is on directly accessible net.
906		 */
907		case IPOPT_LSRR:
908		case IPOPT_SSRR: {
909			struct psref psref;
910			struct sockaddr_in ipaddr = {
911			    .sin_len = sizeof(ipaddr),
912			    .sin_family = AF_INET,
913			};
914
915			if (ip_allowsrcrt == 0) {
916				type = ICMP_UNREACH;
917				code = ICMP_UNREACH_NET_PROHIB;
918				goto bad;
919			}
920			if (srr_present++) {
921				code = &cp[IPOPT_OPTVAL] - (u_char *)ip;
922				goto bad;
923			}
924			if (optlen < IPOPT_OFFSET + sizeof(*cp)) {
925				code = &cp[IPOPT_OLEN] - (u_char *)ip;
926				goto bad;
927			}
928			if ((off = cp[IPOPT_OFFSET]) < IPOPT_MINOFF) {
929				code = &cp[IPOPT_OFFSET] - (u_char *)ip;
930				goto bad;
931			}
932			ipaddr.sin_addr = ip->ip_dst;
933
934			s = pserialize_read_enter();
935			ifa = ifa_ifwithaddr(sintosa(&ipaddr));
936			if (ifa == NULL) {
937				pserialize_read_exit(s);
938				if (opt == IPOPT_SSRR) {
939					type = ICMP_UNREACH;
940					code = ICMP_UNREACH_SRCFAIL;
941					goto bad;
942				}
943				/*
944				 * Loose routing, and not at next destination
945				 * yet; nothing to do except forward.
946				 */
947				break;
948			}
949			pserialize_read_exit(s);
950
951			off--;			/* 0 origin */
952			if ((off + sizeof(struct in_addr)) > optlen) {
953				/*
954				 * End of source route.  Should be for us.
955				 */
956				save_rte(m, cp, ip->ip_src);
957				break;
958			}
959			/*
960			 * locate outgoing interface
961			 */
962			memcpy((void *)&ipaddr.sin_addr, (void *)(cp + off),
963			    sizeof(ipaddr.sin_addr));
964			if (opt == IPOPT_SSRR) {
965				ifa = ifa_ifwithladdr_psref(sintosa(&ipaddr),
966				    &psref);
967				if (ifa != NULL)
968					ia = ifatoia(ifa);
969				else
970					ia = NULL;
971			} else {
972				ia = ip_rtaddr(ipaddr.sin_addr, &psref);
973			}
974			if (ia == NULL) {
975				type = ICMP_UNREACH;
976				code = ICMP_UNREACH_SRCFAIL;
977				goto bad;
978			}
979			ip->ip_dst = ipaddr.sin_addr;
980			bcopy((void *)&ia->ia_addr.sin_addr,
981			    (void *)(cp + off), sizeof(struct in_addr));
982			ia4_release(ia, &psref);
983			cp[IPOPT_OFFSET] += sizeof(struct in_addr);
984			/*
985			 * Let ip_intr's mcast routing check handle mcast pkts
986			 */
987			forward = !IN_MULTICAST(ip->ip_dst.s_addr);
988			break;
989		    }
990
991		case IPOPT_RR: {
992			struct psref psref;
993			struct sockaddr_in ipaddr = {
994			    .sin_len = sizeof(ipaddr),
995			    .sin_family = AF_INET,
996			};
997
998			if (rr_present++) {
999				code = &cp[IPOPT_OPTVAL] - (u_char *)ip;
1000				goto bad;
1001			}
1002			if (optlen < IPOPT_OFFSET + sizeof(*cp)) {
1003				code = &cp[IPOPT_OLEN] - (u_char *)ip;
1004				goto bad;
1005			}
1006			if ((off = cp[IPOPT_OFFSET]) < IPOPT_MINOFF) {
1007				code = &cp[IPOPT_OFFSET] - (u_char *)ip;
1008				goto bad;
1009			}
1010			/*
1011			 * If no space remains, ignore.
1012			 */
1013			off--;			/* 0 origin */
1014			if ((off + sizeof(struct in_addr)) > optlen)
1015				break;
1016			memcpy((void *)&ipaddr.sin_addr, (void *)(&ip->ip_dst),
1017			    sizeof(ipaddr.sin_addr));
1018			/*
1019			 * locate outgoing interface; if we're the destination,
1020			 * use the incoming interface (should be same).
1021			 */
1022			ifa = ifa_ifwithaddr_psref(sintosa(&ipaddr), &psref);
1023			if (ifa == NULL) {
1024				ia = ip_rtaddr(ipaddr.sin_addr, &psref);
1025				if (ia == NULL) {
1026					type = ICMP_UNREACH;
1027					code = ICMP_UNREACH_HOST;
1028					goto bad;
1029				}
1030			} else {
1031				ia = ifatoia(ifa);
1032			}
1033			bcopy((void *)&ia->ia_addr.sin_addr,
1034			    (void *)(cp + off), sizeof(struct in_addr));
1035			ia4_release(ia, &psref);
1036			cp[IPOPT_OFFSET] += sizeof(struct in_addr);
1037			break;
1038		    }
1039
1040		case IPOPT_TS:
1041			code = cp - (u_char *)ip;
1042			ipt = (struct ip_timestamp *)cp;
1043			if (ts_present++) {
1044				code = &cp[IPOPT_OPTVAL] - (u_char *)ip;
1045				goto bad;
1046			}
1047			if (ipt->ipt_len < 4 || ipt->ipt_len > 40) {
1048				code = (u_char *)&ipt->ipt_len - (u_char *)ip;
1049				goto bad;
1050			}
1051			if (ipt->ipt_ptr < 5) {
1052				code = (u_char *)&ipt->ipt_ptr - (u_char *)ip;
1053				goto bad;
1054			}
1055			if (ipt->ipt_ptr > ipt->ipt_len - sizeof(int32_t)) {
1056				if (++ipt->ipt_oflw == 0) {
1057					code = (u_char *)&ipt->ipt_ptr -
1058					    (u_char *)ip;
1059					goto bad;
1060				}
1061				break;
1062			}
1063			cp0 = (cp + ipt->ipt_ptr - 1);
1064			switch (ipt->ipt_flg) {
1065
1066			case IPOPT_TS_TSONLY:
1067				break;
1068
1069			case IPOPT_TS_TSANDADDR: {
1070				struct ifnet *rcvif;
1071				int _s, _ss;
1072				struct sockaddr_in ipaddr = {
1073				    .sin_len = sizeof(ipaddr),
1074				    .sin_family = AF_INET,
1075				};
1076
1077				if (ipt->ipt_ptr - 1 + sizeof(n_time) +
1078				    sizeof(struct in_addr) > ipt->ipt_len) {
1079					code = (u_char *)&ipt->ipt_ptr -
1080					    (u_char *)ip;
1081					goto bad;
1082				}
1083				ipaddr.sin_addr = dst;
1084				_ss = pserialize_read_enter();
1085				rcvif = m_get_rcvif(m, &_s);
1086				if (__predict_true(rcvif != NULL)) {
1087					ifa = ifaof_ifpforaddr(sintosa(&ipaddr),
1088					    rcvif);
1089				}
1090				m_put_rcvif(rcvif, &_s);
1091				if (ifa == NULL) {
1092					pserialize_read_exit(_ss);
1093					break;
1094				}
1095				ia = ifatoia(ifa);
1096				bcopy(&ia->ia_addr.sin_addr,
1097				    cp0, sizeof(struct in_addr));
1098				pserialize_read_exit(_ss);
1099				ipt->ipt_ptr += sizeof(struct in_addr);
1100				break;
1101			}
1102
1103			case IPOPT_TS_PRESPEC: {
1104				struct sockaddr_in ipaddr = {
1105				    .sin_len = sizeof(ipaddr),
1106				    .sin_family = AF_INET,
1107				};
1108
1109				if (ipt->ipt_ptr - 1 + sizeof(n_time) +
1110				    sizeof(struct in_addr) > ipt->ipt_len) {
1111					code = (u_char *)&ipt->ipt_ptr -
1112					    (u_char *)ip;
1113					goto bad;
1114				}
1115				memcpy(&ipaddr.sin_addr, cp0,
1116				    sizeof(struct in_addr));
1117				s = pserialize_read_enter();
1118				ifa = ifa_ifwithaddr(sintosa(&ipaddr));
1119				if (ifa == NULL) {
1120					pserialize_read_exit(s);
1121					continue;
1122				}
1123				pserialize_read_exit(s);
1124				ipt->ipt_ptr += sizeof(struct in_addr);
1125				break;
1126			    }
1127
1128			default:
1129				/* XXX can't take &ipt->ipt_flg */
1130				code = (u_char *)&ipt->ipt_ptr -
1131				    (u_char *)ip + 1;
1132				goto bad;
1133			}
1134			ntime = iptime();
1135			cp0 = (u_char *) &ntime; /* XXX grumble, GCC... */
1136			memmove((char *)cp + ipt->ipt_ptr - 1, cp0,
1137			    sizeof(n_time));
1138			ipt->ipt_ptr += sizeof(n_time);
1139		}
1140	}
1141	if (forward) {
1142		struct ifnet *rcvif;
1143		struct psref _psref;
1144
1145		if (ip_forwsrcrt == 0) {
1146			type = ICMP_UNREACH;
1147			code = ICMP_UNREACH_SRCFAIL;
1148			goto bad;
1149		}
1150
1151		rcvif = m_get_rcvif_psref(m, &_psref);
1152		if (__predict_false(rcvif == NULL)) {
1153			type = ICMP_UNREACH;
1154			code = ICMP_UNREACH_HOST;
1155			goto bad;
1156		}
1157		ip_forward(m, 1, rcvif);
1158		m_put_rcvif_psref(rcvif, &_psref);
1159		return true;
1160	}
1161	return false;
1162bad:
1163	icmp_error(m, type, code, 0, 0);
1164	IP_STATINC(IP_STAT_BADOPTIONS);
1165	return true;
1166}
1167
1168/*
1169 * ip_rtaddr: given address of next destination (final or next hop),
1170 * return internet address info of interface to be used to get there.
1171 */
1172static struct in_ifaddr *
1173ip_rtaddr(struct in_addr dst, struct psref *psref)
1174{
1175	struct rtentry *rt;
1176	union {
1177		struct sockaddr		dst;
1178		struct sockaddr_in	dst4;
1179	} u;
1180	struct route *ro;
1181
1182	sockaddr_in_init(&u.dst4, &dst, 0);
1183
1184	ro = percpu_getref(ipforward_rt_percpu);
1185	rt = rtcache_lookup(ro, &u.dst);
1186	if (rt == NULL) {
1187		percpu_putref(ipforward_rt_percpu);
1188		return NULL;
1189	}
1190
1191	ia4_acquire(ifatoia(rt->rt_ifa), psref);
1192	rtcache_unref(rt, ro);
1193	percpu_putref(ipforward_rt_percpu);
1194
1195	return ifatoia(rt->rt_ifa);
1196}
1197
1198/*
1199 * save_rte: save incoming source route for use in replies, to be picked
1200 * up later by ip_srcroute if the receiver is interested.
1201 */
1202static void
1203save_rte(struct mbuf *m, u_char *option, struct in_addr dst)
1204{
1205	struct ip_srcrt *isr;
1206	struct m_tag *mtag;
1207	unsigned olen;
1208
1209	olen = option[IPOPT_OLEN];
1210	if (olen > sizeof(isr->isr_hdr) + sizeof(isr->isr_routes))
1211		return;
1212
1213	mtag = m_tag_get(PACKET_TAG_SRCROUTE, sizeof(*isr), M_NOWAIT);
1214	if (mtag == NULL)
1215		return;
1216	isr = (struct ip_srcrt *)(mtag + 1);
1217
1218	memcpy(isr->isr_hdr, option, olen);
1219	isr->isr_nhops = (olen - IPOPT_OFFSET - 1) / sizeof(struct in_addr);
1220	isr->isr_dst = dst;
1221	m_tag_prepend(m, mtag);
1222}
1223
1224/*
1225 * Retrieve incoming source route for use in replies,
1226 * in the same form used by setsockopt.
1227 * The first hop is placed before the options, will be removed later.
1228 */
1229struct mbuf *
1230ip_srcroute(struct mbuf *m0)
1231{
1232	struct in_addr *p, *q;
1233	struct mbuf *m;
1234	struct ip_srcrt *isr;
1235	struct m_tag *mtag;
1236
1237	mtag = m_tag_find(m0, PACKET_TAG_SRCROUTE, NULL);
1238	if (mtag == NULL)
1239		return NULL;
1240	isr = (struct ip_srcrt *)(mtag + 1);
1241
1242	if (isr->isr_nhops == 0)
1243		return NULL;
1244
1245	m = m_get(M_DONTWAIT, MT_SOOPTS);
1246	if (m == NULL)
1247		return NULL;
1248
1249	MCLAIM(m, &inetdomain.dom_mowner);
1250#define OPTSIZ	(sizeof(isr->isr_nop) + sizeof(isr->isr_hdr))
1251
1252	/* length is (nhops+1)*sizeof(addr) + sizeof(nop + header) */
1253	m->m_len = (isr->isr_nhops + 1) * sizeof(struct in_addr) + OPTSIZ;
1254
1255	/*
1256	 * First save first hop for return route
1257	 */
1258	p = &(isr->isr_routes[isr->isr_nhops - 1]);
1259	*(mtod(m, struct in_addr *)) = *p--;
1260
1261	/*
1262	 * Copy option fields and padding (nop) to mbuf.
1263	 */
1264	isr->isr_nop = IPOPT_NOP;
1265	isr->isr_hdr[IPOPT_OFFSET] = IPOPT_MINOFF;
1266	memmove(mtod(m, char *) + sizeof(struct in_addr), &isr->isr_nop,
1267	    OPTSIZ);
1268	q = (struct in_addr *)(mtod(m, char *) +
1269	    sizeof(struct in_addr) + OPTSIZ);
1270#undef OPTSIZ
1271	/*
1272	 * Record return path as an IP source route,
1273	 * reversing the path (pointers are now aligned).
1274	 */
1275	while (p >= isr->isr_routes) {
1276		*q++ = *p--;
1277	}
1278	/*
1279	 * Last hop goes to final destination.
1280	 */
1281	*q = isr->isr_dst;
1282	m_tag_delete(m0, mtag);
1283	return m;
1284}
1285
1286const int inetctlerrmap[PRC_NCMDS] = {
1287	[PRC_MSGSIZE] = EMSGSIZE,
1288	[PRC_HOSTDEAD] = EHOSTDOWN,
1289	[PRC_HOSTUNREACH] = EHOSTUNREACH,
1290	[PRC_UNREACH_NET] = EHOSTUNREACH,
1291	[PRC_UNREACH_HOST] = EHOSTUNREACH,
1292	[PRC_UNREACH_PROTOCOL] = ECONNREFUSED,
1293	[PRC_UNREACH_PORT] = ECONNREFUSED,
1294	[PRC_UNREACH_SRCFAIL] = EHOSTUNREACH,
1295	[PRC_PARAMPROB] = ENOPROTOOPT,
1296};
1297
1298void
1299ip_fasttimo(void)
1300{
1301	if (ip_drainwanted) {
1302		ip_drain();
1303		ip_drainwanted = 0;
1304	}
1305}
1306
1307void
1308ip_drainstub(void)
1309{
1310	ip_drainwanted = 1;
1311}
1312
1313/*
1314 * Forward a packet.  If some error occurs return the sender
1315 * an icmp packet.  Note we can't always generate a meaningful
1316 * icmp message because icmp doesn't have a large enough repertoire
1317 * of codes and types.
1318 *
1319 * If not forwarding, just drop the packet.  This could be confusing
1320 * if ipforwarding was zero but some routing protocol was advancing
1321 * us as a gateway to somewhere.  However, we must let the routing
1322 * protocol deal with that.
1323 *
1324 * The srcrt parameter indicates whether the packet is being forwarded
1325 * via a source route.
1326 */
1327static void
1328ip_forward(struct mbuf *m, int srcrt, struct ifnet *rcvif)
1329{
1330	struct ip *ip = mtod(m, struct ip *);
1331	struct rtentry *rt;
1332	int error, type = 0, code = 0, destmtu = 0;
1333	struct mbuf *mcopy;
1334	n_long dest;
1335	union {
1336		struct sockaddr		dst;
1337		struct sockaddr_in	dst4;
1338	} u;
1339	uint64_t *ips;
1340	struct route *ro;
1341
1342	KASSERTMSG(cpu_softintr_p(), "ip_forward: not in the software "
1343	    "interrupt handler; synchronization assumptions violated");
1344
1345	/*
1346	 * We are now in the output path.
1347	 */
1348	MCLAIM(m, &ip_tx_mowner);
1349
1350	/*
1351	 * Clear any in-bound checksum flags for this packet.
1352	 */
1353	m->m_pkthdr.csum_flags = 0;
1354
1355	dest = 0;
1356	if (m->m_flags & (M_BCAST|M_MCAST) || in_canforward(ip->ip_dst) == 0) {
1357		IP_STATINC(IP_STAT_CANTFORWARD);
1358		m_freem(m);
1359		return;
1360	}
1361
1362	if (ip->ip_ttl <= IPTTLDEC) {
1363		icmp_error(m, ICMP_TIMXCEED, ICMP_TIMXCEED_INTRANS, dest, 0);
1364		return;
1365	}
1366
1367	sockaddr_in_init(&u.dst4, &ip->ip_dst, 0);
1368
1369	ro = percpu_getref(ipforward_rt_percpu);
1370	rt = rtcache_lookup(ro, &u.dst);
1371	if (rt == NULL) {
1372		percpu_putref(ipforward_rt_percpu);
1373		icmp_error(m, ICMP_UNREACH, ICMP_UNREACH_NET, dest, 0);
1374		return;
1375	}
1376
1377	/*
1378	 * Save at most 68 bytes of the packet in case
1379	 * we need to generate an ICMP message to the src.
1380	 * Pullup to avoid sharing mbuf cluster between m and mcopy.
1381	 */
1382	mcopy = m_copym(m, 0, imin(ntohs(ip->ip_len), 68), M_DONTWAIT);
1383	if (mcopy)
1384		mcopy = m_pullup(mcopy, ip->ip_hl << 2);
1385
1386	ip->ip_ttl -= IPTTLDEC;
1387
1388	/*
1389	 * If forwarding packet using same interface that it came in on,
1390	 * perhaps should send a redirect to sender to shortcut a hop.
1391	 * Only send redirect if source is sending directly to us,
1392	 * and if packet was not source routed (or has any options).
1393	 * Also, don't send redirect if forwarding using a default route
1394	 * or a route modified by a redirect.
1395	 */
1396	if (rt->rt_ifp == rcvif &&
1397	    (rt->rt_flags & (RTF_DYNAMIC|RTF_MODIFIED)) == 0 &&
1398	    !in_nullhost(satocsin(rt_getkey(rt))->sin_addr) &&
1399	    ipsendredirects && !srcrt) {
1400		if (rt->rt_ifa &&
1401		    (ip->ip_src.s_addr & ifatoia(rt->rt_ifa)->ia_subnetmask) ==
1402		    ifatoia(rt->rt_ifa)->ia_subnet) {
1403			if (rt->rt_flags & RTF_GATEWAY)
1404				dest = satosin(rt->rt_gateway)->sin_addr.s_addr;
1405			else
1406				dest = ip->ip_dst.s_addr;
1407			/*
1408			 * Router requirements says to only send host
1409			 * redirects.
1410			 */
1411			type = ICMP_REDIRECT;
1412			code = ICMP_REDIRECT_HOST;
1413		}
1414	}
1415	rtcache_unref(rt, ro);
1416
1417	error = ip_output(m, NULL, ro,
1418	    (IP_FORWARDING | (ip_directedbcast ? IP_ALLOWBROADCAST : 0)),
1419	    NULL, NULL);
1420
1421	if (error) {
1422		IP_STATINC(IP_STAT_CANTFORWARD);
1423		goto error;
1424	}
1425
1426	ips = IP_STAT_GETREF();
1427	ips[IP_STAT_FORWARD]++;
1428
1429	if (type) {
1430		ips[IP_STAT_REDIRECTSENT]++;
1431		IP_STAT_PUTREF();
1432		goto redirect;
1433	}
1434
1435	IP_STAT_PUTREF();
1436	if (mcopy) {
1437#ifdef GATEWAY
1438		if (mcopy->m_flags & M_CANFASTFWD)
1439			ipflow_create(ro, mcopy);
1440#endif
1441		m_freem(mcopy);
1442	}
1443
1444	percpu_putref(ipforward_rt_percpu);
1445	return;
1446
1447redirect:
1448error:
1449	if (mcopy == NULL) {
1450		percpu_putref(ipforward_rt_percpu);
1451		return;
1452	}
1453
1454	switch (error) {
1455
1456	case 0:				/* forwarded, but need redirect */
1457		/* type, code set above */
1458		break;
1459
1460	case ENETUNREACH:		/* shouldn't happen, checked above */
1461	case EHOSTUNREACH:
1462	case ENETDOWN:
1463	case EHOSTDOWN:
1464	default:
1465		type = ICMP_UNREACH;
1466		code = ICMP_UNREACH_HOST;
1467		break;
1468
1469	case EMSGSIZE:
1470		type = ICMP_UNREACH;
1471		code = ICMP_UNREACH_NEEDFRAG;
1472
1473		if ((rt = rtcache_validate(ro)) != NULL) {
1474			destmtu = rt->rt_ifp->if_mtu;
1475			rtcache_unref(rt, ro);
1476		}
1477#ifdef IPSEC
1478		if (ipsec_used)
1479			(void)ipsec4_forward(mcopy, &destmtu);
1480#endif
1481		IP_STATINC(IP_STAT_CANTFRAG);
1482		break;
1483
1484	case ENOBUFS:
1485		/*
1486		 * Do not generate ICMP_SOURCEQUENCH as required in RFC 1812,
1487		 * Requirements for IP Version 4 Routers.  Source quench can
1488		 * big problem under DoS attacks or if the underlying
1489		 * interface is rate-limited.
1490		 */
1491		if (mcopy)
1492			m_freem(mcopy);
1493		percpu_putref(ipforward_rt_percpu);
1494		return;
1495	}
1496	icmp_error(mcopy, type, code, dest, destmtu);
1497	percpu_putref(ipforward_rt_percpu);
1498}
1499
1500void
1501ip_savecontrol(struct inpcb *inp, struct mbuf **mp, struct ip *ip,
1502    struct mbuf *m)
1503{
1504	struct socket *so = inp->inp_socket;
1505	int inpflags = inp->inp_flags;
1506
1507	if (SOOPT_TIMESTAMP(so->so_options))
1508		mp = sbsavetimestamp(so->so_options, m, mp);
1509
1510	if (inpflags & INP_RECVDSTADDR) {
1511		*mp = sbcreatecontrol(&ip->ip_dst,
1512		    sizeof(struct in_addr), IP_RECVDSTADDR, IPPROTO_IP);
1513		if (*mp)
1514			mp = &(*mp)->m_next;
1515	}
1516
1517	if (inpflags & INP_RECVTTL) {
1518		*mp = sbcreatecontrol(&ip->ip_ttl,
1519		    sizeof(uint8_t), IP_RECVTTL, IPPROTO_IP);
1520		if (*mp)
1521			mp = &(*mp)->m_next;
1522	}
1523
1524	struct psref psref;
1525	ifnet_t *ifp = m_get_rcvif_psref(m, &psref);
1526	if (__predict_false(ifp == NULL)) {
1527#ifdef DIAGNOSTIC
1528		printf("%s: missing receive interface\n", __func__);
1529#endif
1530		return; /* XXX should report error? */
1531	}
1532
1533	if (inpflags & INP_RECVPKTINFO) {
1534		struct in_pktinfo ipi;
1535		ipi.ipi_addr = ip->ip_dst;
1536		ipi.ipi_ifindex = ifp->if_index;
1537		*mp = sbcreatecontrol(&ipi,
1538		    sizeof(ipi), IP_PKTINFO, IPPROTO_IP);
1539		if (*mp)
1540			mp = &(*mp)->m_next;
1541	}
1542	if (inpflags & INP_RECVIF) {
1543		struct sockaddr_dl sdl;
1544
1545		sockaddr_dl_init(&sdl, sizeof(sdl), ifp->if_index, 0, NULL, 0,
1546		    NULL, 0);
1547		*mp = sbcreatecontrol(&sdl, sdl.sdl_len, IP_RECVIF, IPPROTO_IP);
1548		if (*mp)
1549			mp = &(*mp)->m_next;
1550	}
1551	m_put_rcvif_psref(ifp, &psref);
1552}
1553
1554/*
1555 * sysctl helper routine for net.inet.ip.forwsrcrt.
1556 */
1557static int
1558sysctl_net_inet_ip_forwsrcrt(SYSCTLFN_ARGS)
1559{
1560	int error, tmp;
1561	struct sysctlnode node;
1562
1563	node = *rnode;
1564	tmp = ip_forwsrcrt;
1565	node.sysctl_data = &tmp;
1566	error = sysctl_lookup(SYSCTLFN_CALL(&node));
1567	if (error || newp == NULL)
1568		return (error);
1569
1570	error = kauth_authorize_network(l->l_cred, KAUTH_NETWORK_FORWSRCRT,
1571	    0, NULL, NULL, NULL);
1572	if (error)
1573		return (error);
1574
1575	ip_forwsrcrt = tmp;
1576
1577	return (0);
1578}
1579
1580/*
1581 * sysctl helper routine for net.inet.ip.mtudisctimeout.  checks the
1582 * range of the new value and tweaks timers if it changes.
1583 */
1584static int
1585sysctl_net_inet_ip_pmtudto(SYSCTLFN_ARGS)
1586{
1587	int error, tmp;
1588	struct sysctlnode node;
1589
1590	icmp_mtudisc_lock();
1591
1592	node = *rnode;
1593	tmp = ip_mtudisc_timeout;
1594	node.sysctl_data = &tmp;
1595	error = sysctl_lookup(SYSCTLFN_CALL(&node));
1596	if (error || newp == NULL)
1597		goto out;
1598	if (tmp < 0) {
1599		error = EINVAL;
1600		goto out;
1601	}
1602
1603	ip_mtudisc_timeout = tmp;
1604	rt_timer_queue_change(ip_mtudisc_timeout_q, ip_mtudisc_timeout);
1605	error = 0;
1606out:
1607	icmp_mtudisc_unlock();
1608	return error;
1609}
1610
1611static int
1612sysctl_net_inet_ip_stats(SYSCTLFN_ARGS)
1613{
1614
1615	return (NETSTAT_SYSCTL(ipstat_percpu, IP_NSTATS));
1616}
1617
1618static void
1619sysctl_net_inet_ip_setup(struct sysctllog **clog)
1620{
1621	sysctl_createv(clog, 0, NULL, NULL,
1622		       CTLFLAG_PERMANENT,
1623		       CTLTYPE_NODE, "inet",
1624		       SYSCTL_DESCR("PF_INET related settings"),
1625		       NULL, 0, NULL, 0,
1626		       CTL_NET, PF_INET, CTL_EOL);
1627	sysctl_createv(clog, 0, NULL, NULL,
1628		       CTLFLAG_PERMANENT,
1629		       CTLTYPE_NODE, "ip",
1630		       SYSCTL_DESCR("IPv4 related settings"),
1631		       NULL, 0, NULL, 0,
1632		       CTL_NET, PF_INET, IPPROTO_IP, CTL_EOL);
1633
1634	sysctl_createv(clog, 0, NULL, NULL,
1635		       CTLFLAG_PERMANENT|CTLFLAG_READWRITE,
1636		       CTLTYPE_INT, "forwarding",
1637		       SYSCTL_DESCR("Enable forwarding of INET datagrams"),
1638		       NULL, 0, &ipforwarding, 0,
1639		       CTL_NET, PF_INET, IPPROTO_IP,
1640		       IPCTL_FORWARDING, CTL_EOL);
1641	sysctl_createv(clog, 0, NULL, NULL,
1642		       CTLFLAG_PERMANENT|CTLFLAG_READWRITE,
1643		       CTLTYPE_INT, "redirect",
1644		       SYSCTL_DESCR("Enable sending of ICMP redirect messages"),
1645		       NULL, 0, &ipsendredirects, 0,
1646		       CTL_NET, PF_INET, IPPROTO_IP,
1647		       IPCTL_SENDREDIRECTS, CTL_EOL);
1648	sysctl_createv(clog, 0, NULL, NULL,
1649		       CTLFLAG_PERMANENT|CTLFLAG_READWRITE,
1650		       CTLTYPE_INT, "ttl",
1651		       SYSCTL_DESCR("Default TTL for an INET datagram"),
1652		       NULL, 0, &ip_defttl, 0,
1653		       CTL_NET, PF_INET, IPPROTO_IP,
1654		       IPCTL_DEFTTL, CTL_EOL);
1655#ifdef IPCTL_DEFMTU
1656	sysctl_createv(clog, 0, NULL, NULL,
1657		       CTLFLAG_PERMANENT /* |CTLFLAG_READWRITE? */,
1658		       CTLTYPE_INT, "mtu",
1659		       SYSCTL_DESCR("Default MTA for an INET route"),
1660		       NULL, 0, &ip_mtu, 0,
1661		       CTL_NET, PF_INET, IPPROTO_IP,
1662		       IPCTL_DEFMTU, CTL_EOL);
1663#endif /* IPCTL_DEFMTU */
1664	sysctl_createv(clog, 0, NULL, NULL,
1665		       CTLFLAG_PERMANENT|CTLFLAG_READWRITE,
1666		       CTLTYPE_INT, "forwsrcrt",
1667		       SYSCTL_DESCR("Enable forwarding of source-routed "
1668				    "datagrams"),
1669		       sysctl_net_inet_ip_forwsrcrt, 0, &ip_forwsrcrt, 0,
1670		       CTL_NET, PF_INET, IPPROTO_IP,
1671		       IPCTL_FORWSRCRT, CTL_EOL);
1672	sysctl_createv(clog, 0, NULL, NULL,
1673		       CTLFLAG_PERMANENT|CTLFLAG_READWRITE,
1674		       CTLTYPE_INT, "directed-broadcast",
1675		       SYSCTL_DESCR("Enable forwarding of broadcast datagrams"),
1676		       NULL, 0, &ip_directedbcast, 0,
1677		       CTL_NET, PF_INET, IPPROTO_IP,
1678		       IPCTL_DIRECTEDBCAST, CTL_EOL);
1679	sysctl_createv(clog, 0, NULL, NULL,
1680		       CTLFLAG_PERMANENT|CTLFLAG_READWRITE,
1681		       CTLTYPE_INT, "allowsrcrt",
1682		       SYSCTL_DESCR("Accept source-routed datagrams"),
1683		       NULL, 0, &ip_allowsrcrt, 0,
1684		       CTL_NET, PF_INET, IPPROTO_IP,
1685		       IPCTL_ALLOWSRCRT, CTL_EOL);
1686
1687	sysctl_createv(clog, 0, NULL, NULL,
1688		       CTLFLAG_PERMANENT|CTLFLAG_READWRITE,
1689		       CTLTYPE_INT, "mtudisc",
1690		       SYSCTL_DESCR("Use RFC1191 Path MTU Discovery"),
1691		       NULL, 0, &ip_mtudisc, 0,
1692		       CTL_NET, PF_INET, IPPROTO_IP,
1693		       IPCTL_MTUDISC, CTL_EOL);
1694	sysctl_createv(clog, 0, NULL, NULL,
1695		       CTLFLAG_PERMANENT|CTLFLAG_READWRITE,
1696		       CTLTYPE_INT, "anonportmin",
1697		       SYSCTL_DESCR("Lowest ephemeral port number to assign"),
1698		       sysctl_net_inet_ip_ports, 0, &anonportmin, 0,
1699		       CTL_NET, PF_INET, IPPROTO_IP,
1700		       IPCTL_ANONPORTMIN, CTL_EOL);
1701	sysctl_createv(clog, 0, NULL, NULL,
1702		       CTLFLAG_PERMANENT|CTLFLAG_READWRITE,
1703		       CTLTYPE_INT, "anonportmax",
1704		       SYSCTL_DESCR("Highest ephemeral port number to assign"),
1705		       sysctl_net_inet_ip_ports, 0, &anonportmax, 0,
1706		       CTL_NET, PF_INET, IPPROTO_IP,
1707		       IPCTL_ANONPORTMAX, CTL_EOL);
1708	sysctl_createv(clog, 0, NULL, NULL,
1709		       CTLFLAG_PERMANENT|CTLFLAG_READWRITE,
1710		       CTLTYPE_INT, "mtudisctimeout",
1711		       SYSCTL_DESCR("Lifetime of a Path MTU Discovered route"),
1712		       sysctl_net_inet_ip_pmtudto, 0, (void *)&ip_mtudisc_timeout, 0,
1713		       CTL_NET, PF_INET, IPPROTO_IP,
1714		       IPCTL_MTUDISCTIMEOUT, CTL_EOL);
1715#ifndef IPNOPRIVPORTS
1716	sysctl_createv(clog, 0, NULL, NULL,
1717		       CTLFLAG_PERMANENT|CTLFLAG_READWRITE,
1718		       CTLTYPE_INT, "lowportmin",
1719		       SYSCTL_DESCR("Lowest privileged ephemeral port number "
1720				    "to assign"),
1721		       sysctl_net_inet_ip_ports, 0, &lowportmin, 0,
1722		       CTL_NET, PF_INET, IPPROTO_IP,
1723		       IPCTL_LOWPORTMIN, CTL_EOL);
1724	sysctl_createv(clog, 0, NULL, NULL,
1725		       CTLFLAG_PERMANENT|CTLFLAG_READWRITE,
1726		       CTLTYPE_INT, "lowportmax",
1727		       SYSCTL_DESCR("Highest privileged ephemeral port number "
1728				    "to assign"),
1729		       sysctl_net_inet_ip_ports, 0, &lowportmax, 0,
1730		       CTL_NET, PF_INET, IPPROTO_IP,
1731		       IPCTL_LOWPORTMAX, CTL_EOL);
1732#endif /* IPNOPRIVPORTS */
1733#if NGRE > 0
1734	sysctl_createv(clog, 0, NULL, NULL,
1735		       CTLFLAG_PERMANENT|CTLFLAG_READWRITE,
1736		       CTLTYPE_INT, "grettl",
1737		       SYSCTL_DESCR("Default TTL for a gre tunnel datagram"),
1738		       NULL, 0, &ip_gre_ttl, 0,
1739		       CTL_NET, PF_INET, IPPROTO_IP,
1740		       IPCTL_GRE_TTL, CTL_EOL);
1741#endif /* NGRE */
1742	sysctl_createv(clog, 0, NULL, NULL,
1743		       CTLFLAG_PERMANENT|CTLFLAG_READWRITE,
1744		       CTLTYPE_INT, "checkinterface",
1745		       SYSCTL_DESCR("Enable receive side of Strong ES model "
1746				    "from RFC1122"),
1747		       NULL, 0, &ip_checkinterface, 0,
1748		       CTL_NET, PF_INET, IPPROTO_IP,
1749		       IPCTL_CHECKINTERFACE, CTL_EOL);
1750	sysctl_createv(clog, 0, NULL, NULL,
1751		       CTLFLAG_PERMANENT|CTLFLAG_READWRITE,
1752		       CTLTYPE_INT, "random_id",
1753		       SYSCTL_DESCR("Assign random ip_id values"),
1754		       NULL, 0, &ip_do_randomid, 0,
1755		       CTL_NET, PF_INET, IPPROTO_IP,
1756		       IPCTL_RANDOMID, CTL_EOL);
1757	sysctl_createv(clog, 0, NULL, NULL,
1758		       CTLFLAG_PERMANENT|CTLFLAG_READWRITE,
1759		       CTLTYPE_INT, "do_loopback_cksum",
1760		       SYSCTL_DESCR("Perform IP checksum on loopback"),
1761		       NULL, 0, &ip_do_loopback_cksum, 0,
1762		       CTL_NET, PF_INET, IPPROTO_IP,
1763		       IPCTL_LOOPBACKCKSUM, CTL_EOL);
1764	sysctl_createv(clog, 0, NULL, NULL,
1765		       CTLFLAG_PERMANENT,
1766		       CTLTYPE_STRUCT, "stats",
1767		       SYSCTL_DESCR("IP statistics"),
1768		       sysctl_net_inet_ip_stats, 0, NULL, 0,
1769		       CTL_NET, PF_INET, IPPROTO_IP, IPCTL_STATS,
1770		       CTL_EOL);
1771#if NARP
1772	sysctl_createv(clog, 0, NULL, NULL,
1773		       CTLFLAG_PERMANENT|CTLFLAG_READWRITE,
1774		       CTLTYPE_INT, "dad_count",
1775		       SYSCTL_DESCR("Number of Duplicate Address Detection "
1776				    "probes to send"),
1777		       NULL, 0, &ip_dad_count, 0,
1778		       CTL_NET, PF_INET, IPPROTO_IP,
1779		       IPCTL_DAD_COUNT, CTL_EOL);
1780#endif
1781
1782	/* anonportalgo RFC6056 subtree */
1783	const struct sysctlnode *portalgo_node;
1784	sysctl_createv(clog, 0, NULL, &portalgo_node,
1785		       CTLFLAG_PERMANENT,
1786		       CTLTYPE_NODE, "anonportalgo",
1787		       SYSCTL_DESCR("Anonymous Port Algorithm Selection (RFC 6056)"),
1788	    	       NULL, 0, NULL, 0,
1789		       CTL_NET, PF_INET, IPPROTO_IP, CTL_CREATE, CTL_EOL);
1790	sysctl_createv(clog, 0, &portalgo_node, NULL,
1791		       CTLFLAG_PERMANENT,
1792		       CTLTYPE_STRING, "available",
1793		       SYSCTL_DESCR("available algorithms"),
1794		       sysctl_portalgo_available, 0, NULL, PORTALGO_MAXLEN,
1795		       CTL_CREATE, CTL_EOL);
1796	sysctl_createv(clog, 0, &portalgo_node, NULL,
1797		       CTLFLAG_PERMANENT|CTLFLAG_READWRITE,
1798		       CTLTYPE_STRING, "selected",
1799		       SYSCTL_DESCR("selected algorithm"),
1800		       sysctl_portalgo_selected4, 0, NULL, PORTALGO_MAXLEN,
1801		       CTL_CREATE, CTL_EOL);
1802	sysctl_createv(clog, 0, &portalgo_node, NULL,
1803		       CTLFLAG_PERMANENT|CTLFLAG_READWRITE,
1804		       CTLTYPE_STRUCT, "reserve",
1805		       SYSCTL_DESCR("bitmap of reserved ports"),
1806		       sysctl_portalgo_reserve4, 0, NULL, 0,
1807		       CTL_CREATE, CTL_EOL);
1808}
1809
1810void
1811ip_statinc(u_int stat)
1812{
1813
1814	KASSERT(stat < IP_NSTATS);
1815	IP_STATINC(stat);
1816}
1817