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