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