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