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