ip_input.c revision 54175
1/*
2 * Copyright (c) 1982, 1986, 1988, 1993
3 *	The Regents of the University of California.  All rights reserved.
4 *
5 * Redistribution and use in source and binary forms, with or without
6 * modification, are permitted provided that the following conditions
7 * are met:
8 * 1. Redistributions of source code must retain the above copyright
9 *    notice, this list of conditions and the following disclaimer.
10 * 2. Redistributions in binary form must reproduce the above copyright
11 *    notice, this list of conditions and the following disclaimer in the
12 *    documentation and/or other materials provided with the distribution.
13 * 3. All advertising materials mentioning features or use of this software
14 *    must display the following acknowledgement:
15 *	This product includes software developed by the University of
16 *	California, Berkeley and its contributors.
17 * 4. Neither the name of the University nor the names of its contributors
18 *    may be used to endorse or promote products derived from this software
19 *    without specific prior written permission.
20 *
21 * THIS SOFTWARE IS PROVIDED BY THE REGENTS AND CONTRIBUTORS ``AS IS'' AND
22 * ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
23 * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE
24 * ARE DISCLAIMED.  IN NO EVENT SHALL THE REGENTS OR CONTRIBUTORS BE LIABLE
25 * FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL
26 * DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS
27 * OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION)
28 * HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT
29 * LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY
30 * OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF
31 * SUCH DAMAGE.
32 *
33 *	@(#)ip_input.c	8.2 (Berkeley) 1/4/94
34 * $FreeBSD: head/sys/netinet/ip_input.c 54175 1999-12-06 00:43:07Z archie $
35 */
36
37#define	_IP_VHL
38
39#include "opt_bootp.h"
40#include "opt_ipfw.h"
41#include "opt_ipdn.h"
42#include "opt_ipdivert.h"
43#include "opt_ipfilter.h"
44#include "opt_ipstealth.h"
45
46#include <stddef.h>
47
48#include <sys/param.h>
49#include <sys/systm.h>
50#include <sys/mbuf.h>
51#include <sys/malloc.h>
52#include <sys/domain.h>
53#include <sys/protosw.h>
54#include <sys/socket.h>
55#include <sys/time.h>
56#include <sys/kernel.h>
57#include <sys/syslog.h>
58#include <sys/sysctl.h>
59
60#include <net/if.h>
61#include <net/if_var.h>
62#include <net/if_dl.h>
63#include <net/route.h>
64#include <net/netisr.h>
65
66#include <netinet/in.h>
67#include <netinet/in_systm.h>
68#include <netinet/in_var.h>
69#include <netinet/ip.h>
70#include <netinet/in_pcb.h>
71#include <netinet/ip_var.h>
72#include <netinet/ip_icmp.h>
73#include <machine/in_cksum.h>
74
75#include <sys/socketvar.h>
76
77#include <netinet/ip_fw.h>
78
79#ifdef DUMMYNET
80#include <netinet/ip_dummynet.h>
81#endif
82
83int rsvp_on = 0;
84static int ip_rsvp_on;
85struct socket *ip_rsvpd;
86
87int	ipforwarding = 0;
88SYSCTL_INT(_net_inet_ip, IPCTL_FORWARDING, forwarding, CTLFLAG_RW,
89    &ipforwarding, 0, "Enable IP forwarding between interfaces");
90
91static int	ipsendredirects = 1; /* XXX */
92SYSCTL_INT(_net_inet_ip, IPCTL_SENDREDIRECTS, redirect, CTLFLAG_RW,
93    &ipsendredirects, 0, "Enable sending IP redirects");
94
95int	ip_defttl = IPDEFTTL;
96SYSCTL_INT(_net_inet_ip, IPCTL_DEFTTL, ttl, CTLFLAG_RW,
97    &ip_defttl, 0, "Maximum TTL on IP packets");
98
99static int	ip_dosourceroute = 0;
100SYSCTL_INT(_net_inet_ip, IPCTL_SOURCEROUTE, sourceroute, CTLFLAG_RW,
101    &ip_dosourceroute, 0, "Enable forwarding source routed IP packets");
102
103static int	ip_acceptsourceroute = 0;
104SYSCTL_INT(_net_inet_ip, IPCTL_ACCEPTSOURCEROUTE, accept_sourceroute,
105    CTLFLAG_RW, &ip_acceptsourceroute, 0,
106    "Enable accepting source routed IP packets");
107#ifdef DIAGNOSTIC
108static int	ipprintfs = 0;
109#endif
110
111extern	struct domain inetdomain;
112extern	struct protosw inetsw[];
113u_char	ip_protox[IPPROTO_MAX];
114static int	ipqmaxlen = IFQ_MAXLEN;
115struct	in_ifaddrhead in_ifaddrhead; /* first inet address */
116struct	ifqueue ipintrq;
117SYSCTL_INT(_net_inet_ip, IPCTL_INTRQMAXLEN, intr_queue_maxlen, CTLFLAG_RW,
118    &ipintrq.ifq_maxlen, 0, "Maximum size of the IP input queue");
119SYSCTL_INT(_net_inet_ip, IPCTL_INTRQDROPS, intr_queue_drops, CTLFLAG_RD,
120    &ipintrq.ifq_drops, 0, "Number of packets dropped from the IP input queue");
121
122struct ipstat ipstat;
123SYSCTL_STRUCT(_net_inet_ip, IPCTL_STATS, stats, CTLFLAG_RD,
124    &ipstat, ipstat, "IP statistics (struct ipstat, netinet/ip_var.h)");
125
126/* Packet reassembly stuff */
127#define IPREASS_NHASH_LOG2      6
128#define IPREASS_NHASH           (1 << IPREASS_NHASH_LOG2)
129#define IPREASS_HMASK           (IPREASS_NHASH - 1)
130#define IPREASS_HASH(x,y) \
131	(((((x) & 0xF) | ((((x) >> 8) & 0xF) << 4)) ^ (y)) & IPREASS_HMASK)
132
133static struct ipq ipq[IPREASS_NHASH];
134static int    nipq = 0;         /* total # of reass queues */
135static int    maxnipq;
136
137#ifdef IPCTL_DEFMTU
138SYSCTL_INT(_net_inet_ip, IPCTL_DEFMTU, mtu, CTLFLAG_RW,
139    &ip_mtu, 0, "Default MTU");
140#endif
141
142#ifdef IPSTEALTH
143static int	ipstealth = 0;
144SYSCTL_INT(_net_inet_ip, OID_AUTO, stealth, CTLFLAG_RW,
145    &ipstealth, 0, "");
146#endif
147
148
149/* Firewall hooks */
150ip_fw_chk_t *ip_fw_chk_ptr;
151ip_fw_ctl_t *ip_fw_ctl_ptr;
152
153#ifdef DUMMYNET
154ip_dn_ctl_t *ip_dn_ctl_ptr;
155#endif
156
157#if defined(IPFILTER_LKM) || defined(IPFILTER)
158int iplattach __P((void));
159int (*fr_checkp) __P((struct ip *, int, struct ifnet *, int, struct mbuf **)) = NULL;
160#endif
161
162
163/*
164 * We need to save the IP options in case a protocol wants to respond
165 * to an incoming packet over the same route if the packet got here
166 * using IP source routing.  This allows connection establishment and
167 * maintenance when the remote end is on a network that is not known
168 * to us.
169 */
170static int	ip_nhops = 0;
171static	struct ip_srcrt {
172	struct	in_addr dst;			/* final destination */
173	char	nop;				/* one NOP to align */
174	char	srcopt[IPOPT_OFFSET + 1];	/* OPTVAL, OLEN and OFFSET */
175	struct	in_addr route[MAX_IPOPTLEN/sizeof(struct in_addr)];
176} ip_srcrt;
177
178struct sockaddr_in *ip_fw_fwd_addr;
179
180static void	save_rte __P((u_char *, struct in_addr));
181static int	ip_dooptions __P((struct mbuf *));
182static void	ip_forward __P((struct mbuf *, int));
183static void	ip_freef __P((struct ipq *));
184#ifdef IPDIVERT
185static struct	ip *ip_reass __P((struct mbuf *,
186			struct ipq *, struct ipq *, u_int32_t *, u_int16_t *));
187#else
188static struct	ip *ip_reass __P((struct mbuf *, struct ipq *, struct ipq *));
189#endif
190static struct	in_ifaddr *ip_rtaddr __P((struct in_addr));
191static void	ipintr __P((void));
192
193/*
194 * IP initialization: fill in IP protocol switch table.
195 * All protocols not implemented in kernel go to raw IP protocol handler.
196 */
197void
198ip_init()
199{
200	register struct protosw *pr;
201	register int i;
202
203	TAILQ_INIT(&in_ifaddrhead);
204	pr = pffindproto(PF_INET, IPPROTO_RAW, SOCK_RAW);
205	if (pr == 0)
206		panic("ip_init");
207	for (i = 0; i < IPPROTO_MAX; i++)
208		ip_protox[i] = pr - inetsw;
209	for (pr = inetdomain.dom_protosw;
210	    pr < inetdomain.dom_protoswNPROTOSW; pr++)
211		if (pr->pr_domain->dom_family == PF_INET &&
212		    pr->pr_protocol && pr->pr_protocol != IPPROTO_RAW)
213			ip_protox[pr->pr_protocol] = pr - inetsw;
214
215	for (i = 0; i < IPREASS_NHASH; i++)
216	    ipq[i].next = ipq[i].prev = &ipq[i];
217
218	maxnipq = nmbclusters/4;
219
220	ip_id = time_second & 0xffff;
221	ipintrq.ifq_maxlen = ipqmaxlen;
222#ifdef IPFILTER
223        iplattach();
224#endif
225
226}
227
228static struct	sockaddr_in ipaddr = { sizeof(ipaddr), AF_INET };
229static struct	route ipforward_rt;
230
231/*
232 * Ip input routine.  Checksum and byte swap header.  If fragmented
233 * try to reassemble.  Process options.  Pass to next level.
234 */
235void
236ip_input(struct mbuf *m)
237{
238	struct ip *ip;
239	struct ipq *fp;
240	struct in_ifaddr *ia;
241	int    i, hlen, mff;
242	u_short sum;
243	u_int16_t divert_cookie;		/* firewall cookie */
244#ifdef IPDIVERT
245	u_int32_t divert_info = 0;		/* packet divert/tee info */
246#endif
247	struct ip_fw_chain *rule = NULL;
248
249#ifdef IPDIVERT
250	/* Get and reset firewall cookie */
251	divert_cookie = ip_divert_cookie;
252	ip_divert_cookie = 0;
253#else
254	divert_cookie = 0;
255#endif
256
257#if defined(IPFIREWALL) && defined(DUMMYNET)
258        /*
259         * dummynet packet are prepended a vestigial mbuf with
260         * m_type = MT_DUMMYNET and m_data pointing to the matching
261         * rule.
262         */
263        if (m->m_type == MT_DUMMYNET) {
264            rule = (struct ip_fw_chain *)(m->m_data) ;
265            m = m->m_next ;
266            ip = mtod(m, struct ip *);
267            hlen = IP_VHL_HL(ip->ip_vhl) << 2;
268            goto iphack ;
269        } else
270            rule = NULL ;
271#endif
272
273#ifdef	DIAGNOSTIC
274	if (m == NULL || (m->m_flags & M_PKTHDR) == 0)
275		panic("ip_input no HDR");
276#endif
277	ipstat.ips_total++;
278
279	if (m->m_pkthdr.len < sizeof(struct ip))
280		goto tooshort;
281
282	if (m->m_len < sizeof (struct ip) &&
283	    (m = m_pullup(m, sizeof (struct ip))) == 0) {
284		ipstat.ips_toosmall++;
285		return;
286	}
287	ip = mtod(m, struct ip *);
288
289	if (IP_VHL_V(ip->ip_vhl) != IPVERSION) {
290		ipstat.ips_badvers++;
291		goto bad;
292	}
293
294	hlen = IP_VHL_HL(ip->ip_vhl) << 2;
295	if (hlen < sizeof(struct ip)) {	/* minimum header length */
296		ipstat.ips_badhlen++;
297		goto bad;
298	}
299	if (hlen > m->m_len) {
300		if ((m = m_pullup(m, hlen)) == 0) {
301			ipstat.ips_badhlen++;
302			return;
303		}
304		ip = mtod(m, struct ip *);
305	}
306	if (hlen == sizeof(struct ip)) {
307		sum = in_cksum_hdr(ip);
308	} else {
309		sum = in_cksum(m, hlen);
310	}
311	if (sum) {
312		ipstat.ips_badsum++;
313		goto bad;
314	}
315
316	/*
317	 * Convert fields to host representation.
318	 */
319	NTOHS(ip->ip_len);
320	if (ip->ip_len < hlen) {
321		ipstat.ips_badlen++;
322		goto bad;
323	}
324	NTOHS(ip->ip_id);
325	NTOHS(ip->ip_off);
326
327	/*
328	 * Check that the amount of data in the buffers
329	 * is as at least much as the IP header would have us expect.
330	 * Trim mbufs if longer than we expect.
331	 * Drop packet if shorter than we expect.
332	 */
333	if (m->m_pkthdr.len < ip->ip_len) {
334tooshort:
335		ipstat.ips_tooshort++;
336		goto bad;
337	}
338	if (m->m_pkthdr.len > ip->ip_len) {
339		if (m->m_len == m->m_pkthdr.len) {
340			m->m_len = ip->ip_len;
341			m->m_pkthdr.len = ip->ip_len;
342		} else
343			m_adj(m, ip->ip_len - m->m_pkthdr.len);
344	}
345	/*
346	 * IpHack's section.
347	 * Right now when no processing on packet has done
348	 * and it is still fresh out of network we do our black
349	 * deals with it.
350	 * - Firewall: deny/allow/divert
351	 * - Xlate: translate packet's addr/port (NAT).
352	 * - Pipe: pass pkt through dummynet.
353	 * - Wrap: fake packet's addr/port <unimpl.>
354	 * - Encapsulate: put it in another IP and send out. <unimp.>
355 	 */
356
357#if defined(IPFIREWALL) && defined(DUMMYNET)
358iphack:
359#endif
360#if defined(IPFILTER) || defined(IPFILTER_LKM)
361	/*
362	 * Check if we want to allow this packet to be processed.
363	 * Consider it to be bad if not.
364	 */
365	if (fr_checkp) {
366		struct	mbuf	*m1 = m;
367
368		if ((*fr_checkp)(ip, hlen, m->m_pkthdr.rcvif, 0, &m1) || !m1)
369			return;
370		ip = mtod(m = m1, struct ip *);
371	}
372#endif
373	if (ip_fw_chk_ptr) {
374#ifdef IPFIREWALL_FORWARD
375		/*
376		 * If we've been forwarded from the output side, then
377		 * skip the firewall a second time
378		 */
379		if (ip_fw_fwd_addr)
380			goto ours;
381#endif	/* IPFIREWALL_FORWARD */
382		/*
383		 * See the comment in ip_output for the return values
384		 * produced by the firewall.
385		 */
386		i = (*ip_fw_chk_ptr)(&ip,
387		    hlen, NULL, &divert_cookie, &m, &rule, &ip_fw_fwd_addr);
388		if (m == NULL)		/* Packet discarded by firewall */
389			return;
390		if (i == 0 && ip_fw_fwd_addr == NULL)	/* common case */
391			goto pass;
392#ifdef DUMMYNET
393                if ((i & IP_FW_PORT_DYNT_FLAG) != 0) {
394                        /* Send packet to the appropriate pipe */
395                        dummynet_io(i&0xffff,DN_TO_IP_IN,m,NULL,NULL,0, rule);
396			return;
397		}
398#endif
399#ifdef IPDIVERT
400		if (i != 0 && (i & IP_FW_PORT_DYNT_FLAG) == 0) {
401			/* Divert or tee packet */
402			divert_info = i;
403			goto ours;
404		}
405#endif
406#ifdef IPFIREWALL_FORWARD
407		if (i == 0 && ip_fw_fwd_addr != NULL)
408			goto pass;
409#endif
410		/*
411		 * if we get here, the packet must be dropped
412		 */
413		m_freem(m);
414		return;
415	}
416pass:
417
418	/*
419	 * Process options and, if not destined for us,
420	 * ship it on.  ip_dooptions returns 1 when an
421	 * error was detected (causing an icmp message
422	 * to be sent and the original packet to be freed).
423	 */
424	ip_nhops = 0;		/* for source routed packets */
425	if (hlen > sizeof (struct ip) && ip_dooptions(m)) {
426#ifdef IPFIREWALL_FORWARD
427		ip_fw_fwd_addr = NULL;
428#endif
429		return;
430	}
431
432        /* greedy RSVP, snatches any PATH packet of the RSVP protocol and no
433         * matter if it is destined to another node, or whether it is
434         * a multicast one, RSVP wants it! and prevents it from being forwarded
435         * anywhere else. Also checks if the rsvp daemon is running before
436	 * grabbing the packet.
437         */
438	if (rsvp_on && ip->ip_p==IPPROTO_RSVP)
439		goto ours;
440
441	/*
442	 * Check our list of addresses, to see if the packet is for us.
443	 * If we don't have any addresses, assume any unicast packet
444	 * we receive might be for us (and let the upper layers deal
445	 * with it).
446	 */
447	if (TAILQ_EMPTY(&in_ifaddrhead) &&
448	    (m->m_flags & (M_MCAST|M_BCAST)) == 0)
449		goto ours;
450
451	for (ia = TAILQ_FIRST(&in_ifaddrhead); ia;
452					ia = TAILQ_NEXT(ia, ia_link)) {
453#define	satosin(sa)	((struct sockaddr_in *)(sa))
454
455#ifdef BOOTP_COMPAT
456		if (IA_SIN(ia)->sin_addr.s_addr == INADDR_ANY)
457			goto ours;
458#endif
459#ifdef IPFIREWALL_FORWARD
460		/*
461		 * If the addr to forward to is one of ours, we pretend to
462		 * be the destination for this packet.
463		 */
464		if (ip_fw_fwd_addr == NULL) {
465			if (IA_SIN(ia)->sin_addr.s_addr == ip->ip_dst.s_addr)
466				goto ours;
467		} else if (IA_SIN(ia)->sin_addr.s_addr ==
468					 ip_fw_fwd_addr->sin_addr.s_addr)
469			goto ours;
470#else
471		if (IA_SIN(ia)->sin_addr.s_addr == ip->ip_dst.s_addr)
472			goto ours;
473#endif
474		if (ia->ia_ifp && ia->ia_ifp->if_flags & IFF_BROADCAST) {
475			if (satosin(&ia->ia_broadaddr)->sin_addr.s_addr ==
476			    ip->ip_dst.s_addr)
477				goto ours;
478			if (ip->ip_dst.s_addr == ia->ia_netbroadcast.s_addr)
479				goto ours;
480		}
481	}
482	if (IN_MULTICAST(ntohl(ip->ip_dst.s_addr))) {
483		struct in_multi *inm;
484		if (ip_mrouter) {
485			/*
486			 * If we are acting as a multicast router, all
487			 * incoming multicast packets are passed to the
488			 * kernel-level multicast forwarding function.
489			 * The packet is returned (relatively) intact; if
490			 * ip_mforward() returns a non-zero value, the packet
491			 * must be discarded, else it may be accepted below.
492			 *
493			 * (The IP ident field is put in the same byte order
494			 * as expected when ip_mforward() is called from
495			 * ip_output().)
496			 */
497			ip->ip_id = htons(ip->ip_id);
498			if (ip_mforward(ip, m->m_pkthdr.rcvif, m, 0) != 0) {
499				ipstat.ips_cantforward++;
500				m_freem(m);
501				return;
502			}
503			ip->ip_id = ntohs(ip->ip_id);
504
505			/*
506			 * The process-level routing demon needs to receive
507			 * all multicast IGMP packets, whether or not this
508			 * host belongs to their destination groups.
509			 */
510			if (ip->ip_p == IPPROTO_IGMP)
511				goto ours;
512			ipstat.ips_forward++;
513		}
514		/*
515		 * See if we belong to the destination multicast group on the
516		 * arrival interface.
517		 */
518		IN_LOOKUP_MULTI(ip->ip_dst, m->m_pkthdr.rcvif, inm);
519		if (inm == NULL) {
520			ipstat.ips_notmember++;
521			m_freem(m);
522			return;
523		}
524		goto ours;
525	}
526	if (ip->ip_dst.s_addr == (u_long)INADDR_BROADCAST)
527		goto ours;
528	if (ip->ip_dst.s_addr == INADDR_ANY)
529		goto ours;
530
531	/*
532	 * Not for us; forward if possible and desirable.
533	 */
534	if (ipforwarding == 0) {
535		ipstat.ips_cantforward++;
536		m_freem(m);
537	} else
538		ip_forward(m, 0);
539#ifdef IPFIREWALL_FORWARD
540	ip_fw_fwd_addr = NULL;
541#endif
542	return;
543
544ours:
545
546	/*
547	 * If offset or IP_MF are set, must reassemble.
548	 * Otherwise, nothing need be done.
549	 * (We could look in the reassembly queue to see
550	 * if the packet was previously fragmented,
551	 * but it's not worth the time; just let them time out.)
552	 */
553	if (ip->ip_off & (IP_MF | IP_OFFMASK | IP_RF)) {
554		if (m->m_flags & M_EXT) {		/* XXX */
555			if ((m = m_pullup(m, hlen)) == 0) {
556				ipstat.ips_toosmall++;
557#ifdef IPFIREWALL_FORWARD
558				ip_fw_fwd_addr = NULL;
559#endif
560				return;
561			}
562			ip = mtod(m, struct ip *);
563		}
564		sum = IPREASS_HASH(ip->ip_src.s_addr, ip->ip_id);
565		/*
566		 * Look for queue of fragments
567		 * of this datagram.
568		 */
569		for (fp = ipq[sum].next; fp != &ipq[sum]; fp = fp->next)
570			if (ip->ip_id == fp->ipq_id &&
571			    ip->ip_src.s_addr == fp->ipq_src.s_addr &&
572			    ip->ip_dst.s_addr == fp->ipq_dst.s_addr &&
573			    ip->ip_p == fp->ipq_p)
574				goto found;
575
576		fp = 0;
577
578		/* check if there's a place for the new queue */
579		if (nipq > maxnipq) {
580		    /*
581		     * drop something from the tail of the current queue
582		     * before proceeding further
583		     */
584		    if (ipq[sum].prev == &ipq[sum]) {   /* gak */
585			for (i = 0; i < IPREASS_NHASH; i++) {
586			    if (ipq[i].prev != &ipq[i]) {
587				ip_freef(ipq[i].prev);
588				break;
589			    }
590			}
591		    } else
592			ip_freef(ipq[sum].prev);
593		}
594found:
595		/*
596		 * Adjust ip_len to not reflect header,
597		 * set ip_mff if more fragments are expected,
598		 * convert offset of this to bytes.
599		 */
600		ip->ip_len -= hlen;
601		mff = (ip->ip_off & IP_MF) != 0;
602		if (mff) {
603		        /*
604		         * Make sure that fragments have a data length
605			 * that's a non-zero multiple of 8 bytes.
606		         */
607			if (ip->ip_len == 0 || (ip->ip_len & 0x7) != 0) {
608				ipstat.ips_toosmall++; /* XXX */
609				goto bad;
610			}
611			m->m_flags |= M_FRAG;
612		}
613		ip->ip_off <<= 3;
614
615		/*
616		 * If datagram marked as having more fragments
617		 * or if this is not the first fragment,
618		 * attempt reassembly; if it succeeds, proceed.
619		 */
620		if (mff || ip->ip_off) {
621			ipstat.ips_fragments++;
622			m->m_pkthdr.header = ip;
623#ifdef IPDIVERT
624			ip = ip_reass(m,
625			    fp, &ipq[sum], &divert_info, &divert_cookie);
626#else
627			ip = ip_reass(m, fp, &ipq[sum]);
628#endif
629			if (ip == 0) {
630#ifdef IPFIREWALL_FORWARD
631				ip_fw_fwd_addr = NULL;
632#endif
633				return;
634			}
635			/* Get the length of the reassembled packets header */
636			hlen = IP_VHL_HL(ip->ip_vhl) << 2;
637			ipstat.ips_reassembled++;
638			m = dtom(ip);
639#ifdef IPDIVERT
640			/* Restore original checksum before diverting packet */
641			if (divert_info != 0) {
642				ip->ip_len += hlen;
643				HTONS(ip->ip_len);
644				HTONS(ip->ip_off);
645				HTONS(ip->ip_id);
646				ip->ip_sum = 0;
647				ip->ip_sum = in_cksum_hdr(ip);
648				NTOHS(ip->ip_id);
649				NTOHS(ip->ip_off);
650				NTOHS(ip->ip_len);
651				ip->ip_len -= hlen;
652			}
653#endif
654		} else
655			if (fp)
656				ip_freef(fp);
657	} else
658		ip->ip_len -= hlen;
659
660#ifdef IPDIVERT
661	/*
662	 * Divert or tee packet to the divert protocol if required.
663	 *
664	 * If divert_info is zero then cookie should be too, so we shouldn't
665	 * need to clear them here.  Assume divert_packet() does so also.
666	 */
667	if (divert_info != 0) {
668		struct mbuf *clone = NULL;
669
670		/* Clone packet if we're doing a 'tee' */
671		if ((divert_info & IP_FW_PORT_TEE_FLAG) != 0)
672			clone = m_dup(m, M_DONTWAIT);
673
674		/* Restore packet header fields to original values */
675		ip->ip_len += hlen;
676		HTONS(ip->ip_len);
677		HTONS(ip->ip_off);
678		HTONS(ip->ip_id);
679
680		/* Deliver packet to divert input routine */
681		ip_divert_cookie = divert_cookie;
682		divert_packet(m, 1, divert_info & 0xffff);
683		ipstat.ips_delivered++;
684
685		/* If 'tee', continue with original packet */
686		if (clone == NULL)
687			return;
688		m = clone;
689		ip = mtod(m, struct ip *);
690	}
691#endif
692
693	/*
694	 * Switch out to protocol's input routine.
695	 */
696	ipstat.ips_delivered++;
697	(*inetsw[ip_protox[ip->ip_p]].pr_input)(m, hlen);
698#ifdef	IPFIREWALL_FORWARD
699	ip_fw_fwd_addr = NULL;	/* tcp needed it */
700#endif
701	return;
702bad:
703#ifdef	IPFIREWALL_FORWARD
704	ip_fw_fwd_addr = NULL;
705#endif
706	m_freem(m);
707}
708
709/*
710 * IP software interrupt routine - to go away sometime soon
711 */
712static void
713ipintr(void)
714{
715	int s;
716	struct mbuf *m;
717
718	while(1) {
719		s = splimp();
720		IF_DEQUEUE(&ipintrq, m);
721		splx(s);
722		if (m == 0)
723			return;
724		ip_input(m);
725	}
726}
727
728NETISR_SET(NETISR_IP, ipintr);
729
730/*
731 * Take incoming datagram fragment and try to reassemble it into
732 * whole datagram.  If a chain for reassembly of this datagram already
733 * exists, then it is given as fp; otherwise have to make a chain.
734 *
735 * When IPDIVERT enabled, keep additional state with each packet that
736 * tells us if we need to divert or tee the packet we're building.
737 */
738
739static struct ip *
740#ifdef IPDIVERT
741ip_reass(m, fp, where, divinfo, divcookie)
742#else
743ip_reass(m, fp, where)
744#endif
745	register struct mbuf *m;
746	register struct ipq *fp;
747	struct   ipq    *where;
748#ifdef IPDIVERT
749	u_int32_t *divinfo;
750	u_int16_t *divcookie;
751#endif
752{
753	struct ip *ip = mtod(m, struct ip *);
754	register struct mbuf *p = 0, *q, *nq;
755	struct mbuf *t;
756	int hlen = IP_VHL_HL(ip->ip_vhl) << 2;
757	int i, next;
758
759	/*
760	 * Presence of header sizes in mbufs
761	 * would confuse code below.
762	 */
763	m->m_data += hlen;
764	m->m_len -= hlen;
765
766	/*
767	 * If first fragment to arrive, create a reassembly queue.
768	 */
769	if (fp == 0) {
770		if ((t = m_get(M_DONTWAIT, MT_FTABLE)) == NULL)
771			goto dropfrag;
772		fp = mtod(t, struct ipq *);
773		insque(fp, where);
774		nipq++;
775		fp->ipq_ttl = IPFRAGTTL;
776		fp->ipq_p = ip->ip_p;
777		fp->ipq_id = ip->ip_id;
778		fp->ipq_src = ip->ip_src;
779		fp->ipq_dst = ip->ip_dst;
780		fp->ipq_frags = m;
781		m->m_nextpkt = NULL;
782#ifdef IPDIVERT
783		fp->ipq_div_info = 0;
784		fp->ipq_div_cookie = 0;
785#endif
786		goto inserted;
787	}
788
789#define GETIP(m)	((struct ip*)((m)->m_pkthdr.header))
790
791	/*
792	 * Find a segment which begins after this one does.
793	 */
794	for (p = NULL, q = fp->ipq_frags; q; p = q, q = q->m_nextpkt)
795		if (GETIP(q)->ip_off > ip->ip_off)
796			break;
797
798	/*
799	 * If there is a preceding segment, it may provide some of
800	 * our data already.  If so, drop the data from the incoming
801	 * segment.  If it provides all of our data, drop us, otherwise
802	 * stick new segment in the proper place.
803	 */
804	if (p) {
805		i = GETIP(p)->ip_off + GETIP(p)->ip_len - ip->ip_off;
806		if (i > 0) {
807			if (i >= ip->ip_len)
808				goto dropfrag;
809			m_adj(dtom(ip), i);
810			ip->ip_off += i;
811			ip->ip_len -= i;
812		}
813		m->m_nextpkt = p->m_nextpkt;
814		p->m_nextpkt = m;
815	} else {
816		m->m_nextpkt = fp->ipq_frags;
817		fp->ipq_frags = m;
818	}
819
820	/*
821	 * While we overlap succeeding segments trim them or,
822	 * if they are completely covered, dequeue them.
823	 */
824	for (; q != NULL && ip->ip_off + ip->ip_len > GETIP(q)->ip_off;
825	     q = nq) {
826		i = (ip->ip_off + ip->ip_len) -
827		    GETIP(q)->ip_off;
828		if (i < GETIP(q)->ip_len) {
829			GETIP(q)->ip_len -= i;
830			GETIP(q)->ip_off += i;
831			m_adj(q, i);
832			break;
833		}
834		nq = q->m_nextpkt;
835		m->m_nextpkt = nq;
836		m_freem(q);
837	}
838
839inserted:
840
841#ifdef IPDIVERT
842	/*
843	 * Transfer firewall instructions to the fragment structure.
844	 * Any fragment diverting causes the whole packet to divert.
845	 */
846	fp->ipq_div_info = *divinfo;
847	fp->ipq_div_cookie = *divcookie;
848	*divinfo = 0;
849	*divcookie = 0;
850#endif
851
852	/*
853	 * Check for complete reassembly.
854	 */
855	next = 0;
856	for (p = NULL, q = fp->ipq_frags; q; p = q, q = q->m_nextpkt) {
857		if (GETIP(q)->ip_off != next)
858			return (0);
859		next += GETIP(q)->ip_len;
860	}
861	/* Make sure the last packet didn't have the IP_MF flag */
862	if (p->m_flags & M_FRAG)
863		return (0);
864
865	/*
866	 * Reassembly is complete.  Make sure the packet is a sane size.
867	 */
868	q = fp->ipq_frags;
869	ip = GETIP(q);
870	if (next + (IP_VHL_HL(ip->ip_vhl) << 2) > IP_MAXPACKET) {
871		ipstat.ips_toolong++;
872		ip_freef(fp);
873		return (0);
874	}
875
876	/*
877	 * Concatenate fragments.
878	 */
879	m = q;
880	t = m->m_next;
881	m->m_next = 0;
882	m_cat(m, t);
883	nq = q->m_nextpkt;
884	q->m_nextpkt = 0;
885	for (q = nq; q != NULL; q = nq) {
886		nq = q->m_nextpkt;
887		q->m_nextpkt = NULL;
888		m_cat(m, q);
889	}
890
891#ifdef IPDIVERT
892	/*
893	 * Extract firewall instructions from the fragment structure.
894	 */
895	*divinfo = fp->ipq_div_info;
896	*divcookie = fp->ipq_div_cookie;
897#endif
898
899	/*
900	 * Create header for new ip packet by
901	 * modifying header of first packet;
902	 * dequeue and discard fragment reassembly header.
903	 * Make header visible.
904	 */
905	ip->ip_len = next;
906	ip->ip_src = fp->ipq_src;
907	ip->ip_dst = fp->ipq_dst;
908	remque(fp);
909	nipq--;
910	(void) m_free(dtom(fp));
911	m->m_len += (IP_VHL_HL(ip->ip_vhl) << 2);
912	m->m_data -= (IP_VHL_HL(ip->ip_vhl) << 2);
913	/* some debugging cruft by sklower, below, will go away soon */
914	if (m->m_flags & M_PKTHDR) { /* XXX this should be done elsewhere */
915		register int plen = 0;
916		for (t = m; m; m = m->m_next)
917			plen += m->m_len;
918		t->m_pkthdr.len = plen;
919	}
920	return (ip);
921
922dropfrag:
923#ifdef IPDIVERT
924	*divinfo = 0;
925	*divcookie = 0;
926#endif
927	ipstat.ips_fragdropped++;
928	m_freem(m);
929	return (0);
930
931#undef GETIP
932}
933
934/*
935 * Free a fragment reassembly header and all
936 * associated datagrams.
937 */
938static void
939ip_freef(fp)
940	struct ipq *fp;
941{
942	register struct mbuf *q;
943
944	while (fp->ipq_frags) {
945		q = fp->ipq_frags;
946		fp->ipq_frags = q->m_nextpkt;
947		m_freem(q);
948	}
949	remque(fp);
950	(void) m_free(dtom(fp));
951	nipq--;
952}
953
954/*
955 * IP timer processing;
956 * if a timer expires on a reassembly
957 * queue, discard it.
958 */
959void
960ip_slowtimo()
961{
962	register struct ipq *fp;
963	int s = splnet();
964	int i;
965
966	for (i = 0; i < IPREASS_NHASH; i++) {
967		fp = ipq[i].next;
968		if (fp == 0)
969			continue;
970		while (fp != &ipq[i]) {
971			--fp->ipq_ttl;
972			fp = fp->next;
973			if (fp->prev->ipq_ttl == 0) {
974				ipstat.ips_fragtimeout++;
975				ip_freef(fp->prev);
976			}
977		}
978	}
979	ipflow_slowtimo();
980	splx(s);
981}
982
983/*
984 * Drain off all datagram fragments.
985 */
986void
987ip_drain()
988{
989	int     i;
990
991	for (i = 0; i < IPREASS_NHASH; i++) {
992		while (ipq[i].next != &ipq[i]) {
993			ipstat.ips_fragdropped++;
994			ip_freef(ipq[i].next);
995		}
996	}
997	in_rtqdrain();
998}
999
1000/*
1001 * Do option processing on a datagram,
1002 * possibly discarding it if bad options are encountered,
1003 * or forwarding it if source-routed.
1004 * Returns 1 if packet has been forwarded/freed,
1005 * 0 if the packet should be processed further.
1006 */
1007static int
1008ip_dooptions(m)
1009	struct mbuf *m;
1010{
1011	register struct ip *ip = mtod(m, struct ip *);
1012	register u_char *cp;
1013	register struct ip_timestamp *ipt;
1014	register struct in_ifaddr *ia;
1015	int opt, optlen, cnt, off, code, type = ICMP_PARAMPROB, forward = 0;
1016	struct in_addr *sin, dst;
1017	n_time ntime;
1018
1019	dst = ip->ip_dst;
1020	cp = (u_char *)(ip + 1);
1021	cnt = (IP_VHL_HL(ip->ip_vhl) << 2) - sizeof (struct ip);
1022	for (; cnt > 0; cnt -= optlen, cp += optlen) {
1023		opt = cp[IPOPT_OPTVAL];
1024		if (opt == IPOPT_EOL)
1025			break;
1026		if (opt == IPOPT_NOP)
1027			optlen = 1;
1028		else {
1029			optlen = cp[IPOPT_OLEN];
1030			if (optlen <= 0 || optlen > cnt) {
1031				code = &cp[IPOPT_OLEN] - (u_char *)ip;
1032				goto bad;
1033			}
1034		}
1035		switch (opt) {
1036
1037		default:
1038			break;
1039
1040		/*
1041		 * Source routing with record.
1042		 * Find interface with current destination address.
1043		 * If none on this machine then drop if strictly routed,
1044		 * or do nothing if loosely routed.
1045		 * Record interface address and bring up next address
1046		 * component.  If strictly routed make sure next
1047		 * address is on directly accessible net.
1048		 */
1049		case IPOPT_LSRR:
1050		case IPOPT_SSRR:
1051			if ((off = cp[IPOPT_OFFSET]) < IPOPT_MINOFF) {
1052				code = &cp[IPOPT_OFFSET] - (u_char *)ip;
1053				goto bad;
1054			}
1055			ipaddr.sin_addr = ip->ip_dst;
1056			ia = (struct in_ifaddr *)
1057				ifa_ifwithaddr((struct sockaddr *)&ipaddr);
1058			if (ia == 0) {
1059				if (opt == IPOPT_SSRR) {
1060					type = ICMP_UNREACH;
1061					code = ICMP_UNREACH_SRCFAIL;
1062					goto bad;
1063				}
1064				if (!ip_dosourceroute)
1065					goto nosourcerouting;
1066				/*
1067				 * Loose routing, and not at next destination
1068				 * yet; nothing to do except forward.
1069				 */
1070				break;
1071			}
1072			off--;			/* 0 origin */
1073			if (off > optlen - sizeof(struct in_addr)) {
1074				/*
1075				 * End of source route.  Should be for us.
1076				 */
1077				if (!ip_acceptsourceroute)
1078					goto nosourcerouting;
1079				save_rte(cp, ip->ip_src);
1080				break;
1081			}
1082
1083			if (!ip_dosourceroute) {
1084				if (ipforwarding) {
1085					char buf[16]; /* aaa.bbb.ccc.ddd\0 */
1086					/*
1087					 * Acting as a router, so generate ICMP
1088					 */
1089nosourcerouting:
1090					strcpy(buf, inet_ntoa(ip->ip_dst));
1091					log(LOG_WARNING,
1092					    "attempted source route from %s to %s\n",
1093					    inet_ntoa(ip->ip_src), buf);
1094					type = ICMP_UNREACH;
1095					code = ICMP_UNREACH_SRCFAIL;
1096					goto bad;
1097				} else {
1098					/*
1099					 * Not acting as a router, so silently drop.
1100					 */
1101					ipstat.ips_cantforward++;
1102					m_freem(m);
1103					return (1);
1104				}
1105			}
1106
1107			/*
1108			 * locate outgoing interface
1109			 */
1110			(void)memcpy(&ipaddr.sin_addr, cp + off,
1111			    sizeof(ipaddr.sin_addr));
1112
1113			if (opt == IPOPT_SSRR) {
1114#define	INA	struct in_ifaddr *
1115#define	SA	struct sockaddr *
1116			    if ((ia = (INA)ifa_ifwithdstaddr((SA)&ipaddr)) == 0)
1117				ia = (INA)ifa_ifwithnet((SA)&ipaddr);
1118			} else
1119				ia = ip_rtaddr(ipaddr.sin_addr);
1120			if (ia == 0) {
1121				type = ICMP_UNREACH;
1122				code = ICMP_UNREACH_SRCFAIL;
1123				goto bad;
1124			}
1125			ip->ip_dst = ipaddr.sin_addr;
1126			(void)memcpy(cp + off, &(IA_SIN(ia)->sin_addr),
1127			    sizeof(struct in_addr));
1128			cp[IPOPT_OFFSET] += sizeof(struct in_addr);
1129			/*
1130			 * Let ip_intr's mcast routing check handle mcast pkts
1131			 */
1132			forward = !IN_MULTICAST(ntohl(ip->ip_dst.s_addr));
1133			break;
1134
1135		case IPOPT_RR:
1136			if ((off = cp[IPOPT_OFFSET]) < IPOPT_MINOFF) {
1137				code = &cp[IPOPT_OFFSET] - (u_char *)ip;
1138				goto bad;
1139			}
1140			/*
1141			 * If no space remains, ignore.
1142			 */
1143			off--;			/* 0 origin */
1144			if (off > optlen - sizeof(struct in_addr))
1145				break;
1146			(void)memcpy(&ipaddr.sin_addr, &ip->ip_dst,
1147			    sizeof(ipaddr.sin_addr));
1148			/*
1149			 * locate outgoing interface; if we're the destination,
1150			 * use the incoming interface (should be same).
1151			 */
1152			if ((ia = (INA)ifa_ifwithaddr((SA)&ipaddr)) == 0 &&
1153			    (ia = ip_rtaddr(ipaddr.sin_addr)) == 0) {
1154				type = ICMP_UNREACH;
1155				code = ICMP_UNREACH_HOST;
1156				goto bad;
1157			}
1158			(void)memcpy(cp + off, &(IA_SIN(ia)->sin_addr),
1159			    sizeof(struct in_addr));
1160			cp[IPOPT_OFFSET] += sizeof(struct in_addr);
1161			break;
1162
1163		case IPOPT_TS:
1164			code = cp - (u_char *)ip;
1165			ipt = (struct ip_timestamp *)cp;
1166			if (ipt->ipt_len < 5)
1167				goto bad;
1168			if (ipt->ipt_ptr > ipt->ipt_len - sizeof(int32_t)) {
1169				if (++ipt->ipt_oflw == 0)
1170					goto bad;
1171				break;
1172			}
1173			sin = (struct in_addr *)(cp + ipt->ipt_ptr - 1);
1174			switch (ipt->ipt_flg) {
1175
1176			case IPOPT_TS_TSONLY:
1177				break;
1178
1179			case IPOPT_TS_TSANDADDR:
1180				if (ipt->ipt_ptr - 1 + sizeof(n_time) +
1181				    sizeof(struct in_addr) > ipt->ipt_len)
1182					goto bad;
1183				ipaddr.sin_addr = dst;
1184				ia = (INA)ifaof_ifpforaddr((SA)&ipaddr,
1185							    m->m_pkthdr.rcvif);
1186				if (ia == 0)
1187					continue;
1188				(void)memcpy(sin, &IA_SIN(ia)->sin_addr,
1189				    sizeof(struct in_addr));
1190				ipt->ipt_ptr += sizeof(struct in_addr);
1191				break;
1192
1193			case IPOPT_TS_PRESPEC:
1194				if (ipt->ipt_ptr - 1 + sizeof(n_time) +
1195				    sizeof(struct in_addr) > ipt->ipt_len)
1196					goto bad;
1197				(void)memcpy(&ipaddr.sin_addr, sin,
1198				    sizeof(struct in_addr));
1199				if (ifa_ifwithaddr((SA)&ipaddr) == 0)
1200					continue;
1201				ipt->ipt_ptr += sizeof(struct in_addr);
1202				break;
1203
1204			default:
1205				goto bad;
1206			}
1207			ntime = iptime();
1208			(void)memcpy(cp + ipt->ipt_ptr - 1, &ntime,
1209			    sizeof(n_time));
1210			ipt->ipt_ptr += sizeof(n_time);
1211		}
1212	}
1213	if (forward && ipforwarding) {
1214		ip_forward(m, 1);
1215		return (1);
1216	}
1217	return (0);
1218bad:
1219	ip->ip_len -= IP_VHL_HL(ip->ip_vhl) << 2;   /* XXX icmp_error adds in hdr length */
1220	icmp_error(m, type, code, 0, 0);
1221	ipstat.ips_badoptions++;
1222	return (1);
1223}
1224
1225/*
1226 * Given address of next destination (final or next hop),
1227 * return internet address info of interface to be used to get there.
1228 */
1229static struct in_ifaddr *
1230ip_rtaddr(dst)
1231	 struct in_addr dst;
1232{
1233	register struct sockaddr_in *sin;
1234
1235	sin = (struct sockaddr_in *) &ipforward_rt.ro_dst;
1236
1237	if (ipforward_rt.ro_rt == 0 || dst.s_addr != sin->sin_addr.s_addr) {
1238		if (ipforward_rt.ro_rt) {
1239			RTFREE(ipforward_rt.ro_rt);
1240			ipforward_rt.ro_rt = 0;
1241		}
1242		sin->sin_family = AF_INET;
1243		sin->sin_len = sizeof(*sin);
1244		sin->sin_addr = dst;
1245
1246		rtalloc_ign(&ipforward_rt, RTF_PRCLONING);
1247	}
1248	if (ipforward_rt.ro_rt == 0)
1249		return ((struct in_ifaddr *)0);
1250	return ((struct in_ifaddr *) ipforward_rt.ro_rt->rt_ifa);
1251}
1252
1253/*
1254 * Save incoming source route for use in replies,
1255 * to be picked up later by ip_srcroute if the receiver is interested.
1256 */
1257void
1258save_rte(option, dst)
1259	u_char *option;
1260	struct in_addr dst;
1261{
1262	unsigned olen;
1263
1264	olen = option[IPOPT_OLEN];
1265#ifdef DIAGNOSTIC
1266	if (ipprintfs)
1267		printf("save_rte: olen %d\n", olen);
1268#endif
1269	if (olen > sizeof(ip_srcrt) - (1 + sizeof(dst)))
1270		return;
1271	bcopy(option, ip_srcrt.srcopt, olen);
1272	ip_nhops = (olen - IPOPT_OFFSET - 1) / sizeof(struct in_addr);
1273	ip_srcrt.dst = dst;
1274}
1275
1276/*
1277 * Retrieve incoming source route for use in replies,
1278 * in the same form used by setsockopt.
1279 * The first hop is placed before the options, will be removed later.
1280 */
1281struct mbuf *
1282ip_srcroute()
1283{
1284	register struct in_addr *p, *q;
1285	register struct mbuf *m;
1286
1287	if (ip_nhops == 0)
1288		return ((struct mbuf *)0);
1289	m = m_get(M_DONTWAIT, MT_HEADER);
1290	if (m == 0)
1291		return ((struct mbuf *)0);
1292
1293#define OPTSIZ	(sizeof(ip_srcrt.nop) + sizeof(ip_srcrt.srcopt))
1294
1295	/* length is (nhops+1)*sizeof(addr) + sizeof(nop + srcrt header) */
1296	m->m_len = ip_nhops * sizeof(struct in_addr) + sizeof(struct in_addr) +
1297	    OPTSIZ;
1298#ifdef DIAGNOSTIC
1299	if (ipprintfs)
1300		printf("ip_srcroute: nhops %d mlen %d", ip_nhops, m->m_len);
1301#endif
1302
1303	/*
1304	 * First save first hop for return route
1305	 */
1306	p = &ip_srcrt.route[ip_nhops - 1];
1307	*(mtod(m, struct in_addr *)) = *p--;
1308#ifdef DIAGNOSTIC
1309	if (ipprintfs)
1310		printf(" hops %lx", (u_long)ntohl(mtod(m, struct in_addr *)->s_addr));
1311#endif
1312
1313	/*
1314	 * Copy option fields and padding (nop) to mbuf.
1315	 */
1316	ip_srcrt.nop = IPOPT_NOP;
1317	ip_srcrt.srcopt[IPOPT_OFFSET] = IPOPT_MINOFF;
1318	(void)memcpy(mtod(m, caddr_t) + sizeof(struct in_addr),
1319	    &ip_srcrt.nop, OPTSIZ);
1320	q = (struct in_addr *)(mtod(m, caddr_t) +
1321	    sizeof(struct in_addr) + OPTSIZ);
1322#undef OPTSIZ
1323	/*
1324	 * Record return path as an IP source route,
1325	 * reversing the path (pointers are now aligned).
1326	 */
1327	while (p >= ip_srcrt.route) {
1328#ifdef DIAGNOSTIC
1329		if (ipprintfs)
1330			printf(" %lx", (u_long)ntohl(q->s_addr));
1331#endif
1332		*q++ = *p--;
1333	}
1334	/*
1335	 * Last hop goes to final destination.
1336	 */
1337	*q = ip_srcrt.dst;
1338#ifdef DIAGNOSTIC
1339	if (ipprintfs)
1340		printf(" %lx\n", (u_long)ntohl(q->s_addr));
1341#endif
1342	return (m);
1343}
1344
1345/*
1346 * Strip out IP options, at higher
1347 * level protocol in the kernel.
1348 * Second argument is buffer to which options
1349 * will be moved, and return value is their length.
1350 * XXX should be deleted; last arg currently ignored.
1351 */
1352void
1353ip_stripoptions(m, mopt)
1354	register struct mbuf *m;
1355	struct mbuf *mopt;
1356{
1357	register int i;
1358	struct ip *ip = mtod(m, struct ip *);
1359	register caddr_t opts;
1360	int olen;
1361
1362	olen = (IP_VHL_HL(ip->ip_vhl) << 2) - sizeof (struct ip);
1363	opts = (caddr_t)(ip + 1);
1364	i = m->m_len - (sizeof (struct ip) + olen);
1365	bcopy(opts + olen, opts, (unsigned)i);
1366	m->m_len -= olen;
1367	if (m->m_flags & M_PKTHDR)
1368		m->m_pkthdr.len -= olen;
1369	ip->ip_vhl = IP_MAKE_VHL(IPVERSION, sizeof(struct ip) >> 2);
1370}
1371
1372u_char inetctlerrmap[PRC_NCMDS] = {
1373	0,		0,		0,		0,
1374	0,		EMSGSIZE,	EHOSTDOWN,	EHOSTUNREACH,
1375	EHOSTUNREACH,	EHOSTUNREACH,	ECONNREFUSED,	ECONNREFUSED,
1376	EMSGSIZE,	EHOSTUNREACH,	0,		0,
1377	0,		0,		0,		0,
1378	ENOPROTOOPT
1379};
1380
1381/*
1382 * Forward a packet.  If some error occurs return the sender
1383 * an icmp packet.  Note we can't always generate a meaningful
1384 * icmp message because icmp doesn't have a large enough repertoire
1385 * of codes and types.
1386 *
1387 * If not forwarding, just drop the packet.  This could be confusing
1388 * if ipforwarding was zero but some routing protocol was advancing
1389 * us as a gateway to somewhere.  However, we must let the routing
1390 * protocol deal with that.
1391 *
1392 * The srcrt parameter indicates whether the packet is being forwarded
1393 * via a source route.
1394 */
1395static void
1396ip_forward(m, srcrt)
1397	struct mbuf *m;
1398	int srcrt;
1399{
1400	register struct ip *ip = mtod(m, struct ip *);
1401	register struct sockaddr_in *sin;
1402	register struct rtentry *rt;
1403	int error, type = 0, code = 0;
1404	struct mbuf *mcopy;
1405	n_long dest;
1406	struct ifnet *destifp;
1407
1408	dest = 0;
1409#ifdef DIAGNOSTIC
1410	if (ipprintfs)
1411		printf("forward: src %lx dst %lx ttl %x\n",
1412		    (u_long)ip->ip_src.s_addr, (u_long)ip->ip_dst.s_addr,
1413		    ip->ip_ttl);
1414#endif
1415
1416
1417	if (m->m_flags & (M_BCAST|M_MCAST) || in_canforward(ip->ip_dst) == 0) {
1418		ipstat.ips_cantforward++;
1419		m_freem(m);
1420		return;
1421	}
1422	HTONS(ip->ip_id);
1423#ifdef IPSTEALTH
1424	if (!ipstealth) {
1425#endif
1426		if (ip->ip_ttl <= IPTTLDEC) {
1427			icmp_error(m, ICMP_TIMXCEED, ICMP_TIMXCEED_INTRANS,
1428			    dest, 0);
1429			return;
1430		}
1431		ip->ip_ttl -= IPTTLDEC;
1432#ifdef IPSTEALTH
1433	}
1434#endif
1435
1436	sin = (struct sockaddr_in *)&ipforward_rt.ro_dst;
1437	if ((rt = ipforward_rt.ro_rt) == 0 ||
1438	    ip->ip_dst.s_addr != sin->sin_addr.s_addr) {
1439		if (ipforward_rt.ro_rt) {
1440			RTFREE(ipforward_rt.ro_rt);
1441			ipforward_rt.ro_rt = 0;
1442		}
1443		sin->sin_family = AF_INET;
1444		sin->sin_len = sizeof(*sin);
1445		sin->sin_addr = ip->ip_dst;
1446
1447		rtalloc_ign(&ipforward_rt, RTF_PRCLONING);
1448		if (ipforward_rt.ro_rt == 0) {
1449			icmp_error(m, ICMP_UNREACH, ICMP_UNREACH_HOST, dest, 0);
1450			return;
1451		}
1452		rt = ipforward_rt.ro_rt;
1453	}
1454
1455	/*
1456	 * Save at most 64 bytes of the packet in case
1457	 * we need to generate an ICMP message to the src.
1458	 */
1459	mcopy = m_copy(m, 0, imin((int)ip->ip_len, 64));
1460
1461	/*
1462	 * If forwarding packet using same interface that it came in on,
1463	 * perhaps should send a redirect to sender to shortcut a hop.
1464	 * Only send redirect if source is sending directly to us,
1465	 * and if packet was not source routed (or has any options).
1466	 * Also, don't send redirect if forwarding using a default route
1467	 * or a route modified by a redirect.
1468	 */
1469#define	satosin(sa)	((struct sockaddr_in *)(sa))
1470	if (rt->rt_ifp == m->m_pkthdr.rcvif &&
1471	    (rt->rt_flags & (RTF_DYNAMIC|RTF_MODIFIED)) == 0 &&
1472	    satosin(rt_key(rt))->sin_addr.s_addr != 0 &&
1473	    ipsendredirects && !srcrt) {
1474#define	RTA(rt)	((struct in_ifaddr *)(rt->rt_ifa))
1475		u_long src = ntohl(ip->ip_src.s_addr);
1476
1477		if (RTA(rt) &&
1478		    (src & RTA(rt)->ia_subnetmask) == RTA(rt)->ia_subnet) {
1479		    if (rt->rt_flags & RTF_GATEWAY)
1480			dest = satosin(rt->rt_gateway)->sin_addr.s_addr;
1481		    else
1482			dest = ip->ip_dst.s_addr;
1483		    /* Router requirements says to only send host redirects */
1484		    type = ICMP_REDIRECT;
1485		    code = ICMP_REDIRECT_HOST;
1486#ifdef DIAGNOSTIC
1487		    if (ipprintfs)
1488		        printf("redirect (%d) to %lx\n", code, (u_long)dest);
1489#endif
1490		}
1491	}
1492
1493	error = ip_output(m, (struct mbuf *)0, &ipforward_rt,
1494			  IP_FORWARDING, 0);
1495	if (error)
1496		ipstat.ips_cantforward++;
1497	else {
1498		ipstat.ips_forward++;
1499		if (type)
1500			ipstat.ips_redirectsent++;
1501		else {
1502			if (mcopy) {
1503				ipflow_create(&ipforward_rt, mcopy);
1504				m_freem(mcopy);
1505			}
1506			return;
1507		}
1508	}
1509	if (mcopy == NULL)
1510		return;
1511	destifp = NULL;
1512
1513	switch (error) {
1514
1515	case 0:				/* forwarded, but need redirect */
1516		/* type, code set above */
1517		break;
1518
1519	case ENETUNREACH:		/* shouldn't happen, checked above */
1520	case EHOSTUNREACH:
1521	case ENETDOWN:
1522	case EHOSTDOWN:
1523	default:
1524		type = ICMP_UNREACH;
1525		code = ICMP_UNREACH_HOST;
1526		break;
1527
1528	case EMSGSIZE:
1529		type = ICMP_UNREACH;
1530		code = ICMP_UNREACH_NEEDFRAG;
1531		if (ipforward_rt.ro_rt)
1532			destifp = ipforward_rt.ro_rt->rt_ifp;
1533		ipstat.ips_cantfrag++;
1534		break;
1535
1536	case ENOBUFS:
1537		type = ICMP_SOURCEQUENCH;
1538		code = 0;
1539		break;
1540	}
1541	icmp_error(mcopy, type, code, dest, destifp);
1542}
1543
1544void
1545ip_savecontrol(inp, mp, ip, m)
1546	register struct inpcb *inp;
1547	register struct mbuf **mp;
1548	register struct ip *ip;
1549	register struct mbuf *m;
1550{
1551	if (inp->inp_socket->so_options & SO_TIMESTAMP) {
1552		struct timeval tv;
1553
1554		microtime(&tv);
1555		*mp = sbcreatecontrol((caddr_t) &tv, sizeof(tv),
1556			SCM_TIMESTAMP, SOL_SOCKET);
1557		if (*mp)
1558			mp = &(*mp)->m_next;
1559	}
1560	if (inp->inp_flags & INP_RECVDSTADDR) {
1561		*mp = sbcreatecontrol((caddr_t) &ip->ip_dst,
1562		    sizeof(struct in_addr), IP_RECVDSTADDR, IPPROTO_IP);
1563		if (*mp)
1564			mp = &(*mp)->m_next;
1565	}
1566#ifdef notyet
1567	/* XXX
1568	 * Moving these out of udp_input() made them even more broken
1569	 * than they already were.
1570	 */
1571	/* options were tossed already */
1572	if (inp->inp_flags & INP_RECVOPTS) {
1573		*mp = sbcreatecontrol((caddr_t) opts_deleted_above,
1574		    sizeof(struct in_addr), IP_RECVOPTS, IPPROTO_IP);
1575		if (*mp)
1576			mp = &(*mp)->m_next;
1577	}
1578	/* ip_srcroute doesn't do what we want here, need to fix */
1579	if (inp->inp_flags & INP_RECVRETOPTS) {
1580		*mp = sbcreatecontrol((caddr_t) ip_srcroute(),
1581		    sizeof(struct in_addr), IP_RECVRETOPTS, IPPROTO_IP);
1582		if (*mp)
1583			mp = &(*mp)->m_next;
1584	}
1585#endif
1586	if (inp->inp_flags & INP_RECVIF) {
1587		struct ifnet *ifp;
1588		struct sdlbuf {
1589			struct sockaddr_dl sdl;
1590			u_char	pad[32];
1591		} sdlbuf;
1592		struct sockaddr_dl *sdp;
1593		struct sockaddr_dl *sdl2 = &sdlbuf.sdl;
1594
1595		if (((ifp = m->m_pkthdr.rcvif))
1596		&& ( ifp->if_index && (ifp->if_index <= if_index))) {
1597			sdp = (struct sockaddr_dl *)(ifnet_addrs
1598					[ifp->if_index - 1]->ifa_addr);
1599			/*
1600			 * Change our mind and don't try copy.
1601			 */
1602			if ((sdp->sdl_family != AF_LINK)
1603			|| (sdp->sdl_len > sizeof(sdlbuf))) {
1604				goto makedummy;
1605			}
1606			bcopy(sdp, sdl2, sdp->sdl_len);
1607		} else {
1608makedummy:
1609			sdl2->sdl_len
1610				= offsetof(struct sockaddr_dl, sdl_data[0]);
1611			sdl2->sdl_family = AF_LINK;
1612			sdl2->sdl_index = 0;
1613			sdl2->sdl_nlen = sdl2->sdl_alen = sdl2->sdl_slen = 0;
1614		}
1615		*mp = sbcreatecontrol((caddr_t) sdl2, sdl2->sdl_len,
1616			IP_RECVIF, IPPROTO_IP);
1617		if (*mp)
1618			mp = &(*mp)->m_next;
1619	}
1620}
1621
1622int
1623ip_rsvp_init(struct socket *so)
1624{
1625	if (so->so_type != SOCK_RAW ||
1626	    so->so_proto->pr_protocol != IPPROTO_RSVP)
1627	  return EOPNOTSUPP;
1628
1629	if (ip_rsvpd != NULL)
1630	  return EADDRINUSE;
1631
1632	ip_rsvpd = so;
1633	/*
1634	 * This may seem silly, but we need to be sure we don't over-increment
1635	 * the RSVP counter, in case something slips up.
1636	 */
1637	if (!ip_rsvp_on) {
1638		ip_rsvp_on = 1;
1639		rsvp_on++;
1640	}
1641
1642	return 0;
1643}
1644
1645int
1646ip_rsvp_done(void)
1647{
1648	ip_rsvpd = NULL;
1649	/*
1650	 * This may seem silly, but we need to be sure we don't over-decrement
1651	 * the RSVP counter, in case something slips up.
1652	 */
1653	if (ip_rsvp_on) {
1654		ip_rsvp_on = 0;
1655		rsvp_on--;
1656	}
1657	return 0;
1658}
1659