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