Home | History | Annotate | Line # | Download | only in netinet
ip_output.c revision 1.83.2.8
      1 /*	$NetBSD: ip_output.c,v 1.83.2.8 2002/01/11 23:39:46 nathanw Exp $	*/
      2 
      3 /*
      4  * Copyright (C) 1995, 1996, 1997, and 1998 WIDE Project.
      5  * All rights reserved.
      6  *
      7  * Redistribution and use in source and binary forms, with or without
      8  * modification, are permitted provided that the following conditions
      9  * are met:
     10  * 1. Redistributions of source code must retain the above copyright
     11  *    notice, this list of conditions and the following disclaimer.
     12  * 2. Redistributions in binary form must reproduce the above copyright
     13  *    notice, this list of conditions and the following disclaimer in the
     14  *    documentation and/or other materials provided with the distribution.
     15  * 3. Neither the name of the project nor the names of its contributors
     16  *    may be used to endorse or promote products derived from this software
     17  *    without specific prior written permission.
     18  *
     19  * THIS SOFTWARE IS PROVIDED BY THE PROJECT AND CONTRIBUTORS ``AS IS'' AND
     20  * ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
     21  * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE
     22  * ARE DISCLAIMED.  IN NO EVENT SHALL THE PROJECT OR CONTRIBUTORS BE LIABLE
     23  * FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL
     24  * DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS
     25  * OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION)
     26  * HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT
     27  * LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY
     28  * OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF
     29  * SUCH DAMAGE.
     30  */
     31 
     32 /*-
     33  * Copyright (c) 1998 The NetBSD Foundation, Inc.
     34  * All rights reserved.
     35  *
     36  * This code is derived from software contributed to The NetBSD Foundation
     37  * by Public Access Networks Corporation ("Panix").  It was developed under
     38  * contract to Panix by Eric Haszlakiewicz and Thor Lancelot Simon.
     39  *
     40  * Redistribution and use in source and binary forms, with or without
     41  * modification, are permitted provided that the following conditions
     42  * are met:
     43  * 1. Redistributions of source code must retain the above copyright
     44  *    notice, this list of conditions and the following disclaimer.
     45  * 2. Redistributions in binary form must reproduce the above copyright
     46  *    notice, this list of conditions and the following disclaimer in the
     47  *    documentation and/or other materials provided with the distribution.
     48  * 3. All advertising materials mentioning features or use of this software
     49  *    must display the following acknowledgement:
     50  *	This product includes software developed by the NetBSD
     51  *	Foundation, Inc. and its contributors.
     52  * 4. Neither the name of The NetBSD Foundation nor the names of its
     53  *    contributors may be used to endorse or promote products derived
     54  *    from this software without specific prior written permission.
     55  *
     56  * THIS SOFTWARE IS PROVIDED BY THE NETBSD FOUNDATION, INC. AND CONTRIBUTORS
     57  * ``AS IS'' AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED
     58  * TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR
     59  * PURPOSE ARE DISCLAIMED.  IN NO EVENT SHALL THE FOUNDATION OR CONTRIBUTORS
     60  * BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR
     61  * CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF
     62  * SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS
     63  * INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN
     64  * CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE)
     65  * ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE
     66  * POSSIBILITY OF SUCH DAMAGE.
     67  */
     68 
     69 /*
     70  * Copyright (c) 1982, 1986, 1988, 1990, 1993
     71  *	The Regents of the University of California.  All rights reserved.
     72  *
     73  * Redistribution and use in source and binary forms, with or without
     74  * modification, are permitted provided that the following conditions
     75  * are met:
     76  * 1. Redistributions of source code must retain the above copyright
     77  *    notice, this list of conditions and the following disclaimer.
     78  * 2. Redistributions in binary form must reproduce the above copyright
     79  *    notice, this list of conditions and the following disclaimer in the
     80  *    documentation and/or other materials provided with the distribution.
     81  * 3. All advertising materials mentioning features or use of this software
     82  *    must display the following acknowledgement:
     83  *	This product includes software developed by the University of
     84  *	California, Berkeley and its contributors.
     85  * 4. Neither the name of the University nor the names of its contributors
     86  *    may be used to endorse or promote products derived from this software
     87  *    without specific prior written permission.
     88  *
     89  * THIS SOFTWARE IS PROVIDED BY THE REGENTS AND CONTRIBUTORS ``AS IS'' AND
     90  * ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
     91  * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE
     92  * ARE DISCLAIMED.  IN NO EVENT SHALL THE REGENTS OR CONTRIBUTORS BE LIABLE
     93  * FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL
     94  * DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS
     95  * OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION)
     96  * HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT
     97  * LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY
     98  * OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF
     99  * SUCH DAMAGE.
    100  *
    101  *	@(#)ip_output.c	8.3 (Berkeley) 1/21/94
    102  */
    103 
    104 #include <sys/cdefs.h>
    105 __KERNEL_RCSID(0, "$NetBSD: ip_output.c,v 1.83.2.8 2002/01/11 23:39:46 nathanw Exp $");
    106 
    107 #include "opt_pfil_hooks.h"
    108 #include "opt_ipsec.h"
    109 #include "opt_mrouting.h"
    110 
    111 #include <sys/param.h>
    112 #include <sys/malloc.h>
    113 #include <sys/mbuf.h>
    114 #include <sys/errno.h>
    115 #include <sys/protosw.h>
    116 #include <sys/socket.h>
    117 #include <sys/socketvar.h>
    118 #include <sys/systm.h>
    119 #include <sys/lwp.h>
    120 #include <sys/proc.h>
    121 
    122 #include <net/if.h>
    123 #include <net/route.h>
    124 #include <net/pfil.h>
    125 
    126 #include <netinet/in.h>
    127 #include <netinet/in_systm.h>
    128 #include <netinet/ip.h>
    129 #include <netinet/in_pcb.h>
    130 #include <netinet/in_var.h>
    131 #include <netinet/ip_var.h>
    132 
    133 #ifdef MROUTING
    134 #include <netinet/ip_mroute.h>
    135 #endif
    136 
    137 #include <machine/stdarg.h>
    138 
    139 #ifdef IPSEC
    140 #include <netinet6/ipsec.h>
    141 #include <netkey/key.h>
    142 #include <netkey/key_debug.h>
    143 #endif /*IPSEC*/
    144 
    145 static struct mbuf *ip_insertoptions __P((struct mbuf *, struct mbuf *, int *));
    146 static struct ifnet *ip_multicast_if __P((struct in_addr *, int *));
    147 static void ip_mloopback
    148 	__P((struct ifnet *, struct mbuf *, struct sockaddr_in *));
    149 
    150 #ifdef PFIL_HOOKS
    151 extern struct pfil_head inet_pfil_hook;			/* XXX */
    152 #endif
    153 
    154 /*
    155  * IP output.  The packet in mbuf chain m contains a skeletal IP
    156  * header (with len, off, ttl, proto, tos, src, dst).
    157  * The mbuf chain containing the packet will be freed.
    158  * The mbuf opt, if present, will not be freed.
    159  */
    160 int
    161 #if __STDC__
    162 ip_output(struct mbuf *m0, ...)
    163 #else
    164 ip_output(m0, va_alist)
    165 	struct mbuf *m0;
    166 	va_dcl
    167 #endif
    168 {
    169 	struct ip *ip, *mhip;
    170 	struct ifnet *ifp;
    171 	struct mbuf *m = m0;
    172 	int hlen = sizeof (struct ip);
    173 	int len, off, error = 0;
    174 	struct route iproute;
    175 	struct sockaddr_in *dst;
    176 	struct in_ifaddr *ia;
    177 	struct mbuf *opt;
    178 	struct route *ro;
    179 	int flags, sw_csum;
    180 	int *mtu_p;
    181 	int mtu;
    182 	struct ip_moptions *imo;
    183 	va_list ap;
    184 #ifdef IPSEC
    185 	struct socket *so;
    186 	struct secpolicy *sp = NULL;
    187 #endif /*IPSEC*/
    188 	u_int16_t ip_len;
    189 
    190 	va_start(ap, m0);
    191 	opt = va_arg(ap, struct mbuf *);
    192 	ro = va_arg(ap, struct route *);
    193 	flags = va_arg(ap, int);
    194 	imo = va_arg(ap, struct ip_moptions *);
    195 	if (flags & IP_RETURNMTU)
    196 		mtu_p = va_arg(ap, int *);
    197 	else
    198 		mtu_p = NULL;
    199 	va_end(ap);
    200 
    201 #ifdef IPSEC
    202 	so = ipsec_getsocket(m);
    203 	(void)ipsec_setsocket(m, NULL);
    204 #endif /*IPSEC*/
    205 
    206 #ifdef	DIAGNOSTIC
    207 	if ((m->m_flags & M_PKTHDR) == 0)
    208 		panic("ip_output no HDR");
    209 #endif
    210 	if (opt) {
    211 		m = ip_insertoptions(m, opt, &len);
    212 		hlen = len;
    213 	}
    214 	ip = mtod(m, struct ip *);
    215 	/*
    216 	 * Fill in IP header.
    217 	 */
    218 	if ((flags & (IP_FORWARDING|IP_RAWOUTPUT)) == 0) {
    219 		ip->ip_v = IPVERSION;
    220 		ip->ip_off = 0;
    221 		ip->ip_id = htons(ip_id++);
    222 		ip->ip_hl = hlen >> 2;
    223 		ipstat.ips_localout++;
    224 	} else {
    225 		hlen = ip->ip_hl << 2;
    226 	}
    227 	/*
    228 	 * Route packet.
    229 	 */
    230 	if (ro == 0) {
    231 		ro = &iproute;
    232 		bzero((caddr_t)ro, sizeof (*ro));
    233 	}
    234 	dst = satosin(&ro->ro_dst);
    235 	/*
    236 	 * If there is a cached route,
    237 	 * check that it is to the same destination
    238 	 * and is still up.  If not, free it and try again.
    239 	 */
    240 	if (ro->ro_rt && ((ro->ro_rt->rt_flags & RTF_UP) == 0 ||
    241 	    !in_hosteq(dst->sin_addr, ip->ip_dst))) {
    242 		RTFREE(ro->ro_rt);
    243 		ro->ro_rt = (struct rtentry *)0;
    244 	}
    245 	if (ro->ro_rt == 0) {
    246 		dst->sin_family = AF_INET;
    247 		dst->sin_len = sizeof(*dst);
    248 		dst->sin_addr = ip->ip_dst;
    249 	}
    250 	/*
    251 	 * If routing to interface only,
    252 	 * short circuit routing lookup.
    253 	 */
    254 	if (flags & IP_ROUTETOIF) {
    255 		if ((ia = ifatoia(ifa_ifwithladdr(sintosa(dst)))) == 0) {
    256 			ipstat.ips_noroute++;
    257 			error = ENETUNREACH;
    258 			goto bad;
    259 		}
    260 		ifp = ia->ia_ifp;
    261 		mtu = ifp->if_mtu;
    262 		ip->ip_ttl = 1;
    263 	} else {
    264 		if (ro->ro_rt == 0)
    265 			rtalloc(ro);
    266 		if (ro->ro_rt == 0) {
    267 			ipstat.ips_noroute++;
    268 			error = EHOSTUNREACH;
    269 			goto bad;
    270 		}
    271 		ia = ifatoia(ro->ro_rt->rt_ifa);
    272 		ifp = ro->ro_rt->rt_ifp;
    273 		if ((mtu = ro->ro_rt->rt_rmx.rmx_mtu) == 0)
    274 			mtu = ifp->if_mtu;
    275 		ro->ro_rt->rt_use++;
    276 		if (ro->ro_rt->rt_flags & RTF_GATEWAY)
    277 			dst = satosin(ro->ro_rt->rt_gateway);
    278 	}
    279 	if (IN_MULTICAST(ip->ip_dst.s_addr) ||
    280 	    (ip->ip_dst.s_addr == INADDR_BROADCAST)) {
    281 		struct in_multi *inm;
    282 
    283 		m->m_flags |= (ip->ip_dst.s_addr == INADDR_BROADCAST) ?
    284 			M_BCAST : M_MCAST;
    285 		/*
    286 		 * IP destination address is multicast.  Make sure "dst"
    287 		 * still points to the address in "ro".  (It may have been
    288 		 * changed to point to a gateway address, above.)
    289 		 */
    290 		dst = satosin(&ro->ro_dst);
    291 		/*
    292 		 * See if the caller provided any multicast options
    293 		 */
    294 		if (imo != NULL) {
    295 			ip->ip_ttl = imo->imo_multicast_ttl;
    296 			if (imo->imo_multicast_ifp != NULL) {
    297 				ifp = imo->imo_multicast_ifp;
    298 				mtu = ifp->if_mtu;
    299 			}
    300 		} else
    301 			ip->ip_ttl = IP_DEFAULT_MULTICAST_TTL;
    302 		/*
    303 		 * Confirm that the outgoing interface supports multicast.
    304 		 */
    305 		if (((m->m_flags & M_MCAST) &&
    306 		     (ifp->if_flags & IFF_MULTICAST) == 0) ||
    307 		    ((m->m_flags & M_BCAST) &&
    308 		     (ifp->if_flags & IFF_BROADCAST) == 0))  {
    309 			ipstat.ips_noroute++;
    310 			error = ENETUNREACH;
    311 			goto bad;
    312 		}
    313 		/*
    314 		 * If source address not specified yet, use an address
    315 		 * of outgoing interface.
    316 		 */
    317 		if (in_nullhost(ip->ip_src)) {
    318 			struct in_ifaddr *ia;
    319 
    320 			IFP_TO_IA(ifp, ia);
    321 			if (!ia) {
    322 				error = EADDRNOTAVAIL;
    323 				goto bad;
    324 			}
    325 			ip->ip_src = ia->ia_addr.sin_addr;
    326 		}
    327 
    328 		IN_LOOKUP_MULTI(ip->ip_dst, ifp, inm);
    329 		if (inm != NULL &&
    330 		   (imo == NULL || imo->imo_multicast_loop)) {
    331 			/*
    332 			 * If we belong to the destination multicast group
    333 			 * on the outgoing interface, and the caller did not
    334 			 * forbid loopback, loop back a copy.
    335 			 */
    336 			ip_mloopback(ifp, m, dst);
    337 		}
    338 #ifdef MROUTING
    339 		else {
    340 			/*
    341 			 * If we are acting as a multicast router, perform
    342 			 * multicast forwarding as if the packet had just
    343 			 * arrived on the interface to which we are about
    344 			 * to send.  The multicast forwarding function
    345 			 * recursively calls this function, using the
    346 			 * IP_FORWARDING flag to prevent infinite recursion.
    347 			 *
    348 			 * Multicasts that are looped back by ip_mloopback(),
    349 			 * above, will be forwarded by the ip_input() routine,
    350 			 * if necessary.
    351 			 */
    352 			extern struct socket *ip_mrouter;
    353 
    354 			if (ip_mrouter && (flags & IP_FORWARDING) == 0) {
    355 				if (ip_mforward(m, ifp) != 0) {
    356 					m_freem(m);
    357 					goto done;
    358 				}
    359 			}
    360 		}
    361 #endif
    362 		/*
    363 		 * Multicasts with a time-to-live of zero may be looped-
    364 		 * back, above, but must not be transmitted on a network.
    365 		 * Also, multicasts addressed to the loopback interface
    366 		 * are not sent -- the above call to ip_mloopback() will
    367 		 * loop back a copy if this host actually belongs to the
    368 		 * destination group on the loopback interface.
    369 		 */
    370 		if (ip->ip_ttl == 0 || (ifp->if_flags & IFF_LOOPBACK) != 0) {
    371 			m_freem(m);
    372 			goto done;
    373 		}
    374 
    375 		goto sendit;
    376 	}
    377 #ifndef notdef
    378 	/*
    379 	 * If source address not specified yet, use address
    380 	 * of outgoing interface.
    381 	 */
    382 	if (in_nullhost(ip->ip_src))
    383 		ip->ip_src = ia->ia_addr.sin_addr;
    384 #endif
    385 
    386 	/*
    387 	 * packets with Class-D address as source are not valid per
    388 	 * RFC 1112
    389 	 */
    390 	if (IN_MULTICAST(ip->ip_src.s_addr)) {
    391 		ipstat.ips_odropped++;
    392 		error = EADDRNOTAVAIL;
    393 		goto bad;
    394 	}
    395 
    396 	/*
    397 	 * Look for broadcast address and
    398 	 * and verify user is allowed to send
    399 	 * such a packet.
    400 	 */
    401 	if (in_broadcast(dst->sin_addr, ifp)) {
    402 		if ((ifp->if_flags & IFF_BROADCAST) == 0) {
    403 			error = EADDRNOTAVAIL;
    404 			goto bad;
    405 		}
    406 		if ((flags & IP_ALLOWBROADCAST) == 0) {
    407 			error = EACCES;
    408 			goto bad;
    409 		}
    410 		/* don't allow broadcast messages to be fragmented */
    411 		if ((u_int16_t)ip->ip_len > ifp->if_mtu) {
    412 			error = EMSGSIZE;
    413 			goto bad;
    414 		}
    415 		m->m_flags |= M_BCAST;
    416 	} else
    417 		m->m_flags &= ~M_BCAST;
    418 
    419 sendit:
    420 	/*
    421 	 * If we're doing Path MTU Discovery, we need to set DF unless
    422 	 * the route's MTU is locked.
    423 	 */
    424 	if ((flags & IP_MTUDISC) != 0 && ro->ro_rt != NULL &&
    425 	    (ro->ro_rt->rt_rmx.rmx_locks & RTV_MTU) == 0)
    426 		ip->ip_off |= IP_DF;
    427 
    428 	/*
    429 	 * Remember the current ip_len and ip_off, and swap them into
    430 	 * network order.
    431 	 */
    432 	ip_len = ip->ip_len;
    433 
    434 	HTONS(ip->ip_len);
    435 	HTONS(ip->ip_off);
    436 
    437 #ifdef IPSEC
    438 	/* get SP for this packet */
    439 	if (so == NULL)
    440 		sp = ipsec4_getpolicybyaddr(m, IPSEC_DIR_OUTBOUND, flags, &error);
    441 	else
    442 		sp = ipsec4_getpolicybysock(m, IPSEC_DIR_OUTBOUND, so, &error);
    443 
    444 	if (sp == NULL) {
    445 		ipsecstat.out_inval++;
    446 		goto bad;
    447 	}
    448 
    449 	error = 0;
    450 
    451 	/* check policy */
    452 	switch (sp->policy) {
    453 	case IPSEC_POLICY_DISCARD:
    454 		/*
    455 		 * This packet is just discarded.
    456 		 */
    457 		ipsecstat.out_polvio++;
    458 		goto bad;
    459 
    460 	case IPSEC_POLICY_BYPASS:
    461 	case IPSEC_POLICY_NONE:
    462 		/* no need to do IPsec. */
    463 		goto skip_ipsec;
    464 
    465 	case IPSEC_POLICY_IPSEC:
    466 		if (sp->req == NULL) {
    467 			/* XXX should be panic ? */
    468 			printf("ip_output: No IPsec request specified.\n");
    469 			error = EINVAL;
    470 			goto bad;
    471 		}
    472 		break;
    473 
    474 	case IPSEC_POLICY_ENTRUST:
    475 	default:
    476 		printf("ip_output: Invalid policy found. %d\n", sp->policy);
    477 	}
    478 
    479 	/*
    480 	 * ipsec4_output() expects ip_len and ip_off in network
    481 	 * order.  They have been set to network order above.
    482 	 */
    483 
    484     {
    485 	struct ipsec_output_state state;
    486 	bzero(&state, sizeof(state));
    487 	state.m = m;
    488 	if (flags & IP_ROUTETOIF) {
    489 		state.ro = &iproute;
    490 		bzero(&iproute, sizeof(iproute));
    491 	} else
    492 		state.ro = ro;
    493 	state.dst = (struct sockaddr *)dst;
    494 
    495 	/*
    496 	 * We can't defer the checksum of payload data if
    497 	 * we're about to encrypt/authenticate it.
    498 	 *
    499 	 * XXX When we support crypto offloading functions of
    500 	 * XXX network interfaces, we need to reconsider this,
    501 	 * XXX since it's likely that they'll support checksumming,
    502 	 * XXX as well.
    503 	 */
    504 	if (m->m_pkthdr.csum_flags & (M_CSUM_TCPv4|M_CSUM_UDPv4)) {
    505 		in_delayed_cksum(m);
    506 		m->m_pkthdr.csum_flags &= ~(M_CSUM_TCPv4|M_CSUM_UDPv4);
    507 	}
    508 
    509 	error = ipsec4_output(&state, sp, flags);
    510 
    511 	m = state.m;
    512 	if (flags & IP_ROUTETOIF) {
    513 		/*
    514 		 * if we have tunnel mode SA, we may need to ignore
    515 		 * IP_ROUTETOIF.
    516 		 */
    517 		if (state.ro != &iproute || state.ro->ro_rt != NULL) {
    518 			flags &= ~IP_ROUTETOIF;
    519 			ro = state.ro;
    520 		}
    521 	} else
    522 		ro = state.ro;
    523 	dst = (struct sockaddr_in *)state.dst;
    524 	if (error) {
    525 		/* mbuf is already reclaimed in ipsec4_output. */
    526 		m0 = NULL;
    527 		switch (error) {
    528 		case EHOSTUNREACH:
    529 		case ENETUNREACH:
    530 		case EMSGSIZE:
    531 		case ENOBUFS:
    532 		case ENOMEM:
    533 			break;
    534 		default:
    535 			printf("ip4_output (ipsec): error code %d\n", error);
    536 			/*fall through*/
    537 		case ENOENT:
    538 			/* don't show these error codes to the user */
    539 			error = 0;
    540 			break;
    541 		}
    542 		goto bad;
    543 	}
    544 
    545 	/* be sure to update variables that are affected by ipsec4_output() */
    546 	ip = mtod(m, struct ip *);
    547 #ifdef _IP_VHL
    548 	hlen = IP_VHL_HL(ip->ip_vhl) << 2;
    549 #else
    550 	hlen = ip->ip_hl << 2;
    551 #endif
    552 	ip_len = ntohs(ip->ip_len);
    553 
    554 	if (ro->ro_rt == NULL) {
    555 		if ((flags & IP_ROUTETOIF) == 0) {
    556 			printf("ip_output: "
    557 				"can't update route after IPsec processing\n");
    558 			error = EHOSTUNREACH;	/*XXX*/
    559 			goto bad;
    560 		}
    561 	} else {
    562 		/* nobody uses ia beyond here */
    563 		if (state.encap)
    564 			ifp = ro->ro_rt->rt_ifp;
    565 	}
    566     }
    567 
    568 skip_ipsec:
    569 #endif /*IPSEC*/
    570 
    571 #ifdef PFIL_HOOKS
    572 	/*
    573 	 * Run through list of hooks for output packets.
    574 	 */
    575 	if ((error = pfil_run_hooks(&inet_pfil_hook, &m, ifp,
    576 				    PFIL_OUT)) != 0)
    577 		goto done;
    578 	if (m == NULL)
    579 		goto done;
    580 
    581 	ip = mtod(m, struct ip *);
    582 #endif /* PFIL_HOOKS */
    583 
    584 	/*
    585 	 * If small enough for mtu of path, can just send directly.
    586 	 */
    587 	if (ip_len <= mtu) {
    588 #if IFA_STATS
    589 		/*
    590 		 * search for the source address structure to
    591 		 * maintain output statistics.
    592 		 */
    593 		INADDR_TO_IA(ip->ip_src, ia);
    594 		if (ia)
    595 			ia->ia_ifa.ifa_data.ifad_outbytes += ip_len;
    596 #endif
    597 		/*
    598 		 * Always initialize the sum to 0!  Some HW assisted
    599 		 * checksumming requires this.
    600 		 */
    601 		ip->ip_sum = 0;
    602 		m->m_pkthdr.csum_flags |= M_CSUM_IPv4;
    603 
    604 		sw_csum = m->m_pkthdr.csum_flags & ~ifp->if_csum_flags_tx;
    605 
    606 		/*
    607 		 * Perform any checksums that the hardware can't do
    608 		 * for us.
    609 		 *
    610 		 * XXX Does any hardware require the {th,uh}_sum
    611 		 * XXX fields to be 0?
    612 		 */
    613 		if (sw_csum & M_CSUM_IPv4)
    614 			ip->ip_sum = in_cksum(m, hlen);
    615 		if (sw_csum & (M_CSUM_TCPv4|M_CSUM_UDPv4)) {
    616 			in_delayed_cksum(m);
    617 			sw_csum &= ~(M_CSUM_TCPv4|M_CSUM_UDPv4);
    618 		}
    619 		m->m_pkthdr.csum_flags &= ifp->if_csum_flags_tx;
    620 
    621 #ifdef IPSEC
    622 		/* clean ipsec history once it goes out of the node */
    623 		ipsec_delaux(m);
    624 #endif
    625 		error = (*ifp->if_output)(ifp, m, sintosa(dst), ro->ro_rt);
    626 		goto done;
    627 	}
    628 
    629 	/*
    630 	 * We can't use HW checksumming if we're about to
    631 	 * to fragment the packet.
    632 	 *
    633 	 * XXX Some hardware can do this.
    634 	 */
    635 	if (m->m_pkthdr.csum_flags & (M_CSUM_TCPv4|M_CSUM_UDPv4)) {
    636 		in_delayed_cksum(m);
    637 		m->m_pkthdr.csum_flags &= ~(M_CSUM_TCPv4|M_CSUM_UDPv4);
    638 	}
    639 
    640 	/*
    641 	 * Too large for interface; fragment if possible.
    642 	 * Must be able to put at least 8 bytes per fragment.
    643 	 *
    644 	 * Note we swap ip_len and ip_off into host order to make
    645 	 * the logic below a little simpler.
    646 	 */
    647 
    648 	NTOHS(ip->ip_len);
    649 	NTOHS(ip->ip_off);
    650 
    651 	if (ip->ip_off & IP_DF) {
    652 		if (flags & IP_RETURNMTU)
    653 			*mtu_p = mtu;
    654 		error = EMSGSIZE;
    655 		ipstat.ips_cantfrag++;
    656 		goto bad;
    657 	}
    658 	len = (mtu - hlen) &~ 7;
    659 	if (len < 8) {
    660 		error = EMSGSIZE;
    661 		goto bad;
    662 	}
    663 
    664     {
    665 	int mhlen, firstlen = len;
    666 	struct mbuf **mnext = &m->m_nextpkt;
    667 	int fragments = 0;
    668 	int s;
    669 
    670 	/*
    671 	 * Loop through length of segment after first fragment,
    672 	 * make new header and copy data of each part and link onto chain.
    673 	 */
    674 	m0 = m;
    675 	mhlen = sizeof (struct ip);
    676 	for (off = hlen + len; off < (u_int16_t)ip->ip_len; off += len) {
    677 		MGETHDR(m, M_DONTWAIT, MT_HEADER);
    678 		if (m == 0) {
    679 			error = ENOBUFS;
    680 			ipstat.ips_odropped++;
    681 			goto sendorfree;
    682 		}
    683 		*mnext = m;
    684 		mnext = &m->m_nextpkt;
    685 		m->m_data += max_linkhdr;
    686 		mhip = mtod(m, struct ip *);
    687 		*mhip = *ip;
    688 		/* we must inherit MCAST and BCAST flags */
    689 		m->m_flags |= m0->m_flags & (M_MCAST|M_BCAST);
    690 		if (hlen > sizeof (struct ip)) {
    691 			mhlen = ip_optcopy(ip, mhip) + sizeof (struct ip);
    692 			mhip->ip_hl = mhlen >> 2;
    693 		}
    694 		m->m_len = mhlen;
    695 		mhip->ip_off = ((off - hlen) >> 3) + (ip->ip_off & ~IP_MF);
    696 		if (ip->ip_off & IP_MF)
    697 			mhip->ip_off |= IP_MF;
    698 		if (off + len >= (u_int16_t)ip->ip_len)
    699 			len = (u_int16_t)ip->ip_len - off;
    700 		else
    701 			mhip->ip_off |= IP_MF;
    702 		mhip->ip_len = htons((u_int16_t)(len + mhlen));
    703 		m->m_next = m_copy(m0, off, len);
    704 		if (m->m_next == 0) {
    705 			error = ENOBUFS;	/* ??? */
    706 			ipstat.ips_odropped++;
    707 			goto sendorfree;
    708 		}
    709 		m->m_pkthdr.len = mhlen + len;
    710 		m->m_pkthdr.rcvif = (struct ifnet *)0;
    711 		HTONS(mhip->ip_off);
    712 		mhip->ip_sum = 0;
    713 		mhip->ip_sum = in_cksum(m, mhlen);
    714 		ipstat.ips_ofragments++;
    715 		fragments++;
    716 	}
    717 	/*
    718 	 * Update first fragment by trimming what's been copied out
    719 	 * and updating header, then send each fragment (in order).
    720 	 */
    721 	m = m0;
    722 	m_adj(m, hlen + firstlen - (u_int16_t)ip->ip_len);
    723 	m->m_pkthdr.len = hlen + firstlen;
    724 	ip->ip_len = htons((u_int16_t)m->m_pkthdr.len);
    725 	ip->ip_off |= IP_MF;
    726 	HTONS(ip->ip_off);
    727 	ip->ip_sum = 0;
    728 	ip->ip_sum = in_cksum(m, hlen);
    729 sendorfree:
    730 	/*
    731 	 * If there is no room for all the fragments, don't queue
    732 	 * any of them.
    733 	 */
    734 	s = splnet();
    735 	if (ifp->if_snd.ifq_maxlen - ifp->if_snd.ifq_len < fragments)
    736 		error = ENOBUFS;
    737 	splx(s);
    738 	for (m = m0; m; m = m0) {
    739 		m0 = m->m_nextpkt;
    740 		m->m_nextpkt = 0;
    741 		if (error == 0) {
    742 #if IFA_STATS
    743 			/*
    744 			 * search for the source address structure to
    745 			 * maintain output statistics.
    746 			 */
    747 			INADDR_TO_IA(ip->ip_src, ia);
    748 			if (ia) {
    749 				ia->ia_ifa.ifa_data.ifad_outbytes +=
    750 					ntohs(ip->ip_len);
    751 			}
    752 #endif
    753 #ifdef IPSEC
    754 			/* clean ipsec history once it goes out of the node */
    755 			ipsec_delaux(m);
    756 #endif
    757 			error = (*ifp->if_output)(ifp, m, sintosa(dst),
    758 			    ro->ro_rt);
    759 		} else
    760 			m_freem(m);
    761 	}
    762 
    763 	if (error == 0)
    764 		ipstat.ips_fragmented++;
    765     }
    766 done:
    767 	if (ro == &iproute && (flags & IP_ROUTETOIF) == 0 && ro->ro_rt) {
    768 		RTFREE(ro->ro_rt);
    769 		ro->ro_rt = 0;
    770 	}
    771 
    772 #ifdef IPSEC
    773 	if (sp != NULL) {
    774 		KEYDEBUG(KEYDEBUG_IPSEC_STAMP,
    775 			printf("DP ip_output call free SP:%p\n", sp));
    776 		key_freesp(sp);
    777 	}
    778 #endif /* IPSEC */
    779 
    780 	return (error);
    781 bad:
    782 	m_freem(m);
    783 	goto done;
    784 }
    785 
    786 /*
    787  * Process a delayed payload checksum calculation.
    788  */
    789 void
    790 in_delayed_cksum(struct mbuf *m)
    791 {
    792 	struct ip *ip;
    793 	u_int16_t csum, offset;
    794 
    795 	ip = mtod(m, struct ip *);
    796 	offset = ip->ip_hl << 2;
    797 	csum = in4_cksum(m, 0, offset, ntohs(ip->ip_len) - offset);
    798 	if (csum == 0 && (m->m_pkthdr.csum_flags & M_CSUM_UDPv4) != 0)
    799 		csum = 0xffff;
    800 
    801 	offset += m->m_pkthdr.csum_data;	/* checksum offset */
    802 
    803 	if ((offset + sizeof(u_int16_t)) > m->m_len) {
    804 		/* This happen when ip options were inserted
    805 		printf("in_delayed_cksum: pullup len %d off %d proto %d\n",
    806 		    m->m_len, offset, ip->ip_p);
    807 		 */
    808 		m_copyback(m, offset, sizeof(csum), (caddr_t) &csum);
    809 	} else
    810 		*(u_int16_t *)(mtod(m, caddr_t) + offset) = csum;
    811 }
    812 
    813 /*
    814  * Determine the maximum length of the options to be inserted;
    815  * we would far rather allocate too much space rather than too little.
    816  */
    817 
    818 u_int
    819 ip_optlen(inp)
    820 	struct inpcb *inp;
    821 {
    822 	struct mbuf *m = inp->inp_options;
    823 
    824 	if (m && m->m_len > offsetof(struct ipoption, ipopt_dst))
    825 		return(m->m_len - offsetof(struct ipoption, ipopt_dst));
    826 	else
    827 		return 0;
    828 }
    829 
    830 
    831 /*
    832  * Insert IP options into preformed packet.
    833  * Adjust IP destination as required for IP source routing,
    834  * as indicated by a non-zero in_addr at the start of the options.
    835  */
    836 static struct mbuf *
    837 ip_insertoptions(m, opt, phlen)
    838 	struct mbuf *m;
    839 	struct mbuf *opt;
    840 	int *phlen;
    841 {
    842 	struct ipoption *p = mtod(opt, struct ipoption *);
    843 	struct mbuf *n;
    844 	struct ip *ip = mtod(m, struct ip *);
    845 	unsigned optlen;
    846 
    847 	optlen = opt->m_len - sizeof(p->ipopt_dst);
    848 	if (optlen + (u_int16_t)ip->ip_len > IP_MAXPACKET)
    849 		return (m);		/* XXX should fail */
    850 	if (!in_nullhost(p->ipopt_dst))
    851 		ip->ip_dst = p->ipopt_dst;
    852 	if (m->m_flags & M_EXT || m->m_data - optlen < m->m_pktdat) {
    853 		MGETHDR(n, M_DONTWAIT, MT_HEADER);
    854 		if (n == 0)
    855 			return (m);
    856 		M_COPY_PKTHDR(n, m);
    857 		m->m_flags &= ~M_PKTHDR;
    858 		m->m_len -= sizeof(struct ip);
    859 		m->m_data += sizeof(struct ip);
    860 		n->m_next = m;
    861 		m = n;
    862 		m->m_len = optlen + sizeof(struct ip);
    863 		m->m_data += max_linkhdr;
    864 		bcopy((caddr_t)ip, mtod(m, caddr_t), sizeof(struct ip));
    865 	} else {
    866 		m->m_data -= optlen;
    867 		m->m_len += optlen;
    868 		memmove(mtod(m, caddr_t), ip, sizeof(struct ip));
    869 	}
    870 	m->m_pkthdr.len += optlen;
    871 	ip = mtod(m, struct ip *);
    872 	bcopy((caddr_t)p->ipopt_list, (caddr_t)(ip + 1), (unsigned)optlen);
    873 	*phlen = sizeof(struct ip) + optlen;
    874 	ip->ip_len += optlen;
    875 	return (m);
    876 }
    877 
    878 /*
    879  * Copy options from ip to jp,
    880  * omitting those not copied during fragmentation.
    881  */
    882 int
    883 ip_optcopy(ip, jp)
    884 	struct ip *ip, *jp;
    885 {
    886 	u_char *cp, *dp;
    887 	int opt, optlen, cnt;
    888 
    889 	cp = (u_char *)(ip + 1);
    890 	dp = (u_char *)(jp + 1);
    891 	cnt = (ip->ip_hl << 2) - sizeof (struct ip);
    892 	for (; cnt > 0; cnt -= optlen, cp += optlen) {
    893 		opt = cp[0];
    894 		if (opt == IPOPT_EOL)
    895 			break;
    896 		if (opt == IPOPT_NOP) {
    897 			/* Preserve for IP mcast tunnel's LSRR alignment. */
    898 			*dp++ = IPOPT_NOP;
    899 			optlen = 1;
    900 			continue;
    901 		}
    902 #ifdef DIAGNOSTIC
    903 		if (cnt < IPOPT_OLEN + sizeof(*cp))
    904 			panic("malformed IPv4 option passed to ip_optcopy");
    905 #endif
    906 		optlen = cp[IPOPT_OLEN];
    907 #ifdef DIAGNOSTIC
    908 		if (optlen < IPOPT_OLEN + sizeof(*cp) || optlen > cnt)
    909 			panic("malformed IPv4 option passed to ip_optcopy");
    910 #endif
    911 		/* bogus lengths should have been caught by ip_dooptions */
    912 		if (optlen > cnt)
    913 			optlen = cnt;
    914 		if (IPOPT_COPIED(opt)) {
    915 			bcopy((caddr_t)cp, (caddr_t)dp, (unsigned)optlen);
    916 			dp += optlen;
    917 		}
    918 	}
    919 	for (optlen = dp - (u_char *)(jp+1); optlen & 0x3; optlen++)
    920 		*dp++ = IPOPT_EOL;
    921 	return (optlen);
    922 }
    923 
    924 /*
    925  * IP socket option processing.
    926  */
    927 int
    928 ip_ctloutput(op, so, level, optname, mp)
    929 	int op;
    930 	struct socket *so;
    931 	int level, optname;
    932 	struct mbuf **mp;
    933 {
    934 	struct inpcb *inp = sotoinpcb(so);
    935 	struct mbuf *m = *mp;
    936 	int optval = 0;
    937 	int error = 0;
    938 #ifdef IPSEC
    939 #ifdef __NetBSD__
    940 	struct proc *p = (curproc ? curproc->l_proc : 0);	/*XXX*/
    941 #endif
    942 #endif
    943 
    944 	if (level != IPPROTO_IP) {
    945 		error = EINVAL;
    946 		if (op == PRCO_SETOPT && *mp)
    947 			(void) m_free(*mp);
    948 	} else switch (op) {
    949 
    950 	case PRCO_SETOPT:
    951 		switch (optname) {
    952 		case IP_OPTIONS:
    953 #ifdef notyet
    954 		case IP_RETOPTS:
    955 			return (ip_pcbopts(optname, &inp->inp_options, m));
    956 #else
    957 			return (ip_pcbopts(&inp->inp_options, m));
    958 #endif
    959 
    960 		case IP_TOS:
    961 		case IP_TTL:
    962 		case IP_RECVOPTS:
    963 		case IP_RECVRETOPTS:
    964 		case IP_RECVDSTADDR:
    965 		case IP_RECVIF:
    966 			if (m == NULL || m->m_len != sizeof(int))
    967 				error = EINVAL;
    968 			else {
    969 				optval = *mtod(m, int *);
    970 				switch (optname) {
    971 
    972 				case IP_TOS:
    973 					inp->inp_ip.ip_tos = optval;
    974 					break;
    975 
    976 				case IP_TTL:
    977 					inp->inp_ip.ip_ttl = optval;
    978 					break;
    979 #define	OPTSET(bit) \
    980 	if (optval) \
    981 		inp->inp_flags |= bit; \
    982 	else \
    983 		inp->inp_flags &= ~bit;
    984 
    985 				case IP_RECVOPTS:
    986 					OPTSET(INP_RECVOPTS);
    987 					break;
    988 
    989 				case IP_RECVRETOPTS:
    990 					OPTSET(INP_RECVRETOPTS);
    991 					break;
    992 
    993 				case IP_RECVDSTADDR:
    994 					OPTSET(INP_RECVDSTADDR);
    995 					break;
    996 
    997 				case IP_RECVIF:
    998 					OPTSET(INP_RECVIF);
    999 					break;
   1000 				}
   1001 			}
   1002 			break;
   1003 #undef OPTSET
   1004 
   1005 		case IP_MULTICAST_IF:
   1006 		case IP_MULTICAST_TTL:
   1007 		case IP_MULTICAST_LOOP:
   1008 		case IP_ADD_MEMBERSHIP:
   1009 		case IP_DROP_MEMBERSHIP:
   1010 			error = ip_setmoptions(optname, &inp->inp_moptions, m);
   1011 			break;
   1012 
   1013 		case IP_PORTRANGE:
   1014 			if (m == 0 || m->m_len != sizeof(int))
   1015 				error = EINVAL;
   1016 			else {
   1017 				optval = *mtod(m, int *);
   1018 
   1019 				switch (optval) {
   1020 
   1021 				case IP_PORTRANGE_DEFAULT:
   1022 				case IP_PORTRANGE_HIGH:
   1023 					inp->inp_flags &= ~(INP_LOWPORT);
   1024 					break;
   1025 
   1026 				case IP_PORTRANGE_LOW:
   1027 					inp->inp_flags |= INP_LOWPORT;
   1028 					break;
   1029 
   1030 				default:
   1031 					error = EINVAL;
   1032 					break;
   1033 				}
   1034 			}
   1035 			break;
   1036 
   1037 #ifdef IPSEC
   1038 		case IP_IPSEC_POLICY:
   1039 		{
   1040 			caddr_t req = NULL;
   1041 			size_t len = 0;
   1042 			int priv = 0;
   1043 
   1044 #ifdef __NetBSD__
   1045 			if (p == 0 || suser(p->p_ucred, &p->p_acflag))
   1046 				priv = 0;
   1047 			else
   1048 				priv = 1;
   1049 #else
   1050 			priv = (in6p->in6p_socket->so_state & SS_PRIV);
   1051 #endif
   1052 			if (m) {
   1053 				req = mtod(m, caddr_t);
   1054 				len = m->m_len;
   1055 			}
   1056 			error = ipsec4_set_policy(inp, optname, req, len, priv);
   1057 			break;
   1058 		    }
   1059 #endif /*IPSEC*/
   1060 
   1061 		default:
   1062 			error = ENOPROTOOPT;
   1063 			break;
   1064 		}
   1065 		if (m)
   1066 			(void)m_free(m);
   1067 		break;
   1068 
   1069 	case PRCO_GETOPT:
   1070 		switch (optname) {
   1071 		case IP_OPTIONS:
   1072 		case IP_RETOPTS:
   1073 			*mp = m = m_get(M_WAIT, MT_SOOPTS);
   1074 			if (inp->inp_options) {
   1075 				m->m_len = inp->inp_options->m_len;
   1076 				bcopy(mtod(inp->inp_options, caddr_t),
   1077 				    mtod(m, caddr_t), (unsigned)m->m_len);
   1078 			} else
   1079 				m->m_len = 0;
   1080 			break;
   1081 
   1082 		case IP_TOS:
   1083 		case IP_TTL:
   1084 		case IP_RECVOPTS:
   1085 		case IP_RECVRETOPTS:
   1086 		case IP_RECVDSTADDR:
   1087 		case IP_RECVIF:
   1088 		case IP_ERRORMTU:
   1089 			*mp = m = m_get(M_WAIT, MT_SOOPTS);
   1090 			m->m_len = sizeof(int);
   1091 			switch (optname) {
   1092 
   1093 			case IP_TOS:
   1094 				optval = inp->inp_ip.ip_tos;
   1095 				break;
   1096 
   1097 			case IP_TTL:
   1098 				optval = inp->inp_ip.ip_ttl;
   1099 				break;
   1100 
   1101 			case IP_ERRORMTU:
   1102 				optval = inp->inp_errormtu;
   1103 				break;
   1104 
   1105 #define	OPTBIT(bit)	(inp->inp_flags & bit ? 1 : 0)
   1106 
   1107 			case IP_RECVOPTS:
   1108 				optval = OPTBIT(INP_RECVOPTS);
   1109 				break;
   1110 
   1111 			case IP_RECVRETOPTS:
   1112 				optval = OPTBIT(INP_RECVRETOPTS);
   1113 				break;
   1114 
   1115 			case IP_RECVDSTADDR:
   1116 				optval = OPTBIT(INP_RECVDSTADDR);
   1117 				break;
   1118 
   1119 			case IP_RECVIF:
   1120 				optval = OPTBIT(INP_RECVIF);
   1121 				break;
   1122 			}
   1123 			*mtod(m, int *) = optval;
   1124 			break;
   1125 
   1126 #ifdef IPSEC
   1127 		case IP_IPSEC_POLICY:
   1128 		{
   1129 			caddr_t req = NULL;
   1130 			size_t len = 0;
   1131 
   1132 			if (m) {
   1133 				req = mtod(m, caddr_t);
   1134 				len = m->m_len;
   1135 			}
   1136 			error = ipsec4_get_policy(inp, req, len, mp);
   1137 			break;
   1138 		}
   1139 #endif /*IPSEC*/
   1140 
   1141 		case IP_MULTICAST_IF:
   1142 		case IP_MULTICAST_TTL:
   1143 		case IP_MULTICAST_LOOP:
   1144 		case IP_ADD_MEMBERSHIP:
   1145 		case IP_DROP_MEMBERSHIP:
   1146 			error = ip_getmoptions(optname, inp->inp_moptions, mp);
   1147 			break;
   1148 
   1149 		case IP_PORTRANGE:
   1150 			*mp = m = m_get(M_WAIT, MT_SOOPTS);
   1151 			m->m_len = sizeof(int);
   1152 
   1153 			if (inp->inp_flags & INP_LOWPORT)
   1154 				optval = IP_PORTRANGE_LOW;
   1155 			else
   1156 				optval = IP_PORTRANGE_DEFAULT;
   1157 
   1158 			*mtod(m, int *) = optval;
   1159 			break;
   1160 
   1161 		default:
   1162 			error = ENOPROTOOPT;
   1163 			break;
   1164 		}
   1165 		break;
   1166 	}
   1167 	return (error);
   1168 }
   1169 
   1170 /*
   1171  * Set up IP options in pcb for insertion in output packets.
   1172  * Store in mbuf with pointer in pcbopt, adding pseudo-option
   1173  * with destination address if source routed.
   1174  */
   1175 int
   1176 #ifdef notyet
   1177 ip_pcbopts(optname, pcbopt, m)
   1178 	int optname;
   1179 #else
   1180 ip_pcbopts(pcbopt, m)
   1181 #endif
   1182 	struct mbuf **pcbopt;
   1183 	struct mbuf *m;
   1184 {
   1185 	int cnt, optlen;
   1186 	u_char *cp;
   1187 	u_char opt;
   1188 
   1189 	/* turn off any old options */
   1190 	if (*pcbopt)
   1191 		(void)m_free(*pcbopt);
   1192 	*pcbopt = 0;
   1193 	if (m == (struct mbuf *)0 || m->m_len == 0) {
   1194 		/*
   1195 		 * Only turning off any previous options.
   1196 		 */
   1197 		if (m)
   1198 			(void)m_free(m);
   1199 		return (0);
   1200 	}
   1201 
   1202 #ifndef	__vax__
   1203 	if (m->m_len % sizeof(int32_t))
   1204 		goto bad;
   1205 #endif
   1206 	/*
   1207 	 * IP first-hop destination address will be stored before
   1208 	 * actual options; move other options back
   1209 	 * and clear it when none present.
   1210 	 */
   1211 	if (m->m_data + m->m_len + sizeof(struct in_addr) >= &m->m_dat[MLEN])
   1212 		goto bad;
   1213 	cnt = m->m_len;
   1214 	m->m_len += sizeof(struct in_addr);
   1215 	cp = mtod(m, u_char *) + sizeof(struct in_addr);
   1216 	memmove(cp, mtod(m, caddr_t), (unsigned)cnt);
   1217 	bzero(mtod(m, caddr_t), sizeof(struct in_addr));
   1218 
   1219 	for (; cnt > 0; cnt -= optlen, cp += optlen) {
   1220 		opt = cp[IPOPT_OPTVAL];
   1221 		if (opt == IPOPT_EOL)
   1222 			break;
   1223 		if (opt == IPOPT_NOP)
   1224 			optlen = 1;
   1225 		else {
   1226 			if (cnt < IPOPT_OLEN + sizeof(*cp))
   1227 				goto bad;
   1228 			optlen = cp[IPOPT_OLEN];
   1229 			if (optlen < IPOPT_OLEN  + sizeof(*cp) || optlen > cnt)
   1230 				goto bad;
   1231 		}
   1232 		switch (opt) {
   1233 
   1234 		default:
   1235 			break;
   1236 
   1237 		case IPOPT_LSRR:
   1238 		case IPOPT_SSRR:
   1239 			/*
   1240 			 * user process specifies route as:
   1241 			 *	->A->B->C->D
   1242 			 * D must be our final destination (but we can't
   1243 			 * check that since we may not have connected yet).
   1244 			 * A is first hop destination, which doesn't appear in
   1245 			 * actual IP option, but is stored before the options.
   1246 			 */
   1247 			if (optlen < IPOPT_MINOFF - 1 + sizeof(struct in_addr))
   1248 				goto bad;
   1249 			m->m_len -= sizeof(struct in_addr);
   1250 			cnt -= sizeof(struct in_addr);
   1251 			optlen -= sizeof(struct in_addr);
   1252 			cp[IPOPT_OLEN] = optlen;
   1253 			/*
   1254 			 * Move first hop before start of options.
   1255 			 */
   1256 			bcopy((caddr_t)&cp[IPOPT_OFFSET+1], mtod(m, caddr_t),
   1257 			    sizeof(struct in_addr));
   1258 			/*
   1259 			 * Then copy rest of options back
   1260 			 * to close up the deleted entry.
   1261 			 */
   1262 			memmove(&cp[IPOPT_OFFSET+1],
   1263                             (caddr_t)(&cp[IPOPT_OFFSET+1] + sizeof(struct in_addr)),
   1264 			    (unsigned)cnt + sizeof(struct in_addr));
   1265 			break;
   1266 		}
   1267 	}
   1268 	if (m->m_len > MAX_IPOPTLEN + sizeof(struct in_addr))
   1269 		goto bad;
   1270 	*pcbopt = m;
   1271 	return (0);
   1272 
   1273 bad:
   1274 	(void)m_free(m);
   1275 	return (EINVAL);
   1276 }
   1277 
   1278 /*
   1279  * following RFC1724 section 3.3, 0.0.0.0/8 is interpreted as interface index.
   1280  */
   1281 static struct ifnet *
   1282 ip_multicast_if(a, ifindexp)
   1283 	struct in_addr *a;
   1284 	int *ifindexp;
   1285 {
   1286 	int ifindex;
   1287 	struct ifnet *ifp;
   1288 
   1289 	if (ifindexp)
   1290 		*ifindexp = 0;
   1291 	if (ntohl(a->s_addr) >> 24 == 0) {
   1292 		ifindex = ntohl(a->s_addr) & 0xffffff;
   1293 		if (ifindex < 0 || if_index < ifindex)
   1294 			return NULL;
   1295 		ifp = ifindex2ifnet[ifindex];
   1296 		if (ifindexp)
   1297 			*ifindexp = ifindex;
   1298 	} else {
   1299 		INADDR_TO_IFP(*a, ifp);
   1300 	}
   1301 	return ifp;
   1302 }
   1303 
   1304 /*
   1305  * Set the IP multicast options in response to user setsockopt().
   1306  */
   1307 int
   1308 ip_setmoptions(optname, imop, m)
   1309 	int optname;
   1310 	struct ip_moptions **imop;
   1311 	struct mbuf *m;
   1312 {
   1313 	int error = 0;
   1314 	u_char loop;
   1315 	int i;
   1316 	struct in_addr addr;
   1317 	struct ip_mreq *mreq;
   1318 	struct ifnet *ifp;
   1319 	struct ip_moptions *imo = *imop;
   1320 	struct route ro;
   1321 	struct sockaddr_in *dst;
   1322 	int ifindex;
   1323 
   1324 	if (imo == NULL) {
   1325 		/*
   1326 		 * No multicast option buffer attached to the pcb;
   1327 		 * allocate one and initialize to default values.
   1328 		 */
   1329 		imo = (struct ip_moptions *)malloc(sizeof(*imo), M_IPMOPTS,
   1330 		    M_WAITOK);
   1331 
   1332 		if (imo == NULL)
   1333 			return (ENOBUFS);
   1334 		*imop = imo;
   1335 		imo->imo_multicast_ifp = NULL;
   1336 		imo->imo_multicast_addr.s_addr = INADDR_ANY;
   1337 		imo->imo_multicast_ttl = IP_DEFAULT_MULTICAST_TTL;
   1338 		imo->imo_multicast_loop = IP_DEFAULT_MULTICAST_LOOP;
   1339 		imo->imo_num_memberships = 0;
   1340 	}
   1341 
   1342 	switch (optname) {
   1343 
   1344 	case IP_MULTICAST_IF:
   1345 		/*
   1346 		 * Select the interface for outgoing multicast packets.
   1347 		 */
   1348 		if (m == NULL || m->m_len != sizeof(struct in_addr)) {
   1349 			error = EINVAL;
   1350 			break;
   1351 		}
   1352 		addr = *(mtod(m, struct in_addr *));
   1353 		/*
   1354 		 * INADDR_ANY is used to remove a previous selection.
   1355 		 * When no interface is selected, a default one is
   1356 		 * chosen every time a multicast packet is sent.
   1357 		 */
   1358 		if (in_nullhost(addr)) {
   1359 			imo->imo_multicast_ifp = NULL;
   1360 			break;
   1361 		}
   1362 		/*
   1363 		 * The selected interface is identified by its local
   1364 		 * IP address.  Find the interface and confirm that
   1365 		 * it supports multicasting.
   1366 		 */
   1367 		ifp = ip_multicast_if(&addr, &ifindex);
   1368 		if (ifp == NULL || (ifp->if_flags & IFF_MULTICAST) == 0) {
   1369 			error = EADDRNOTAVAIL;
   1370 			break;
   1371 		}
   1372 		imo->imo_multicast_ifp = ifp;
   1373 		if (ifindex)
   1374 			imo->imo_multicast_addr = addr;
   1375 		else
   1376 			imo->imo_multicast_addr.s_addr = INADDR_ANY;
   1377 		break;
   1378 
   1379 	case IP_MULTICAST_TTL:
   1380 		/*
   1381 		 * Set the IP time-to-live for outgoing multicast packets.
   1382 		 */
   1383 		if (m == NULL || m->m_len != 1) {
   1384 			error = EINVAL;
   1385 			break;
   1386 		}
   1387 		imo->imo_multicast_ttl = *(mtod(m, u_char *));
   1388 		break;
   1389 
   1390 	case IP_MULTICAST_LOOP:
   1391 		/*
   1392 		 * Set the loopback flag for outgoing multicast packets.
   1393 		 * Must be zero or one.
   1394 		 */
   1395 		if (m == NULL || m->m_len != 1 ||
   1396 		   (loop = *(mtod(m, u_char *))) > 1) {
   1397 			error = EINVAL;
   1398 			break;
   1399 		}
   1400 		imo->imo_multicast_loop = loop;
   1401 		break;
   1402 
   1403 	case IP_ADD_MEMBERSHIP:
   1404 		/*
   1405 		 * Add a multicast group membership.
   1406 		 * Group must be a valid IP multicast address.
   1407 		 */
   1408 		if (m == NULL || m->m_len != sizeof(struct ip_mreq)) {
   1409 			error = EINVAL;
   1410 			break;
   1411 		}
   1412 		mreq = mtod(m, struct ip_mreq *);
   1413 		if (!IN_MULTICAST(mreq->imr_multiaddr.s_addr)) {
   1414 			error = EINVAL;
   1415 			break;
   1416 		}
   1417 		/*
   1418 		 * If no interface address was provided, use the interface of
   1419 		 * the route to the given multicast address.
   1420 		 */
   1421 		if (in_nullhost(mreq->imr_interface)) {
   1422 			bzero((caddr_t)&ro, sizeof(ro));
   1423 			ro.ro_rt = NULL;
   1424 			dst = satosin(&ro.ro_dst);
   1425 			dst->sin_len = sizeof(*dst);
   1426 			dst->sin_family = AF_INET;
   1427 			dst->sin_addr = mreq->imr_multiaddr;
   1428 			rtalloc(&ro);
   1429 			if (ro.ro_rt == NULL) {
   1430 				error = EADDRNOTAVAIL;
   1431 				break;
   1432 			}
   1433 			ifp = ro.ro_rt->rt_ifp;
   1434 			rtfree(ro.ro_rt);
   1435 		} else {
   1436 			ifp = ip_multicast_if(&mreq->imr_interface, NULL);
   1437 		}
   1438 		/*
   1439 		 * See if we found an interface, and confirm that it
   1440 		 * supports multicast.
   1441 		 */
   1442 		if (ifp == NULL || (ifp->if_flags & IFF_MULTICAST) == 0) {
   1443 			error = EADDRNOTAVAIL;
   1444 			break;
   1445 		}
   1446 		/*
   1447 		 * See if the membership already exists or if all the
   1448 		 * membership slots are full.
   1449 		 */
   1450 		for (i = 0; i < imo->imo_num_memberships; ++i) {
   1451 			if (imo->imo_membership[i]->inm_ifp == ifp &&
   1452 			    in_hosteq(imo->imo_membership[i]->inm_addr,
   1453 				      mreq->imr_multiaddr))
   1454 				break;
   1455 		}
   1456 		if (i < imo->imo_num_memberships) {
   1457 			error = EADDRINUSE;
   1458 			break;
   1459 		}
   1460 		if (i == IP_MAX_MEMBERSHIPS) {
   1461 			error = ETOOMANYREFS;
   1462 			break;
   1463 		}
   1464 		/*
   1465 		 * Everything looks good; add a new record to the multicast
   1466 		 * address list for the given interface.
   1467 		 */
   1468 		if ((imo->imo_membership[i] =
   1469 		    in_addmulti(&mreq->imr_multiaddr, ifp)) == NULL) {
   1470 			error = ENOBUFS;
   1471 			break;
   1472 		}
   1473 		++imo->imo_num_memberships;
   1474 		break;
   1475 
   1476 	case IP_DROP_MEMBERSHIP:
   1477 		/*
   1478 		 * Drop a multicast group membership.
   1479 		 * Group must be a valid IP multicast address.
   1480 		 */
   1481 		if (m == NULL || m->m_len != sizeof(struct ip_mreq)) {
   1482 			error = EINVAL;
   1483 			break;
   1484 		}
   1485 		mreq = mtod(m, struct ip_mreq *);
   1486 		if (!IN_MULTICAST(mreq->imr_multiaddr.s_addr)) {
   1487 			error = EINVAL;
   1488 			break;
   1489 		}
   1490 		/*
   1491 		 * If an interface address was specified, get a pointer
   1492 		 * to its ifnet structure.
   1493 		 */
   1494 		if (in_nullhost(mreq->imr_interface))
   1495 			ifp = NULL;
   1496 		else {
   1497 			ifp = ip_multicast_if(&mreq->imr_interface, NULL);
   1498 			if (ifp == NULL) {
   1499 				error = EADDRNOTAVAIL;
   1500 				break;
   1501 			}
   1502 		}
   1503 		/*
   1504 		 * Find the membership in the membership array.
   1505 		 */
   1506 		for (i = 0; i < imo->imo_num_memberships; ++i) {
   1507 			if ((ifp == NULL ||
   1508 			     imo->imo_membership[i]->inm_ifp == ifp) &&
   1509 			     in_hosteq(imo->imo_membership[i]->inm_addr,
   1510 				       mreq->imr_multiaddr))
   1511 				break;
   1512 		}
   1513 		if (i == imo->imo_num_memberships) {
   1514 			error = EADDRNOTAVAIL;
   1515 			break;
   1516 		}
   1517 		/*
   1518 		 * Give up the multicast address record to which the
   1519 		 * membership points.
   1520 		 */
   1521 		in_delmulti(imo->imo_membership[i]);
   1522 		/*
   1523 		 * Remove the gap in the membership array.
   1524 		 */
   1525 		for (++i; i < imo->imo_num_memberships; ++i)
   1526 			imo->imo_membership[i-1] = imo->imo_membership[i];
   1527 		--imo->imo_num_memberships;
   1528 		break;
   1529 
   1530 	default:
   1531 		error = EOPNOTSUPP;
   1532 		break;
   1533 	}
   1534 
   1535 	/*
   1536 	 * If all options have default values, no need to keep the mbuf.
   1537 	 */
   1538 	if (imo->imo_multicast_ifp == NULL &&
   1539 	    imo->imo_multicast_ttl == IP_DEFAULT_MULTICAST_TTL &&
   1540 	    imo->imo_multicast_loop == IP_DEFAULT_MULTICAST_LOOP &&
   1541 	    imo->imo_num_memberships == 0) {
   1542 		free(*imop, M_IPMOPTS);
   1543 		*imop = NULL;
   1544 	}
   1545 
   1546 	return (error);
   1547 }
   1548 
   1549 /*
   1550  * Return the IP multicast options in response to user getsockopt().
   1551  */
   1552 int
   1553 ip_getmoptions(optname, imo, mp)
   1554 	int optname;
   1555 	struct ip_moptions *imo;
   1556 	struct mbuf **mp;
   1557 {
   1558 	u_char *ttl;
   1559 	u_char *loop;
   1560 	struct in_addr *addr;
   1561 	struct in_ifaddr *ia;
   1562 
   1563 	*mp = m_get(M_WAIT, MT_SOOPTS);
   1564 
   1565 	switch (optname) {
   1566 
   1567 	case IP_MULTICAST_IF:
   1568 		addr = mtod(*mp, struct in_addr *);
   1569 		(*mp)->m_len = sizeof(struct in_addr);
   1570 		if (imo == NULL || imo->imo_multicast_ifp == NULL)
   1571 			*addr = zeroin_addr;
   1572 		else if (imo->imo_multicast_addr.s_addr) {
   1573 			/* return the value user has set */
   1574 			*addr = imo->imo_multicast_addr;
   1575 		} else {
   1576 			IFP_TO_IA(imo->imo_multicast_ifp, ia);
   1577 			*addr = ia ? ia->ia_addr.sin_addr : zeroin_addr;
   1578 		}
   1579 		return (0);
   1580 
   1581 	case IP_MULTICAST_TTL:
   1582 		ttl = mtod(*mp, u_char *);
   1583 		(*mp)->m_len = 1;
   1584 		*ttl = imo ? imo->imo_multicast_ttl
   1585 			   : IP_DEFAULT_MULTICAST_TTL;
   1586 		return (0);
   1587 
   1588 	case IP_MULTICAST_LOOP:
   1589 		loop = mtod(*mp, u_char *);
   1590 		(*mp)->m_len = 1;
   1591 		*loop = imo ? imo->imo_multicast_loop
   1592 			    : IP_DEFAULT_MULTICAST_LOOP;
   1593 		return (0);
   1594 
   1595 	default:
   1596 		return (EOPNOTSUPP);
   1597 	}
   1598 }
   1599 
   1600 /*
   1601  * Discard the IP multicast options.
   1602  */
   1603 void
   1604 ip_freemoptions(imo)
   1605 	struct ip_moptions *imo;
   1606 {
   1607 	int i;
   1608 
   1609 	if (imo != NULL) {
   1610 		for (i = 0; i < imo->imo_num_memberships; ++i)
   1611 			in_delmulti(imo->imo_membership[i]);
   1612 		free(imo, M_IPMOPTS);
   1613 	}
   1614 }
   1615 
   1616 /*
   1617  * Routine called from ip_output() to loop back a copy of an IP multicast
   1618  * packet to the input queue of a specified interface.  Note that this
   1619  * calls the output routine of the loopback "driver", but with an interface
   1620  * pointer that might NOT be &loif -- easier than replicating that code here.
   1621  */
   1622 static void
   1623 ip_mloopback(ifp, m, dst)
   1624 	struct ifnet *ifp;
   1625 	struct mbuf *m;
   1626 	struct sockaddr_in *dst;
   1627 {
   1628 	struct ip *ip;
   1629 	struct mbuf *copym;
   1630 
   1631 	copym = m_copy(m, 0, M_COPYALL);
   1632 	if (copym != NULL
   1633 	 && (copym->m_flags & M_EXT || copym->m_len < sizeof(struct ip)))
   1634 		copym = m_pullup(copym, sizeof(struct ip));
   1635 	if (copym != NULL) {
   1636 		/*
   1637 		 * We don't bother to fragment if the IP length is greater
   1638 		 * than the interface's MTU.  Can this possibly matter?
   1639 		 */
   1640 		ip = mtod(copym, struct ip *);
   1641 		HTONS(ip->ip_len);
   1642 		HTONS(ip->ip_off);
   1643 		ip->ip_sum = 0;
   1644 		ip->ip_sum = in_cksum(copym, ip->ip_hl << 2);
   1645 		(void) looutput(ifp, copym, sintosa(dst), NULL);
   1646 	}
   1647 }
   1648