xref: /original-bsd/sys/netinet/ip_input.c (revision a95f03a8)
1 /*
2  * Copyright (c) 1982, 1986, 1988 Regents of the University of California.
3  * All rights reserved.
4  *
5  * %sccs.include.redist.c%
6  *
7  *	@(#)ip_input.c	7.23 (Berkeley) 10/11/92
8  */
9 
10 #include <sys/param.h>
11 #include <sys/systm.h>
12 #include <sys/malloc.h>
13 #include <sys/mbuf.h>
14 #include <sys/domain.h>
15 #include <sys/protosw.h>
16 #include <sys/socket.h>
17 #include <sys/errno.h>
18 #include <sys/time.h>
19 #include <sys/kernel.h>
20 
21 #include <net/if.h>
22 #include <net/route.h>
23 
24 #include <netinet/in.h>
25 #include <netinet/in_systm.h>
26 #include <netinet/ip.h>
27 #include <netinet/in_pcb.h>
28 #include <netinet/in_var.h>
29 #include <netinet/ip_var.h>
30 #include <netinet/ip_icmp.h>
31 
32 #ifndef	IPFORWARDING
33 #ifdef GATEWAY
34 #define	IPFORWARDING	1	/* forward IP packets not for us */
35 #else /* GATEWAY */
36 #define	IPFORWARDING	0	/* don't forward IP packets not for us */
37 #endif /* GATEWAY */
38 #endif /* IPFORWARDING */
39 #ifndef	IPSENDREDIRECTS
40 #define	IPSENDREDIRECTS	1
41 #endif
42 int	ipforwarding = IPFORWARDING;
43 int	ipsendredirects = IPSENDREDIRECTS;
44 #ifdef DIAGNOSTIC
45 int	ipprintfs = 0;
46 #endif
47 
48 extern	struct domain inetdomain;
49 extern	struct protosw inetsw[];
50 u_char	ip_protox[IPPROTO_MAX];
51 int	ipqmaxlen = IFQ_MAXLEN;
52 struct	in_ifaddr *in_ifaddr;			/* first inet address */
53 
54 /*
55  * We need to save the IP options in case a protocol wants to respond
56  * to an incoming packet over the same route if the packet got here
57  * using IP source routing.  This allows connection establishment and
58  * maintenance when the remote end is on a network that is not known
59  * to us.
60  */
61 int	ip_nhops = 0;
62 static	struct ip_srcrt {
63 	struct	in_addr dst;			/* final destination */
64 	char	nop;				/* one NOP to align */
65 	char	srcopt[IPOPT_OFFSET + 1];	/* OPTVAL, OLEN and OFFSET */
66 	struct	in_addr route[MAX_IPOPTLEN/sizeof(struct in_addr)];
67 } ip_srcrt;
68 
69 #ifdef GATEWAY
70 extern	int if_index;
71 u_long	*ip_ifmatrix;
72 #endif
73 
74 /*
75  * IP initialization: fill in IP protocol switch table.
76  * All protocols not implemented in kernel go to raw IP protocol handler.
77  */
78 ip_init()
79 {
80 	register struct protosw *pr;
81 	register int i;
82 
83 	pr = pffindproto(PF_INET, IPPROTO_RAW, SOCK_RAW);
84 	if (pr == 0)
85 		panic("ip_init");
86 	for (i = 0; i < IPPROTO_MAX; i++)
87 		ip_protox[i] = pr - inetsw;
88 	for (pr = inetdomain.dom_protosw;
89 	    pr < inetdomain.dom_protoswNPROTOSW; pr++)
90 		if (pr->pr_domain->dom_family == PF_INET &&
91 		    pr->pr_protocol && pr->pr_protocol != IPPROTO_RAW)
92 			ip_protox[pr->pr_protocol] = pr - inetsw;
93 	ipq.next = ipq.prev = &ipq;
94 	ip_id = time.tv_sec & 0xffff;
95 	ipintrq.ifq_maxlen = ipqmaxlen;
96 #ifdef GATEWAY
97 	i = (if_index + 1) * (if_index + 1) * sizeof (u_long);
98 	ip_ifmatrix = (u_long *) malloc(i, M_RTABLE, M_WAITOK);
99 	bzero((char *)ip_ifmatrix, i);
100 #endif
101 }
102 
103 struct	ip *ip_reass();
104 struct	sockaddr_in ipaddr = { sizeof(ipaddr), AF_INET };
105 struct	route ipforward_rt;
106 
107 /*
108  * Ip input routine.  Checksum and byte swap header.  If fragmented
109  * try to reassemble.  Process options.  Pass to next level.
110  */
111 ipintr()
112 {
113 	register struct ip *ip;
114 	register struct mbuf *m;
115 	register struct ipq *fp;
116 	register struct in_ifaddr *ia;
117 	int hlen, s;
118 
119 next:
120 	/*
121 	 * Get next datagram off input queue and get IP header
122 	 * in first mbuf.
123 	 */
124 	s = splimp();
125 	IF_DEQUEUE(&ipintrq, m);
126 	splx(s);
127 	if (m == 0)
128 		return;
129 #ifdef	DIAGNOSTIC
130 	if ((m->m_flags & M_PKTHDR) == 0)
131 		panic("ipintr no HDR");
132 #endif
133 	/*
134 	 * If no IP addresses have been set yet but the interfaces
135 	 * are receiving, can't do anything with incoming packets yet.
136 	 */
137 	if (in_ifaddr == NULL)
138 		goto bad;
139 	ipstat.ips_total++;
140 	if (m->m_len < sizeof (struct ip) &&
141 	    (m = m_pullup(m, sizeof (struct ip))) == 0) {
142 		ipstat.ips_toosmall++;
143 		goto next;
144 	}
145 	ip = mtod(m, struct ip *);
146 	hlen = ip->ip_hl << 2;
147 	if (hlen < sizeof(struct ip)) {	/* minimum header length */
148 		ipstat.ips_badhlen++;
149 		goto bad;
150 	}
151 	if (hlen > m->m_len) {
152 		if ((m = m_pullup(m, hlen)) == 0) {
153 			ipstat.ips_badhlen++;
154 			goto next;
155 		}
156 		ip = mtod(m, struct ip *);
157 	}
158 	if (ip->ip_sum = in_cksum(m, hlen)) {
159 		ipstat.ips_badsum++;
160 		goto bad;
161 	}
162 
163 	/*
164 	 * Convert fields to host representation.
165 	 */
166 	NTOHS(ip->ip_len);
167 	if (ip->ip_len < hlen) {
168 		ipstat.ips_badlen++;
169 		goto bad;
170 	}
171 	NTOHS(ip->ip_id);
172 	NTOHS(ip->ip_off);
173 
174 	/*
175 	 * Check that the amount of data in the buffers
176 	 * is as at least much as the IP header would have us expect.
177 	 * Trim mbufs if longer than we expect.
178 	 * Drop packet if shorter than we expect.
179 	 */
180 	if (m->m_pkthdr.len < ip->ip_len) {
181 		ipstat.ips_tooshort++;
182 		goto bad;
183 	}
184 	if (m->m_pkthdr.len > ip->ip_len) {
185 		if (m->m_len == m->m_pkthdr.len) {
186 			m->m_len = ip->ip_len;
187 			m->m_pkthdr.len = ip->ip_len;
188 		} else
189 			m_adj(m, ip->ip_len - m->m_pkthdr.len);
190 	}
191 
192 	/*
193 	 * Process options and, if not destined for us,
194 	 * ship it on.  ip_dooptions returns 1 when an
195 	 * error was detected (causing an icmp message
196 	 * to be sent and the original packet to be freed).
197 	 */
198 	ip_nhops = 0;		/* for source routed packets */
199 	if (hlen > sizeof (struct ip) && ip_dooptions(m))
200 		goto next;
201 
202 	/*
203 	 * Check our list of addresses, to see if the packet is for us.
204 	 */
205 	for (ia = in_ifaddr; ia; ia = ia->ia_next) {
206 #define	satosin(sa)	((struct sockaddr_in *)(sa))
207 
208 		if (IA_SIN(ia)->sin_addr.s_addr == ip->ip_dst.s_addr)
209 			goto ours;
210 		if (
211 #ifdef	DIRECTED_BROADCAST
212 		    ia->ia_ifp == m->m_pkthdr.rcvif &&
213 #endif
214 		    (ia->ia_ifp->if_flags & IFF_BROADCAST)) {
215 			u_long t;
216 
217 			if (satosin(&ia->ia_broadaddr)->sin_addr.s_addr ==
218 			    ip->ip_dst.s_addr)
219 				goto ours;
220 			if (ip->ip_dst.s_addr == ia->ia_netbroadcast.s_addr)
221 				goto ours;
222 			/*
223 			 * Look for all-0's host part (old broadcast addr),
224 			 * either for subnet or net.
225 			 */
226 			t = ntohl(ip->ip_dst.s_addr);
227 			if (t == ia->ia_subnet)
228 				goto ours;
229 			if (t == ia->ia_net)
230 				goto ours;
231 		}
232 	}
233 #ifdef MULTICAST
234 	if (IN_MULTICAST(ntohl(ip->ip_dst.s_addr))) {
235 		struct in_multi *inm;
236 #ifdef MROUTING
237 		extern struct socket *ip_mrouter;
238 
239 		if (ip_mrouter) {
240 			/*
241 			 * If we are acting as a multicast router, all
242 			 * incoming multicast packets are passed to the
243 			 * kernel-level multicast forwarding function.
244 			 * The packet is returned (relatively) intact; if
245 			 * ip_mforward() returns a non-zero value, the packet
246 			 * must be discarded, else it may be accepted below.
247 			 *
248 			 * (The IP ident field is put in the same byte order
249 			 * as expected when ip_mforward() is called from
250 			 * ip_output().)
251 			 */
252 			ip->ip_id = htons(ip->ip_id);
253 			if (ip_mforward(m, m->m_pkthdr.rcvif) != 0) {
254 				m_freem(m);
255 				goto next;
256 			}
257 			ip->ip_id = ntohs(ip->ip_id);
258 
259 			/*
260 			 * The process-level routing demon needs to receive
261 			 * all multicast IGMP packets, whether or not this
262 			 * host belongs to their destination groups.
263 			 */
264 			if (ip->ip_p == IPPROTO_IGMP)
265 				goto ours;
266 		}
267 #endif
268 		/*
269 		 * See if we belong to the destination multicast group on the
270 		 * arrival interface.
271 		 */
272 		IN_LOOKUP_MULTI(ip->ip_dst, m->m_pkthdr.rcvif, inm);
273 		if (inm == NULL) {
274 			m_freem(m);
275 			goto next;
276 		}
277 		goto ours;
278 	}
279 #endif
280 	if (ip->ip_dst.s_addr == (u_long)INADDR_BROADCAST)
281 		goto ours;
282 	if (ip->ip_dst.s_addr == INADDR_ANY)
283 		goto ours;
284 
285 	/*
286 	 * Not for us; forward if possible and desirable.
287 	 */
288 	if (ipforwarding == 0) {
289 		ipstat.ips_cantforward++;
290 		m_freem(m);
291 	} else
292 		ip_forward(m, 0);
293 	goto next;
294 
295 ours:
296 	/*
297 	 * If offset or IP_MF are set, must reassemble.
298 	 * Otherwise, nothing need be done.
299 	 * (We could look in the reassembly queue to see
300 	 * if the packet was previously fragmented,
301 	 * but it's not worth the time; just let them time out.)
302 	 */
303 	if (ip->ip_off &~ IP_DF) {
304 		if (m->m_flags & M_EXT) {		/* XXX */
305 			if ((m = m_pullup(m, sizeof (struct ip))) == 0) {
306 				ipstat.ips_toosmall++;
307 				goto next;
308 			}
309 			ip = mtod(m, struct ip *);
310 		}
311 		/*
312 		 * Look for queue of fragments
313 		 * of this datagram.
314 		 */
315 		for (fp = ipq.next; fp != &ipq; fp = fp->next)
316 			if (ip->ip_id == fp->ipq_id &&
317 			    ip->ip_src.s_addr == fp->ipq_src.s_addr &&
318 			    ip->ip_dst.s_addr == fp->ipq_dst.s_addr &&
319 			    ip->ip_p == fp->ipq_p)
320 				goto found;
321 		fp = 0;
322 found:
323 
324 		/*
325 		 * Adjust ip_len to not reflect header,
326 		 * set ip_mff if more fragments are expected,
327 		 * convert offset of this to bytes.
328 		 */
329 		ip->ip_len -= hlen;
330 		((struct ipasfrag *)ip)->ipf_mff = 0;
331 		if (ip->ip_off & IP_MF)
332 			((struct ipasfrag *)ip)->ipf_mff = 1;
333 		ip->ip_off <<= 3;
334 
335 		/*
336 		 * If datagram marked as having more fragments
337 		 * or if this is not the first fragment,
338 		 * attempt reassembly; if it succeeds, proceed.
339 		 */
340 		if (((struct ipasfrag *)ip)->ipf_mff || ip->ip_off) {
341 			ipstat.ips_fragments++;
342 			ip = ip_reass((struct ipasfrag *)ip, fp);
343 			if (ip == 0)
344 				goto next;
345 			else
346 				ipstat.ips_reassembled++;
347 			m = dtom(ip);
348 		} else
349 			if (fp)
350 				ip_freef(fp);
351 	} else
352 		ip->ip_len -= hlen;
353 
354 	/*
355 	 * Switch out to protocol's input routine.
356 	 */
357 	ipstat.ips_delivered++;
358 	(*inetsw[ip_protox[ip->ip_p]].pr_input)(m, hlen);
359 	goto next;
360 bad:
361 	m_freem(m);
362 	goto next;
363 }
364 
365 /*
366  * Take incoming datagram fragment and try to
367  * reassemble it into whole datagram.  If a chain for
368  * reassembly of this datagram already exists, then it
369  * is given as fp; otherwise have to make a chain.
370  */
371 struct ip *
372 ip_reass(ip, fp)
373 	register struct ipasfrag *ip;
374 	register struct ipq *fp;
375 {
376 	register struct mbuf *m = dtom(ip);
377 	register struct ipasfrag *q;
378 	struct mbuf *t;
379 	int hlen = ip->ip_hl << 2;
380 	int i, next;
381 
382 	/*
383 	 * Presence of header sizes in mbufs
384 	 * would confuse code below.
385 	 */
386 	m->m_data += hlen;
387 	m->m_len -= hlen;
388 
389 	/*
390 	 * If first fragment to arrive, create a reassembly queue.
391 	 */
392 	if (fp == 0) {
393 		if ((t = m_get(M_DONTWAIT, MT_FTABLE)) == NULL)
394 			goto dropfrag;
395 		fp = mtod(t, struct ipq *);
396 		insque(fp, &ipq);
397 		fp->ipq_ttl = IPFRAGTTL;
398 		fp->ipq_p = ip->ip_p;
399 		fp->ipq_id = ip->ip_id;
400 		fp->ipq_next = fp->ipq_prev = (struct ipasfrag *)fp;
401 		fp->ipq_src = ((struct ip *)ip)->ip_src;
402 		fp->ipq_dst = ((struct ip *)ip)->ip_dst;
403 		q = (struct ipasfrag *)fp;
404 		goto insert;
405 	}
406 
407 	/*
408 	 * Find a segment which begins after this one does.
409 	 */
410 	for (q = fp->ipq_next; q != (struct ipasfrag *)fp; q = q->ipf_next)
411 		if (q->ip_off > ip->ip_off)
412 			break;
413 
414 	/*
415 	 * If there is a preceding segment, it may provide some of
416 	 * our data already.  If so, drop the data from the incoming
417 	 * segment.  If it provides all of our data, drop us.
418 	 */
419 	if (q->ipf_prev != (struct ipasfrag *)fp) {
420 		i = q->ipf_prev->ip_off + q->ipf_prev->ip_len - ip->ip_off;
421 		if (i > 0) {
422 			if (i >= ip->ip_len)
423 				goto dropfrag;
424 			m_adj(dtom(ip), i);
425 			ip->ip_off += i;
426 			ip->ip_len -= i;
427 		}
428 	}
429 
430 	/*
431 	 * While we overlap succeeding segments trim them or,
432 	 * if they are completely covered, dequeue them.
433 	 */
434 	while (q != (struct ipasfrag *)fp && ip->ip_off + ip->ip_len > q->ip_off) {
435 		i = (ip->ip_off + ip->ip_len) - q->ip_off;
436 		if (i < q->ip_len) {
437 			q->ip_len -= i;
438 			q->ip_off += i;
439 			m_adj(dtom(q), i);
440 			break;
441 		}
442 		q = q->ipf_next;
443 		m_freem(dtom(q->ipf_prev));
444 		ip_deq(q->ipf_prev);
445 	}
446 
447 insert:
448 	/*
449 	 * Stick new segment in its place;
450 	 * check for complete reassembly.
451 	 */
452 	ip_enq(ip, q->ipf_prev);
453 	next = 0;
454 	for (q = fp->ipq_next; q != (struct ipasfrag *)fp; q = q->ipf_next) {
455 		if (q->ip_off != next)
456 			return (0);
457 		next += q->ip_len;
458 	}
459 	if (q->ipf_prev->ipf_mff)
460 		return (0);
461 
462 	/*
463 	 * Reassembly is complete; concatenate fragments.
464 	 */
465 	q = fp->ipq_next;
466 	m = dtom(q);
467 	t = m->m_next;
468 	m->m_next = 0;
469 	m_cat(m, t);
470 	q = q->ipf_next;
471 	while (q != (struct ipasfrag *)fp) {
472 		t = dtom(q);
473 		q = q->ipf_next;
474 		m_cat(m, t);
475 	}
476 
477 	/*
478 	 * Create header for new ip packet by
479 	 * modifying header of first packet;
480 	 * dequeue and discard fragment reassembly header.
481 	 * Make header visible.
482 	 */
483 	ip = fp->ipq_next;
484 	ip->ip_len = next;
485 	((struct ip *)ip)->ip_src = fp->ipq_src;
486 	((struct ip *)ip)->ip_dst = fp->ipq_dst;
487 	remque(fp);
488 	(void) m_free(dtom(fp));
489 	m = dtom(ip);
490 	m->m_len += (ip->ip_hl << 2);
491 	m->m_data -= (ip->ip_hl << 2);
492 	/* some debugging cruft by sklower, below, will go away soon */
493 	if (m->m_flags & M_PKTHDR) { /* XXX this should be done elsewhere */
494 		register int plen = 0;
495 		for (t = m; m; m = m->m_next)
496 			plen += m->m_len;
497 		t->m_pkthdr.len = plen;
498 	}
499 	return ((struct ip *)ip);
500 
501 dropfrag:
502 	ipstat.ips_fragdropped++;
503 	m_freem(m);
504 	return (0);
505 }
506 
507 /*
508  * Free a fragment reassembly header and all
509  * associated datagrams.
510  */
511 ip_freef(fp)
512 	struct ipq *fp;
513 {
514 	register struct ipasfrag *q, *p;
515 
516 	for (q = fp->ipq_next; q != (struct ipasfrag *)fp; q = p) {
517 		p = q->ipf_next;
518 		ip_deq(q);
519 		m_freem(dtom(q));
520 	}
521 	remque(fp);
522 	(void) m_free(dtom(fp));
523 }
524 
525 /*
526  * Put an ip fragment on a reassembly chain.
527  * Like insque, but pointers in middle of structure.
528  */
529 ip_enq(p, prev)
530 	register struct ipasfrag *p, *prev;
531 {
532 
533 	p->ipf_prev = prev;
534 	p->ipf_next = prev->ipf_next;
535 	prev->ipf_next->ipf_prev = p;
536 	prev->ipf_next = p;
537 }
538 
539 /*
540  * To ip_enq as remque is to insque.
541  */
542 ip_deq(p)
543 	register struct ipasfrag *p;
544 {
545 
546 	p->ipf_prev->ipf_next = p->ipf_next;
547 	p->ipf_next->ipf_prev = p->ipf_prev;
548 }
549 
550 /*
551  * IP timer processing;
552  * if a timer expires on a reassembly
553  * queue, discard it.
554  */
555 ip_slowtimo()
556 {
557 	register struct ipq *fp;
558 	int s = splnet();
559 
560 	fp = ipq.next;
561 	if (fp == 0) {
562 		splx(s);
563 		return;
564 	}
565 	while (fp != &ipq) {
566 		--fp->ipq_ttl;
567 		fp = fp->next;
568 		if (fp->prev->ipq_ttl == 0) {
569 			ipstat.ips_fragtimeout++;
570 			ip_freef(fp->prev);
571 		}
572 	}
573 	splx(s);
574 }
575 
576 /*
577  * Drain off all datagram fragments.
578  */
579 ip_drain()
580 {
581 
582 	while (ipq.next != &ipq) {
583 		ipstat.ips_fragdropped++;
584 		ip_freef(ipq.next);
585 	}
586 }
587 
588 extern struct in_ifaddr *ifptoia();
589 struct in_ifaddr *ip_rtaddr();
590 
591 /*
592  * Do option processing on a datagram,
593  * possibly discarding it if bad options are encountered,
594  * or forwarding it if source-routed.
595  * Returns 1 if packet has been forwarded/freed,
596  * 0 if the packet should be processed further.
597  */
598 ip_dooptions(m)
599 	struct mbuf *m;
600 {
601 	register struct ip *ip = mtod(m, struct ip *);
602 	register u_char *cp;
603 	register struct ip_timestamp *ipt;
604 	register struct in_ifaddr *ia;
605 	int opt, optlen, cnt, off, code, type = ICMP_PARAMPROB, forward = 0;
606 	struct in_addr *sin;
607 	n_time ntime;
608 
609 	cp = (u_char *)(ip + 1);
610 	cnt = (ip->ip_hl << 2) - sizeof (struct ip);
611 	for (; cnt > 0; cnt -= optlen, cp += optlen) {
612 		opt = cp[IPOPT_OPTVAL];
613 		if (opt == IPOPT_EOL)
614 			break;
615 		if (opt == IPOPT_NOP)
616 			optlen = 1;
617 		else {
618 			optlen = cp[IPOPT_OLEN];
619 			if (optlen <= 0 || optlen > cnt) {
620 				code = &cp[IPOPT_OLEN] - (u_char *)ip;
621 				goto bad;
622 			}
623 		}
624 		switch (opt) {
625 
626 		default:
627 			break;
628 
629 		/*
630 		 * Source routing with record.
631 		 * Find interface with current destination address.
632 		 * If none on this machine then drop if strictly routed,
633 		 * or do nothing if loosely routed.
634 		 * Record interface address and bring up next address
635 		 * component.  If strictly routed make sure next
636 		 * address is on directly accessible net.
637 		 */
638 		case IPOPT_LSRR:
639 		case IPOPT_SSRR:
640 			if ((off = cp[IPOPT_OFFSET]) < IPOPT_MINOFF) {
641 				code = &cp[IPOPT_OFFSET] - (u_char *)ip;
642 				goto bad;
643 			}
644 			ipaddr.sin_addr = ip->ip_dst;
645 			ia = (struct in_ifaddr *)
646 				ifa_ifwithaddr((struct sockaddr *)&ipaddr);
647 			if (ia == 0) {
648 				if (opt == IPOPT_SSRR) {
649 					type = ICMP_UNREACH;
650 					code = ICMP_UNREACH_SRCFAIL;
651 					goto bad;
652 				}
653 				/*
654 				 * Loose routing, and not at next destination
655 				 * yet; nothing to do except forward.
656 				 */
657 				break;
658 			}
659 			off--;			/* 0 origin */
660 			if (off > optlen - sizeof(struct in_addr)) {
661 				/*
662 				 * End of source route.  Should be for us.
663 				 */
664 				save_rte(cp, ip->ip_src);
665 				break;
666 			}
667 			/*
668 			 * locate outgoing interface
669 			 */
670 			bcopy((caddr_t)(cp + off), (caddr_t)&ipaddr.sin_addr,
671 			    sizeof(ipaddr.sin_addr));
672 			if (opt == IPOPT_SSRR) {
673 #define	INA	struct in_ifaddr *
674 #define	SA	struct sockaddr *
675 			    if ((ia = (INA)ifa_ifwithdstaddr((SA)&ipaddr)) == 0)
676 				ia = in_iaonnetof(in_netof(ipaddr.sin_addr));
677 			} else
678 				ia = ip_rtaddr(ipaddr.sin_addr);
679 			if (ia == 0) {
680 				type = ICMP_UNREACH;
681 				code = ICMP_UNREACH_SRCFAIL;
682 				goto bad;
683 			}
684 			ip->ip_dst = ipaddr.sin_addr;
685 			bcopy((caddr_t)&(IA_SIN(ia)->sin_addr),
686 			    (caddr_t)(cp + off), sizeof(struct in_addr));
687 			cp[IPOPT_OFFSET] += sizeof(struct in_addr);
688 			forward = 1;
689 			break;
690 
691 		case IPOPT_RR:
692 			if ((off = cp[IPOPT_OFFSET]) < IPOPT_MINOFF) {
693 				code = &cp[IPOPT_OFFSET] - (u_char *)ip;
694 				goto bad;
695 			}
696 			/*
697 			 * If no space remains, ignore.
698 			 */
699 			off--;			/* 0 origin */
700 			if (off > optlen - sizeof(struct in_addr))
701 				break;
702 			bcopy((caddr_t)(&ip->ip_dst), (caddr_t)&ipaddr.sin_addr,
703 			    sizeof(ipaddr.sin_addr));
704 			/*
705 			 * locate outgoing interface; if we're the destination,
706 			 * use the incoming interface (should be same).
707 			 */
708 			if ((ia = (INA)ifa_ifwithaddr((SA)&ipaddr)) == 0 &&
709 			    (ia = ip_rtaddr(ipaddr.sin_addr)) == 0) {
710 				type = ICMP_UNREACH;
711 				code = ICMP_UNREACH_HOST;
712 				goto bad;
713 			}
714 			bcopy((caddr_t)&(IA_SIN(ia)->sin_addr),
715 			    (caddr_t)(cp + off), sizeof(struct in_addr));
716 			cp[IPOPT_OFFSET] += sizeof(struct in_addr);
717 			break;
718 
719 		case IPOPT_TS:
720 			code = cp - (u_char *)ip;
721 			ipt = (struct ip_timestamp *)cp;
722 			if (ipt->ipt_len < 5)
723 				goto bad;
724 			if (ipt->ipt_ptr > ipt->ipt_len - sizeof (long)) {
725 				if (++ipt->ipt_oflw == 0)
726 					goto bad;
727 				break;
728 			}
729 			sin = (struct in_addr *)(cp + ipt->ipt_ptr - 1);
730 			switch (ipt->ipt_flg) {
731 
732 			case IPOPT_TS_TSONLY:
733 				break;
734 
735 			case IPOPT_TS_TSANDADDR:
736 				if (ipt->ipt_ptr + sizeof(n_time) +
737 				    sizeof(struct in_addr) > ipt->ipt_len)
738 					goto bad;
739 				ia = ifptoia(m->m_pkthdr.rcvif);
740 				bcopy((caddr_t)&IA_SIN(ia)->sin_addr,
741 				    (caddr_t)sin, sizeof(struct in_addr));
742 				ipt->ipt_ptr += sizeof(struct in_addr);
743 				break;
744 
745 			case IPOPT_TS_PRESPEC:
746 				if (ipt->ipt_ptr + sizeof(n_time) +
747 				    sizeof(struct in_addr) > ipt->ipt_len)
748 					goto bad;
749 				bcopy((caddr_t)sin, (caddr_t)&ipaddr.sin_addr,
750 				    sizeof(struct in_addr));
751 				if (ifa_ifwithaddr((SA)&ipaddr) == 0)
752 					continue;
753 				ipt->ipt_ptr += sizeof(struct in_addr);
754 				break;
755 
756 			default:
757 				goto bad;
758 			}
759 			ntime = iptime();
760 			bcopy((caddr_t)&ntime, (caddr_t)cp + ipt->ipt_ptr - 1,
761 			    sizeof(n_time));
762 			ipt->ipt_ptr += sizeof(n_time);
763 		}
764 	}
765 	if (forward) {
766 		ip_forward(m, 1);
767 		return (1);
768 	} else
769 		return (0);
770 bad:
771 	icmp_error(m, type, code);
772 	return (1);
773 }
774 
775 /*
776  * Given address of next destination (final or next hop),
777  * return internet address info of interface to be used to get there.
778  */
779 struct in_ifaddr *
780 ip_rtaddr(dst)
781 	 struct in_addr dst;
782 {
783 	register struct sockaddr_in *sin;
784 
785 	sin = (struct sockaddr_in *) &ipforward_rt.ro_dst;
786 
787 	if (ipforward_rt.ro_rt == 0 || dst.s_addr != sin->sin_addr.s_addr) {
788 		if (ipforward_rt.ro_rt) {
789 			RTFREE(ipforward_rt.ro_rt);
790 			ipforward_rt.ro_rt = 0;
791 		}
792 		sin->sin_family = AF_INET;
793 		sin->sin_len = sizeof(*sin);
794 		sin->sin_addr = dst;
795 
796 		rtalloc(&ipforward_rt);
797 	}
798 	if (ipforward_rt.ro_rt == 0)
799 		return ((struct in_ifaddr *)0);
800 	return ((struct in_ifaddr *) ipforward_rt.ro_rt->rt_ifa);
801 }
802 
803 /*
804  * Save incoming source route for use in replies,
805  * to be picked up later by ip_srcroute if the receiver is interested.
806  */
807 save_rte(option, dst)
808 	u_char *option;
809 	struct in_addr dst;
810 {
811 	unsigned olen;
812 
813 	olen = option[IPOPT_OLEN];
814 #ifdef DIAGNOSTIC
815 	if (ipprintfs)
816 		printf("save_rte: olen %d\n", olen);
817 #endif
818 	if (olen > sizeof(ip_srcrt) - (1 + sizeof(dst)))
819 		return;
820 	bcopy((caddr_t)option, (caddr_t)ip_srcrt.srcopt, olen);
821 	ip_nhops = (olen - IPOPT_OFFSET - 1) / sizeof(struct in_addr);
822 	ip_srcrt.dst = dst;
823 }
824 
825 /*
826  * Retrieve incoming source route for use in replies,
827  * in the same form used by setsockopt.
828  * The first hop is placed before the options, will be removed later.
829  */
830 struct mbuf *
831 ip_srcroute()
832 {
833 	register struct in_addr *p, *q;
834 	register struct mbuf *m;
835 
836 	if (ip_nhops == 0)
837 		return ((struct mbuf *)0);
838 	m = m_get(M_DONTWAIT, MT_SOOPTS);
839 	if (m == 0)
840 		return ((struct mbuf *)0);
841 
842 #define OPTSIZ	(sizeof(ip_srcrt.nop) + sizeof(ip_srcrt.srcopt))
843 
844 	/* length is (nhops+1)*sizeof(addr) + sizeof(nop + srcrt header) */
845 	m->m_len = ip_nhops * sizeof(struct in_addr) + sizeof(struct in_addr) +
846 	    OPTSIZ;
847 #ifdef DIAGNOSTIC
848 	if (ipprintfs)
849 		printf("ip_srcroute: nhops %d mlen %d", ip_nhops, m->m_len);
850 #endif
851 
852 	/*
853 	 * First save first hop for return route
854 	 */
855 	p = &ip_srcrt.route[ip_nhops - 1];
856 	*(mtod(m, struct in_addr *)) = *p--;
857 #ifdef DIAGNOSTIC
858 	if (ipprintfs)
859 		printf(" hops %lx", ntohl(mtod(m, struct in_addr *)->s_addr));
860 #endif
861 
862 	/*
863 	 * Copy option fields and padding (nop) to mbuf.
864 	 */
865 	ip_srcrt.nop = IPOPT_NOP;
866 	ip_srcrt.srcopt[IPOPT_OFFSET] = IPOPT_MINOFF;
867 	bcopy((caddr_t)&ip_srcrt.nop,
868 	    mtod(m, caddr_t) + sizeof(struct in_addr), OPTSIZ);
869 	q = (struct in_addr *)(mtod(m, caddr_t) +
870 	    sizeof(struct in_addr) + OPTSIZ);
871 #undef OPTSIZ
872 	/*
873 	 * Record return path as an IP source route,
874 	 * reversing the path (pointers are now aligned).
875 	 */
876 	while (p >= ip_srcrt.route) {
877 #ifdef DIAGNOSTIC
878 		if (ipprintfs)
879 			printf(" %lx", ntohl(q->s_addr));
880 #endif
881 		*q++ = *p--;
882 	}
883 	/*
884 	 * Last hop goes to final destination.
885 	 */
886 	*q = ip_srcrt.dst;
887 #ifdef DIAGNOSTIC
888 	if (ipprintfs)
889 		printf(" %lx\n", ntohl(q->s_addr));
890 #endif
891 	return (m);
892 }
893 
894 /*
895  * Strip out IP options, at higher
896  * level protocol in the kernel.
897  * Second argument is buffer to which options
898  * will be moved, and return value is their length.
899  * XXX should be deleted; last arg currently ignored.
900  */
901 ip_stripoptions(m, mopt)
902 	register struct mbuf *m;
903 	struct mbuf *mopt;
904 {
905 	register int i;
906 	struct ip *ip = mtod(m, struct ip *);
907 	register caddr_t opts;
908 	int olen;
909 
910 	olen = (ip->ip_hl<<2) - sizeof (struct ip);
911 	opts = (caddr_t)(ip + 1);
912 	i = m->m_len - (sizeof (struct ip) + olen);
913 	bcopy(opts  + olen, opts, (unsigned)i);
914 	m->m_len -= olen;
915 	if (m->m_flags & M_PKTHDR)
916 		m->m_pkthdr.len -= olen;
917 	ip->ip_hl = sizeof(struct ip) >> 2;
918 }
919 
920 u_char inetctlerrmap[PRC_NCMDS] = {
921 	0,		0,		0,		0,
922 	0,		EMSGSIZE,	EHOSTDOWN,	EHOSTUNREACH,
923 	EHOSTUNREACH,	EHOSTUNREACH,	ECONNREFUSED,	ECONNREFUSED,
924 	EMSGSIZE,	EHOSTUNREACH,	0,		0,
925 	0,		0,		0,		0,
926 	ENOPROTOOPT
927 };
928 
929 /*
930  * Forward a packet.  If some error occurs return the sender
931  * an icmp packet.  Note we can't always generate a meaningful
932  * icmp message because icmp doesn't have a large enough repertoire
933  * of codes and types.
934  *
935  * If not forwarding, just drop the packet.  This could be confusing
936  * if ipforwarding was zero but some routing protocol was advancing
937  * us as a gateway to somewhere.  However, we must let the routing
938  * protocol deal with that.
939  *
940  * The srcrt parameter indicates whether the packet is being forwarded
941  * via a source route.
942  */
943 ip_forward(m, srcrt)
944 	struct mbuf *m;
945 	int srcrt;
946 {
947 	register struct ip *ip = mtod(m, struct ip *);
948 	register struct sockaddr_in *sin;
949 	register struct rtentry *rt;
950 	int error, type = 0, code;
951 	struct mbuf *mcopy;
952 	struct in_addr dest;
953 
954 	dest.s_addr = 0;
955 #ifdef DIAGNOSTIC
956 	if (ipprintfs)
957 		printf("forward: src %x dst %x ttl %x\n", ip->ip_src,
958 			ip->ip_dst, ip->ip_ttl);
959 #endif
960 	if (m->m_flags & M_BCAST || in_canforward(ip->ip_dst) == 0) {
961 		ipstat.ips_cantforward++;
962 		m_freem(m);
963 		return;
964 	}
965 	HTONS(ip->ip_id);
966 	if (ip->ip_ttl <= IPTTLDEC) {
967 		icmp_error(m, ICMP_TIMXCEED, ICMP_TIMXCEED_INTRANS, dest);
968 		return;
969 	}
970 	ip->ip_ttl -= IPTTLDEC;
971 
972 	sin = (struct sockaddr_in *)&ipforward_rt.ro_dst;
973 	if ((rt = ipforward_rt.ro_rt) == 0 ||
974 	    ip->ip_dst.s_addr != sin->sin_addr.s_addr) {
975 		if (ipforward_rt.ro_rt) {
976 			RTFREE(ipforward_rt.ro_rt);
977 			ipforward_rt.ro_rt = 0;
978 		}
979 		sin->sin_family = AF_INET;
980 		sin->sin_len = sizeof(*sin);
981 		sin->sin_addr = ip->ip_dst;
982 
983 		rtalloc(&ipforward_rt);
984 		if (ipforward_rt.ro_rt == 0) {
985 			icmp_error(m, ICMP_UNREACH, ICMP_UNREACH_HOST, dest);
986 			return;
987 		}
988 		rt = ipforward_rt.ro_rt;
989 	}
990 
991 	/*
992 	 * Save at most 64 bytes of the packet in case
993 	 * we need to generate an ICMP message to the src.
994 	 */
995 	mcopy = m_copy(m, 0, imin((int)ip->ip_len, 64));
996 
997 #ifdef GATEWAY
998 	ip_ifmatrix[rt->rt_ifp->if_index +
999 	     if_index * m->m_pkthdr.rcvif->if_index]++;
1000 #endif
1001 	/*
1002 	 * If forwarding packet using same interface that it came in on,
1003 	 * perhaps should send a redirect to sender to shortcut a hop.
1004 	 * Only send redirect if source is sending directly to us,
1005 	 * and if packet was not source routed (or has any options).
1006 	 * Also, don't send redirect if forwarding using a default route
1007 	 * or a route modified by a redirect.
1008 	 */
1009 #define	satosin(sa)	((struct sockaddr_in *)(sa))
1010 	if (rt->rt_ifp == m->m_pkthdr.rcvif &&
1011 	    (rt->rt_flags & (RTF_DYNAMIC|RTF_MODIFIED)) == 0 &&
1012 	    satosin(rt_key(rt))->sin_addr.s_addr != 0 &&
1013 	    ipsendredirects && !srcrt) {
1014 #define	RTA(rt)	((struct in_ifaddr *)(rt->rt_ifa))
1015 		u_long src = ntohl(ip->ip_src.s_addr);
1016 		u_long dst = ntohl(ip->ip_dst.s_addr);
1017 
1018 		if (RTA(rt) &&
1019 		    (src & RTA(rt)->ia_subnetmask) == RTA(rt)->ia_subnet) {
1020 		    if (rt->rt_flags & RTF_GATEWAY)
1021 			dest = satosin(rt->rt_gateway)->sin_addr;
1022 		    else
1023 			dest = ip->ip_dst;
1024 		    /*
1025 		     * If the destination is reached by a route to host,
1026 		     * is on a subnet of a local net, or is directly
1027 		     * on the attached net (!), use host redirect.
1028 		     * (We may be the correct first hop for other subnets.)
1029 		     */
1030 		    type = ICMP_REDIRECT;
1031 		    if ((rt->rt_flags & RTF_HOST) ||
1032 		        (rt->rt_flags & RTF_GATEWAY) == 0)
1033 			    code = ICMP_REDIRECT_HOST;
1034 		    else if (RTA(rt)->ia_subnetmask != RTA(rt)->ia_netmask &&
1035 		        (dst & RTA(rt)->ia_netmask) ==  RTA(rt)->ia_net)
1036 			    code = ICMP_REDIRECT_HOST;
1037 		    else
1038 			    code = ICMP_REDIRECT_NET;
1039 #ifdef DIAGNOSTIC
1040 		    if (ipprintfs)
1041 		        printf("redirect (%d) to %x\n", code, dest.s_addr);
1042 #endif
1043 		}
1044 	}
1045 
1046 	error = ip_output(m, (struct mbuf *)0, &ipforward_rt, IP_FORWARDING);
1047 	if (error)
1048 		ipstat.ips_cantforward++;
1049 	else {
1050 		ipstat.ips_forward++;
1051 		if (type)
1052 			ipstat.ips_redirectsent++;
1053 		else {
1054 			if (mcopy)
1055 				m_freem(mcopy);
1056 			return;
1057 		}
1058 	}
1059 	if (mcopy == NULL)
1060 		return;
1061 	switch (error) {
1062 
1063 	case 0:				/* forwarded, but need redirect */
1064 		/* type, code set above */
1065 		break;
1066 
1067 	case ENETUNREACH:		/* shouldn't happen, checked above */
1068 	case EHOSTUNREACH:
1069 	case ENETDOWN:
1070 	case EHOSTDOWN:
1071 	default:
1072 		type = ICMP_UNREACH;
1073 		code = ICMP_UNREACH_HOST;
1074 		break;
1075 
1076 	case EMSGSIZE:
1077 		type = ICMP_UNREACH;
1078 		code = ICMP_UNREACH_NEEDFRAG;
1079 		ipstat.ips_cantfrag++;
1080 		break;
1081 
1082 	case ENOBUFS:
1083 		type = ICMP_SOURCEQUENCH;
1084 		code = 0;
1085 		break;
1086 	}
1087 	icmp_error(mcopy, type, code, dest);
1088 }
1089