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