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