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