Home | History | Annotate | Line # | Download | only in netinet
ip_output.c revision 1.83.2.7
      1 /*	$NetBSD: ip_output.c,v 1.83.2.7 2002/01/08 00:34:09 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.7 2002/01/08 00:34:09 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 			ip->ip_src = ia->ia_addr.sin_addr;
    322 		}
    323 
    324 		IN_LOOKUP_MULTI(ip->ip_dst, ifp, inm);
    325 		if (inm != NULL &&
    326 		   (imo == NULL || imo->imo_multicast_loop)) {
    327 			/*
    328 			 * If we belong to the destination multicast group
    329 			 * on the outgoing interface, and the caller did not
    330 			 * forbid loopback, loop back a copy.
    331 			 */
    332 			ip_mloopback(ifp, m, dst);
    333 		}
    334 #ifdef MROUTING
    335 		else {
    336 			/*
    337 			 * If we are acting as a multicast router, perform
    338 			 * multicast forwarding as if the packet had just
    339 			 * arrived on the interface to which we are about
    340 			 * to send.  The multicast forwarding function
    341 			 * recursively calls this function, using the
    342 			 * IP_FORWARDING flag to prevent infinite recursion.
    343 			 *
    344 			 * Multicasts that are looped back by ip_mloopback(),
    345 			 * above, will be forwarded by the ip_input() routine,
    346 			 * if necessary.
    347 			 */
    348 			extern struct socket *ip_mrouter;
    349 
    350 			if (ip_mrouter && (flags & IP_FORWARDING) == 0) {
    351 				if (ip_mforward(m, ifp) != 0) {
    352 					m_freem(m);
    353 					goto done;
    354 				}
    355 			}
    356 		}
    357 #endif
    358 		/*
    359 		 * Multicasts with a time-to-live of zero may be looped-
    360 		 * back, above, but must not be transmitted on a network.
    361 		 * Also, multicasts addressed to the loopback interface
    362 		 * are not sent -- the above call to ip_mloopback() will
    363 		 * loop back a copy if this host actually belongs to the
    364 		 * destination group on the loopback interface.
    365 		 */
    366 		if (ip->ip_ttl == 0 || (ifp->if_flags & IFF_LOOPBACK) != 0) {
    367 			m_freem(m);
    368 			goto done;
    369 		}
    370 
    371 		goto sendit;
    372 	}
    373 #ifndef notdef
    374 	/*
    375 	 * If source address not specified yet, use address
    376 	 * of outgoing interface.
    377 	 */
    378 	if (in_nullhost(ip->ip_src))
    379 		ip->ip_src = ia->ia_addr.sin_addr;
    380 #endif
    381 
    382 	/*
    383 	 * packets with Class-D address as source are not valid per
    384 	 * RFC 1112
    385 	 */
    386 	if (IN_MULTICAST(ip->ip_src.s_addr)) {
    387 		ipstat.ips_odropped++;
    388 		error = EADDRNOTAVAIL;
    389 		goto bad;
    390 	}
    391 
    392 	/*
    393 	 * Look for broadcast address and
    394 	 * and verify user is allowed to send
    395 	 * such a packet.
    396 	 */
    397 	if (in_broadcast(dst->sin_addr, ifp)) {
    398 		if ((ifp->if_flags & IFF_BROADCAST) == 0) {
    399 			error = EADDRNOTAVAIL;
    400 			goto bad;
    401 		}
    402 		if ((flags & IP_ALLOWBROADCAST) == 0) {
    403 			error = EACCES;
    404 			goto bad;
    405 		}
    406 		/* don't allow broadcast messages to be fragmented */
    407 		if ((u_int16_t)ip->ip_len > ifp->if_mtu) {
    408 			error = EMSGSIZE;
    409 			goto bad;
    410 		}
    411 		m->m_flags |= M_BCAST;
    412 	} else
    413 		m->m_flags &= ~M_BCAST;
    414 
    415 sendit:
    416 	/*
    417 	 * If we're doing Path MTU Discovery, we need to set DF unless
    418 	 * the route's MTU is locked.
    419 	 */
    420 	if ((flags & IP_MTUDISC) != 0 && ro->ro_rt != NULL &&
    421 	    (ro->ro_rt->rt_rmx.rmx_locks & RTV_MTU) == 0)
    422 		ip->ip_off |= IP_DF;
    423 
    424 	/*
    425 	 * Remember the current ip_len and ip_off, and swap them into
    426 	 * network order.
    427 	 */
    428 	ip_len = ip->ip_len;
    429 
    430 	HTONS(ip->ip_len);
    431 	HTONS(ip->ip_off);
    432 
    433 #ifdef IPSEC
    434 	/* get SP for this packet */
    435 	if (so == NULL)
    436 		sp = ipsec4_getpolicybyaddr(m, IPSEC_DIR_OUTBOUND, flags, &error);
    437 	else
    438 		sp = ipsec4_getpolicybysock(m, IPSEC_DIR_OUTBOUND, so, &error);
    439 
    440 	if (sp == NULL) {
    441 		ipsecstat.out_inval++;
    442 		goto bad;
    443 	}
    444 
    445 	error = 0;
    446 
    447 	/* check policy */
    448 	switch (sp->policy) {
    449 	case IPSEC_POLICY_DISCARD:
    450 		/*
    451 		 * This packet is just discarded.
    452 		 */
    453 		ipsecstat.out_polvio++;
    454 		goto bad;
    455 
    456 	case IPSEC_POLICY_BYPASS:
    457 	case IPSEC_POLICY_NONE:
    458 		/* no need to do IPsec. */
    459 		goto skip_ipsec;
    460 
    461 	case IPSEC_POLICY_IPSEC:
    462 		if (sp->req == NULL) {
    463 			/* XXX should be panic ? */
    464 			printf("ip_output: No IPsec request specified.\n");
    465 			error = EINVAL;
    466 			goto bad;
    467 		}
    468 		break;
    469 
    470 	case IPSEC_POLICY_ENTRUST:
    471 	default:
    472 		printf("ip_output: Invalid policy found. %d\n", sp->policy);
    473 	}
    474 
    475 	/*
    476 	 * ipsec4_output() expects ip_len and ip_off in network
    477 	 * order.  They have been set to network order above.
    478 	 */
    479 
    480     {
    481 	struct ipsec_output_state state;
    482 	bzero(&state, sizeof(state));
    483 	state.m = m;
    484 	if (flags & IP_ROUTETOIF) {
    485 		state.ro = &iproute;
    486 		bzero(&iproute, sizeof(iproute));
    487 	} else
    488 		state.ro = ro;
    489 	state.dst = (struct sockaddr *)dst;
    490 
    491 	/*
    492 	 * We can't defer the checksum of payload data if
    493 	 * we're about to encrypt/authenticate it.
    494 	 *
    495 	 * XXX When we support crypto offloading functions of
    496 	 * XXX network interfaces, we need to reconsider this,
    497 	 * XXX since it's likely that they'll support checksumming,
    498 	 * XXX as well.
    499 	 */
    500 	if (m->m_pkthdr.csum_flags & (M_CSUM_TCPv4|M_CSUM_UDPv4)) {
    501 		in_delayed_cksum(m);
    502 		m->m_pkthdr.csum_flags &= ~(M_CSUM_TCPv4|M_CSUM_UDPv4);
    503 	}
    504 
    505 	error = ipsec4_output(&state, sp, flags);
    506 
    507 	m = state.m;
    508 	if (flags & IP_ROUTETOIF) {
    509 		/*
    510 		 * if we have tunnel mode SA, we may need to ignore
    511 		 * IP_ROUTETOIF.
    512 		 */
    513 		if (state.ro != &iproute || state.ro->ro_rt != NULL) {
    514 			flags &= ~IP_ROUTETOIF;
    515 			ro = state.ro;
    516 		}
    517 	} else
    518 		ro = state.ro;
    519 	dst = (struct sockaddr_in *)state.dst;
    520 	if (error) {
    521 		/* mbuf is already reclaimed in ipsec4_output. */
    522 		m0 = NULL;
    523 		switch (error) {
    524 		case EHOSTUNREACH:
    525 		case ENETUNREACH:
    526 		case EMSGSIZE:
    527 		case ENOBUFS:
    528 		case ENOMEM:
    529 			break;
    530 		default:
    531 			printf("ip4_output (ipsec): error code %d\n", error);
    532 			/*fall through*/
    533 		case ENOENT:
    534 			/* don't show these error codes to the user */
    535 			error = 0;
    536 			break;
    537 		}
    538 		goto bad;
    539 	}
    540 
    541 	/* be sure to update variables that are affected by ipsec4_output() */
    542 	ip = mtod(m, struct ip *);
    543 #ifdef _IP_VHL
    544 	hlen = IP_VHL_HL(ip->ip_vhl) << 2;
    545 #else
    546 	hlen = ip->ip_hl << 2;
    547 #endif
    548 	ip_len = ntohs(ip->ip_len);
    549 
    550 	if (ro->ro_rt == NULL) {
    551 		if ((flags & IP_ROUTETOIF) == 0) {
    552 			printf("ip_output: "
    553 				"can't update route after IPsec processing\n");
    554 			error = EHOSTUNREACH;	/*XXX*/
    555 			goto bad;
    556 		}
    557 	} else {
    558 		/* nobody uses ia beyond here */
    559 		if (state.encap)
    560 			ifp = ro->ro_rt->rt_ifp;
    561 	}
    562     }
    563 
    564 skip_ipsec:
    565 #endif /*IPSEC*/
    566 
    567 #ifdef PFIL_HOOKS
    568 	/*
    569 	 * Run through list of hooks for output packets.
    570 	 */
    571 	if ((error = pfil_run_hooks(&inet_pfil_hook, &m, ifp,
    572 				    PFIL_OUT)) != 0)
    573 		goto done;
    574 	if (m == NULL)
    575 		goto done;
    576 
    577 	ip = mtod(m, struct ip *);
    578 #endif /* PFIL_HOOKS */
    579 
    580 	/*
    581 	 * If small enough for mtu of path, can just send directly.
    582 	 */
    583 	if (ip_len <= mtu) {
    584 #if IFA_STATS
    585 		/*
    586 		 * search for the source address structure to
    587 		 * maintain output statistics.
    588 		 */
    589 		INADDR_TO_IA(ip->ip_src, ia);
    590 		if (ia)
    591 			ia->ia_ifa.ifa_data.ifad_outbytes += ip_len;
    592 #endif
    593 		/*
    594 		 * Always initialize the sum to 0!  Some HW assisted
    595 		 * checksumming requires this.
    596 		 */
    597 		ip->ip_sum = 0;
    598 		m->m_pkthdr.csum_flags |= M_CSUM_IPv4;
    599 
    600 		sw_csum = m->m_pkthdr.csum_flags & ~ifp->if_csum_flags_tx;
    601 
    602 		/*
    603 		 * Perform any checksums that the hardware can't do
    604 		 * for us.
    605 		 *
    606 		 * XXX Does any hardware require the {th,uh}_sum
    607 		 * XXX fields to be 0?
    608 		 */
    609 		if (sw_csum & M_CSUM_IPv4)
    610 			ip->ip_sum = in_cksum(m, hlen);
    611 		if (sw_csum & (M_CSUM_TCPv4|M_CSUM_UDPv4)) {
    612 			in_delayed_cksum(m);
    613 			sw_csum &= ~(M_CSUM_TCPv4|M_CSUM_UDPv4);
    614 		}
    615 		m->m_pkthdr.csum_flags &= ifp->if_csum_flags_tx;
    616 
    617 #ifdef IPSEC
    618 		/* clean ipsec history once it goes out of the node */
    619 		ipsec_delaux(m);
    620 #endif
    621 		error = (*ifp->if_output)(ifp, m, sintosa(dst), ro->ro_rt);
    622 		goto done;
    623 	}
    624 
    625 	/*
    626 	 * We can't use HW checksumming if we're about to
    627 	 * to fragment the packet.
    628 	 *
    629 	 * XXX Some hardware can do this.
    630 	 */
    631 	if (m->m_pkthdr.csum_flags & (M_CSUM_TCPv4|M_CSUM_UDPv4)) {
    632 		in_delayed_cksum(m);
    633 		m->m_pkthdr.csum_flags &= ~(M_CSUM_TCPv4|M_CSUM_UDPv4);
    634 	}
    635 
    636 	/*
    637 	 * Too large for interface; fragment if possible.
    638 	 * Must be able to put at least 8 bytes per fragment.
    639 	 *
    640 	 * Note we swap ip_len and ip_off into host order to make
    641 	 * the logic below a little simpler.
    642 	 */
    643 
    644 	NTOHS(ip->ip_len);
    645 	NTOHS(ip->ip_off);
    646 
    647 	if (ip->ip_off & IP_DF) {
    648 		if (flags & IP_RETURNMTU)
    649 			*mtu_p = mtu;
    650 		error = EMSGSIZE;
    651 		ipstat.ips_cantfrag++;
    652 		goto bad;
    653 	}
    654 	len = (mtu - hlen) &~ 7;
    655 	if (len < 8) {
    656 		error = EMSGSIZE;
    657 		goto bad;
    658 	}
    659 
    660     {
    661 	int mhlen, firstlen = len;
    662 	struct mbuf **mnext = &m->m_nextpkt;
    663 	int fragments = 0;
    664 	int s;
    665 
    666 	/*
    667 	 * Loop through length of segment after first fragment,
    668 	 * make new header and copy data of each part and link onto chain.
    669 	 */
    670 	m0 = m;
    671 	mhlen = sizeof (struct ip);
    672 	for (off = hlen + len; off < (u_int16_t)ip->ip_len; off += len) {
    673 		MGETHDR(m, M_DONTWAIT, MT_HEADER);
    674 		if (m == 0) {
    675 			error = ENOBUFS;
    676 			ipstat.ips_odropped++;
    677 			goto sendorfree;
    678 		}
    679 		*mnext = m;
    680 		mnext = &m->m_nextpkt;
    681 		m->m_data += max_linkhdr;
    682 		mhip = mtod(m, struct ip *);
    683 		*mhip = *ip;
    684 		/* we must inherit MCAST and BCAST flags */
    685 		m->m_flags |= m0->m_flags & (M_MCAST|M_BCAST);
    686 		if (hlen > sizeof (struct ip)) {
    687 			mhlen = ip_optcopy(ip, mhip) + sizeof (struct ip);
    688 			mhip->ip_hl = mhlen >> 2;
    689 		}
    690 		m->m_len = mhlen;
    691 		mhip->ip_off = ((off - hlen) >> 3) + (ip->ip_off & ~IP_MF);
    692 		if (ip->ip_off & IP_MF)
    693 			mhip->ip_off |= IP_MF;
    694 		if (off + len >= (u_int16_t)ip->ip_len)
    695 			len = (u_int16_t)ip->ip_len - off;
    696 		else
    697 			mhip->ip_off |= IP_MF;
    698 		mhip->ip_len = htons((u_int16_t)(len + mhlen));
    699 		m->m_next = m_copy(m0, off, len);
    700 		if (m->m_next == 0) {
    701 			error = ENOBUFS;	/* ??? */
    702 			ipstat.ips_odropped++;
    703 			goto sendorfree;
    704 		}
    705 		m->m_pkthdr.len = mhlen + len;
    706 		m->m_pkthdr.rcvif = (struct ifnet *)0;
    707 		HTONS(mhip->ip_off);
    708 		mhip->ip_sum = 0;
    709 		mhip->ip_sum = in_cksum(m, mhlen);
    710 		ipstat.ips_ofragments++;
    711 		fragments++;
    712 	}
    713 	/*
    714 	 * Update first fragment by trimming what's been copied out
    715 	 * and updating header, then send each fragment (in order).
    716 	 */
    717 	m = m0;
    718 	m_adj(m, hlen + firstlen - (u_int16_t)ip->ip_len);
    719 	m->m_pkthdr.len = hlen + firstlen;
    720 	ip->ip_len = htons((u_int16_t)m->m_pkthdr.len);
    721 	ip->ip_off |= IP_MF;
    722 	HTONS(ip->ip_off);
    723 	ip->ip_sum = 0;
    724 	ip->ip_sum = in_cksum(m, hlen);
    725 sendorfree:
    726 	/*
    727 	 * If there is no room for all the fragments, don't queue
    728 	 * any of them.
    729 	 */
    730 	s = splnet();
    731 	if (ifp->if_snd.ifq_maxlen - ifp->if_snd.ifq_len < fragments)
    732 		error = ENOBUFS;
    733 	splx(s);
    734 	for (m = m0; m; m = m0) {
    735 		m0 = m->m_nextpkt;
    736 		m->m_nextpkt = 0;
    737 		if (error == 0) {
    738 #if IFA_STATS
    739 			/*
    740 			 * search for the source address structure to
    741 			 * maintain output statistics.
    742 			 */
    743 			INADDR_TO_IA(ip->ip_src, ia);
    744 			if (ia) {
    745 				ia->ia_ifa.ifa_data.ifad_outbytes +=
    746 					ntohs(ip->ip_len);
    747 			}
    748 #endif
    749 #ifdef IPSEC
    750 			/* clean ipsec history once it goes out of the node */
    751 			ipsec_delaux(m);
    752 #endif
    753 			error = (*ifp->if_output)(ifp, m, sintosa(dst),
    754 			    ro->ro_rt);
    755 		} else
    756 			m_freem(m);
    757 	}
    758 
    759 	if (error == 0)
    760 		ipstat.ips_fragmented++;
    761     }
    762 done:
    763 	if (ro == &iproute && (flags & IP_ROUTETOIF) == 0 && ro->ro_rt) {
    764 		RTFREE(ro->ro_rt);
    765 		ro->ro_rt = 0;
    766 	}
    767 
    768 #ifdef IPSEC
    769 	if (sp != NULL) {
    770 		KEYDEBUG(KEYDEBUG_IPSEC_STAMP,
    771 			printf("DP ip_output call free SP:%p\n", sp));
    772 		key_freesp(sp);
    773 	}
    774 #endif /* IPSEC */
    775 
    776 	return (error);
    777 bad:
    778 	m_freem(m);
    779 	goto done;
    780 }
    781 
    782 /*
    783  * Process a delayed payload checksum calculation.
    784  */
    785 void
    786 in_delayed_cksum(struct mbuf *m)
    787 {
    788 	struct ip *ip;
    789 	u_int16_t csum, offset;
    790 
    791 	ip = mtod(m, struct ip *);
    792 	offset = ip->ip_hl << 2;
    793 	csum = in4_cksum(m, 0, offset, ntohs(ip->ip_len) - offset);
    794 	if (csum == 0 && (m->m_pkthdr.csum_flags & M_CSUM_UDPv4) != 0)
    795 		csum = 0xffff;
    796 
    797 	offset += m->m_pkthdr.csum_data;	/* checksum offset */
    798 
    799 	if ((offset + sizeof(u_int16_t)) > m->m_len) {
    800 		/* This happen when ip options were inserted
    801 		printf("in_delayed_cksum: pullup len %d off %d proto %d\n",
    802 		    m->m_len, offset, ip->ip_p);
    803 		 */
    804 		m_copyback(m, offset, sizeof(csum), (caddr_t) &csum);
    805 	} else
    806 		*(u_int16_t *)(mtod(m, caddr_t) + offset) = csum;
    807 }
    808 
    809 /*
    810  * Determine the maximum length of the options to be inserted;
    811  * we would far rather allocate too much space rather than too little.
    812  */
    813 
    814 u_int
    815 ip_optlen(inp)
    816 	struct inpcb *inp;
    817 {
    818 	struct mbuf *m = inp->inp_options;
    819 
    820 	if (m && m->m_len > offsetof(struct ipoption, ipopt_dst))
    821 		return(m->m_len - offsetof(struct ipoption, ipopt_dst));
    822 	else
    823 		return 0;
    824 }
    825 
    826 
    827 /*
    828  * Insert IP options into preformed packet.
    829  * Adjust IP destination as required for IP source routing,
    830  * as indicated by a non-zero in_addr at the start of the options.
    831  */
    832 static struct mbuf *
    833 ip_insertoptions(m, opt, phlen)
    834 	struct mbuf *m;
    835 	struct mbuf *opt;
    836 	int *phlen;
    837 {
    838 	struct ipoption *p = mtod(opt, struct ipoption *);
    839 	struct mbuf *n;
    840 	struct ip *ip = mtod(m, struct ip *);
    841 	unsigned optlen;
    842 
    843 	optlen = opt->m_len - sizeof(p->ipopt_dst);
    844 	if (optlen + (u_int16_t)ip->ip_len > IP_MAXPACKET)
    845 		return (m);		/* XXX should fail */
    846 	if (!in_nullhost(p->ipopt_dst))
    847 		ip->ip_dst = p->ipopt_dst;
    848 	if (m->m_flags & M_EXT || m->m_data - optlen < m->m_pktdat) {
    849 		MGETHDR(n, M_DONTWAIT, MT_HEADER);
    850 		if (n == 0)
    851 			return (m);
    852 		M_COPY_PKTHDR(n, m);
    853 		m->m_flags &= ~M_PKTHDR;
    854 		m->m_len -= sizeof(struct ip);
    855 		m->m_data += sizeof(struct ip);
    856 		n->m_next = m;
    857 		m = n;
    858 		m->m_len = optlen + sizeof(struct ip);
    859 		m->m_data += max_linkhdr;
    860 		bcopy((caddr_t)ip, mtod(m, caddr_t), sizeof(struct ip));
    861 	} else {
    862 		m->m_data -= optlen;
    863 		m->m_len += optlen;
    864 		memmove(mtod(m, caddr_t), ip, sizeof(struct ip));
    865 	}
    866 	m->m_pkthdr.len += optlen;
    867 	ip = mtod(m, struct ip *);
    868 	bcopy((caddr_t)p->ipopt_list, (caddr_t)(ip + 1), (unsigned)optlen);
    869 	*phlen = sizeof(struct ip) + optlen;
    870 	ip->ip_len += optlen;
    871 	return (m);
    872 }
    873 
    874 /*
    875  * Copy options from ip to jp,
    876  * omitting those not copied during fragmentation.
    877  */
    878 int
    879 ip_optcopy(ip, jp)
    880 	struct ip *ip, *jp;
    881 {
    882 	u_char *cp, *dp;
    883 	int opt, optlen, cnt;
    884 
    885 	cp = (u_char *)(ip + 1);
    886 	dp = (u_char *)(jp + 1);
    887 	cnt = (ip->ip_hl << 2) - sizeof (struct ip);
    888 	for (; cnt > 0; cnt -= optlen, cp += optlen) {
    889 		opt = cp[0];
    890 		if (opt == IPOPT_EOL)
    891 			break;
    892 		if (opt == IPOPT_NOP) {
    893 			/* Preserve for IP mcast tunnel's LSRR alignment. */
    894 			*dp++ = IPOPT_NOP;
    895 			optlen = 1;
    896 			continue;
    897 		}
    898 #ifdef DIAGNOSTIC
    899 		if (cnt < IPOPT_OLEN + sizeof(*cp))
    900 			panic("malformed IPv4 option passed to ip_optcopy");
    901 #endif
    902 		optlen = cp[IPOPT_OLEN];
    903 #ifdef DIAGNOSTIC
    904 		if (optlen < IPOPT_OLEN + sizeof(*cp) || optlen > cnt)
    905 			panic("malformed IPv4 option passed to ip_optcopy");
    906 #endif
    907 		/* bogus lengths should have been caught by ip_dooptions */
    908 		if (optlen > cnt)
    909 			optlen = cnt;
    910 		if (IPOPT_COPIED(opt)) {
    911 			bcopy((caddr_t)cp, (caddr_t)dp, (unsigned)optlen);
    912 			dp += optlen;
    913 		}
    914 	}
    915 	for (optlen = dp - (u_char *)(jp+1); optlen & 0x3; optlen++)
    916 		*dp++ = IPOPT_EOL;
    917 	return (optlen);
    918 }
    919 
    920 /*
    921  * IP socket option processing.
    922  */
    923 int
    924 ip_ctloutput(op, so, level, optname, mp)
    925 	int op;
    926 	struct socket *so;
    927 	int level, optname;
    928 	struct mbuf **mp;
    929 {
    930 	struct inpcb *inp = sotoinpcb(so);
    931 	struct mbuf *m = *mp;
    932 	int optval = 0;
    933 	int error = 0;
    934 #ifdef IPSEC
    935 #ifdef __NetBSD__
    936 	struct proc *p = (curproc ? curproc->l_proc : 0);	/*XXX*/
    937 #endif
    938 #endif
    939 
    940 	if (level != IPPROTO_IP) {
    941 		error = EINVAL;
    942 		if (op == PRCO_SETOPT && *mp)
    943 			(void) m_free(*mp);
    944 	} else switch (op) {
    945 
    946 	case PRCO_SETOPT:
    947 		switch (optname) {
    948 		case IP_OPTIONS:
    949 #ifdef notyet
    950 		case IP_RETOPTS:
    951 			return (ip_pcbopts(optname, &inp->inp_options, m));
    952 #else
    953 			return (ip_pcbopts(&inp->inp_options, m));
    954 #endif
    955 
    956 		case IP_TOS:
    957 		case IP_TTL:
    958 		case IP_RECVOPTS:
    959 		case IP_RECVRETOPTS:
    960 		case IP_RECVDSTADDR:
    961 		case IP_RECVIF:
    962 			if (m == NULL || m->m_len != sizeof(int))
    963 				error = EINVAL;
    964 			else {
    965 				optval = *mtod(m, int *);
    966 				switch (optname) {
    967 
    968 				case IP_TOS:
    969 					inp->inp_ip.ip_tos = optval;
    970 					break;
    971 
    972 				case IP_TTL:
    973 					inp->inp_ip.ip_ttl = optval;
    974 					break;
    975 #define	OPTSET(bit) \
    976 	if (optval) \
    977 		inp->inp_flags |= bit; \
    978 	else \
    979 		inp->inp_flags &= ~bit;
    980 
    981 				case IP_RECVOPTS:
    982 					OPTSET(INP_RECVOPTS);
    983 					break;
    984 
    985 				case IP_RECVRETOPTS:
    986 					OPTSET(INP_RECVRETOPTS);
    987 					break;
    988 
    989 				case IP_RECVDSTADDR:
    990 					OPTSET(INP_RECVDSTADDR);
    991 					break;
    992 
    993 				case IP_RECVIF:
    994 					OPTSET(INP_RECVIF);
    995 					break;
    996 				}
    997 			}
    998 			break;
    999 #undef OPTSET
   1000 
   1001 		case IP_MULTICAST_IF:
   1002 		case IP_MULTICAST_TTL:
   1003 		case IP_MULTICAST_LOOP:
   1004 		case IP_ADD_MEMBERSHIP:
   1005 		case IP_DROP_MEMBERSHIP:
   1006 			error = ip_setmoptions(optname, &inp->inp_moptions, m);
   1007 			break;
   1008 
   1009 		case IP_PORTRANGE:
   1010 			if (m == 0 || m->m_len != sizeof(int))
   1011 				error = EINVAL;
   1012 			else {
   1013 				optval = *mtod(m, int *);
   1014 
   1015 				switch (optval) {
   1016 
   1017 				case IP_PORTRANGE_DEFAULT:
   1018 				case IP_PORTRANGE_HIGH:
   1019 					inp->inp_flags &= ~(INP_LOWPORT);
   1020 					break;
   1021 
   1022 				case IP_PORTRANGE_LOW:
   1023 					inp->inp_flags |= INP_LOWPORT;
   1024 					break;
   1025 
   1026 				default:
   1027 					error = EINVAL;
   1028 					break;
   1029 				}
   1030 			}
   1031 			break;
   1032 
   1033 #ifdef IPSEC
   1034 		case IP_IPSEC_POLICY:
   1035 		{
   1036 			caddr_t req = NULL;
   1037 			size_t len = 0;
   1038 			int priv = 0;
   1039 
   1040 #ifdef __NetBSD__
   1041 			if (p == 0 || suser(p->p_ucred, &p->p_acflag))
   1042 				priv = 0;
   1043 			else
   1044 				priv = 1;
   1045 #else
   1046 			priv = (in6p->in6p_socket->so_state & SS_PRIV);
   1047 #endif
   1048 			if (m) {
   1049 				req = mtod(m, caddr_t);
   1050 				len = m->m_len;
   1051 			}
   1052 			error = ipsec4_set_policy(inp, optname, req, len, priv);
   1053 			break;
   1054 		    }
   1055 #endif /*IPSEC*/
   1056 
   1057 		default:
   1058 			error = ENOPROTOOPT;
   1059 			break;
   1060 		}
   1061 		if (m)
   1062 			(void)m_free(m);
   1063 		break;
   1064 
   1065 	case PRCO_GETOPT:
   1066 		switch (optname) {
   1067 		case IP_OPTIONS:
   1068 		case IP_RETOPTS:
   1069 			*mp = m = m_get(M_WAIT, MT_SOOPTS);
   1070 			if (inp->inp_options) {
   1071 				m->m_len = inp->inp_options->m_len;
   1072 				bcopy(mtod(inp->inp_options, caddr_t),
   1073 				    mtod(m, caddr_t), (unsigned)m->m_len);
   1074 			} else
   1075 				m->m_len = 0;
   1076 			break;
   1077 
   1078 		case IP_TOS:
   1079 		case IP_TTL:
   1080 		case IP_RECVOPTS:
   1081 		case IP_RECVRETOPTS:
   1082 		case IP_RECVDSTADDR:
   1083 		case IP_RECVIF:
   1084 		case IP_ERRORMTU:
   1085 			*mp = m = m_get(M_WAIT, MT_SOOPTS);
   1086 			m->m_len = sizeof(int);
   1087 			switch (optname) {
   1088 
   1089 			case IP_TOS:
   1090 				optval = inp->inp_ip.ip_tos;
   1091 				break;
   1092 
   1093 			case IP_TTL:
   1094 				optval = inp->inp_ip.ip_ttl;
   1095 				break;
   1096 
   1097 			case IP_ERRORMTU:
   1098 				optval = inp->inp_errormtu;
   1099 				break;
   1100 
   1101 #define	OPTBIT(bit)	(inp->inp_flags & bit ? 1 : 0)
   1102 
   1103 			case IP_RECVOPTS:
   1104 				optval = OPTBIT(INP_RECVOPTS);
   1105 				break;
   1106 
   1107 			case IP_RECVRETOPTS:
   1108 				optval = OPTBIT(INP_RECVRETOPTS);
   1109 				break;
   1110 
   1111 			case IP_RECVDSTADDR:
   1112 				optval = OPTBIT(INP_RECVDSTADDR);
   1113 				break;
   1114 
   1115 			case IP_RECVIF:
   1116 				optval = OPTBIT(INP_RECVIF);
   1117 				break;
   1118 			}
   1119 			*mtod(m, int *) = optval;
   1120 			break;
   1121 
   1122 #ifdef IPSEC
   1123 		case IP_IPSEC_POLICY:
   1124 		{
   1125 			caddr_t req = NULL;
   1126 			size_t len = 0;
   1127 
   1128 			if (m) {
   1129 				req = mtod(m, caddr_t);
   1130 				len = m->m_len;
   1131 			}
   1132 			error = ipsec4_get_policy(inp, req, len, mp);
   1133 			break;
   1134 		}
   1135 #endif /*IPSEC*/
   1136 
   1137 		case IP_MULTICAST_IF:
   1138 		case IP_MULTICAST_TTL:
   1139 		case IP_MULTICAST_LOOP:
   1140 		case IP_ADD_MEMBERSHIP:
   1141 		case IP_DROP_MEMBERSHIP:
   1142 			error = ip_getmoptions(optname, inp->inp_moptions, mp);
   1143 			break;
   1144 
   1145 		case IP_PORTRANGE:
   1146 			*mp = m = m_get(M_WAIT, MT_SOOPTS);
   1147 			m->m_len = sizeof(int);
   1148 
   1149 			if (inp->inp_flags & INP_LOWPORT)
   1150 				optval = IP_PORTRANGE_LOW;
   1151 			else
   1152 				optval = IP_PORTRANGE_DEFAULT;
   1153 
   1154 			*mtod(m, int *) = optval;
   1155 			break;
   1156 
   1157 		default:
   1158 			error = ENOPROTOOPT;
   1159 			break;
   1160 		}
   1161 		break;
   1162 	}
   1163 	return (error);
   1164 }
   1165 
   1166 /*
   1167  * Set up IP options in pcb for insertion in output packets.
   1168  * Store in mbuf with pointer in pcbopt, adding pseudo-option
   1169  * with destination address if source routed.
   1170  */
   1171 int
   1172 #ifdef notyet
   1173 ip_pcbopts(optname, pcbopt, m)
   1174 	int optname;
   1175 #else
   1176 ip_pcbopts(pcbopt, m)
   1177 #endif
   1178 	struct mbuf **pcbopt;
   1179 	struct mbuf *m;
   1180 {
   1181 	int cnt, optlen;
   1182 	u_char *cp;
   1183 	u_char opt;
   1184 
   1185 	/* turn off any old options */
   1186 	if (*pcbopt)
   1187 		(void)m_free(*pcbopt);
   1188 	*pcbopt = 0;
   1189 	if (m == (struct mbuf *)0 || m->m_len == 0) {
   1190 		/*
   1191 		 * Only turning off any previous options.
   1192 		 */
   1193 		if (m)
   1194 			(void)m_free(m);
   1195 		return (0);
   1196 	}
   1197 
   1198 #ifndef	__vax__
   1199 	if (m->m_len % sizeof(int32_t))
   1200 		goto bad;
   1201 #endif
   1202 	/*
   1203 	 * IP first-hop destination address will be stored before
   1204 	 * actual options; move other options back
   1205 	 * and clear it when none present.
   1206 	 */
   1207 	if (m->m_data + m->m_len + sizeof(struct in_addr) >= &m->m_dat[MLEN])
   1208 		goto bad;
   1209 	cnt = m->m_len;
   1210 	m->m_len += sizeof(struct in_addr);
   1211 	cp = mtod(m, u_char *) + sizeof(struct in_addr);
   1212 	memmove(cp, mtod(m, caddr_t), (unsigned)cnt);
   1213 	bzero(mtod(m, caddr_t), sizeof(struct in_addr));
   1214 
   1215 	for (; cnt > 0; cnt -= optlen, cp += optlen) {
   1216 		opt = cp[IPOPT_OPTVAL];
   1217 		if (opt == IPOPT_EOL)
   1218 			break;
   1219 		if (opt == IPOPT_NOP)
   1220 			optlen = 1;
   1221 		else {
   1222 			if (cnt < IPOPT_OLEN + sizeof(*cp))
   1223 				goto bad;
   1224 			optlen = cp[IPOPT_OLEN];
   1225 			if (optlen < IPOPT_OLEN  + sizeof(*cp) || optlen > cnt)
   1226 				goto bad;
   1227 		}
   1228 		switch (opt) {
   1229 
   1230 		default:
   1231 			break;
   1232 
   1233 		case IPOPT_LSRR:
   1234 		case IPOPT_SSRR:
   1235 			/*
   1236 			 * user process specifies route as:
   1237 			 *	->A->B->C->D
   1238 			 * D must be our final destination (but we can't
   1239 			 * check that since we may not have connected yet).
   1240 			 * A is first hop destination, which doesn't appear in
   1241 			 * actual IP option, but is stored before the options.
   1242 			 */
   1243 			if (optlen < IPOPT_MINOFF - 1 + sizeof(struct in_addr))
   1244 				goto bad;
   1245 			m->m_len -= sizeof(struct in_addr);
   1246 			cnt -= sizeof(struct in_addr);
   1247 			optlen -= sizeof(struct in_addr);
   1248 			cp[IPOPT_OLEN] = optlen;
   1249 			/*
   1250 			 * Move first hop before start of options.
   1251 			 */
   1252 			bcopy((caddr_t)&cp[IPOPT_OFFSET+1], mtod(m, caddr_t),
   1253 			    sizeof(struct in_addr));
   1254 			/*
   1255 			 * Then copy rest of options back
   1256 			 * to close up the deleted entry.
   1257 			 */
   1258 			memmove(&cp[IPOPT_OFFSET+1],
   1259                             (caddr_t)(&cp[IPOPT_OFFSET+1] + sizeof(struct in_addr)),
   1260 			    (unsigned)cnt + sizeof(struct in_addr));
   1261 			break;
   1262 		}
   1263 	}
   1264 	if (m->m_len > MAX_IPOPTLEN + sizeof(struct in_addr))
   1265 		goto bad;
   1266 	*pcbopt = m;
   1267 	return (0);
   1268 
   1269 bad:
   1270 	(void)m_free(m);
   1271 	return (EINVAL);
   1272 }
   1273 
   1274 /*
   1275  * following RFC1724 section 3.3, 0.0.0.0/8 is interpreted as interface index.
   1276  */
   1277 static struct ifnet *
   1278 ip_multicast_if(a, ifindexp)
   1279 	struct in_addr *a;
   1280 	int *ifindexp;
   1281 {
   1282 	int ifindex;
   1283 	struct ifnet *ifp;
   1284 
   1285 	if (ifindexp)
   1286 		*ifindexp = 0;
   1287 	if (ntohl(a->s_addr) >> 24 == 0) {
   1288 		ifindex = ntohl(a->s_addr) & 0xffffff;
   1289 		if (ifindex < 0 || if_index < ifindex)
   1290 			return NULL;
   1291 		ifp = ifindex2ifnet[ifindex];
   1292 		if (ifindexp)
   1293 			*ifindexp = ifindex;
   1294 	} else {
   1295 		INADDR_TO_IFP(*a, ifp);
   1296 	}
   1297 	return ifp;
   1298 }
   1299 
   1300 /*
   1301  * Set the IP multicast options in response to user setsockopt().
   1302  */
   1303 int
   1304 ip_setmoptions(optname, imop, m)
   1305 	int optname;
   1306 	struct ip_moptions **imop;
   1307 	struct mbuf *m;
   1308 {
   1309 	int error = 0;
   1310 	u_char loop;
   1311 	int i;
   1312 	struct in_addr addr;
   1313 	struct ip_mreq *mreq;
   1314 	struct ifnet *ifp;
   1315 	struct ip_moptions *imo = *imop;
   1316 	struct route ro;
   1317 	struct sockaddr_in *dst;
   1318 	int ifindex;
   1319 
   1320 	if (imo == NULL) {
   1321 		/*
   1322 		 * No multicast option buffer attached to the pcb;
   1323 		 * allocate one and initialize to default values.
   1324 		 */
   1325 		imo = (struct ip_moptions *)malloc(sizeof(*imo), M_IPMOPTS,
   1326 		    M_WAITOK);
   1327 
   1328 		if (imo == NULL)
   1329 			return (ENOBUFS);
   1330 		*imop = imo;
   1331 		imo->imo_multicast_ifp = NULL;
   1332 		imo->imo_multicast_addr.s_addr = INADDR_ANY;
   1333 		imo->imo_multicast_ttl = IP_DEFAULT_MULTICAST_TTL;
   1334 		imo->imo_multicast_loop = IP_DEFAULT_MULTICAST_LOOP;
   1335 		imo->imo_num_memberships = 0;
   1336 	}
   1337 
   1338 	switch (optname) {
   1339 
   1340 	case IP_MULTICAST_IF:
   1341 		/*
   1342 		 * Select the interface for outgoing multicast packets.
   1343 		 */
   1344 		if (m == NULL || m->m_len != sizeof(struct in_addr)) {
   1345 			error = EINVAL;
   1346 			break;
   1347 		}
   1348 		addr = *(mtod(m, struct in_addr *));
   1349 		/*
   1350 		 * INADDR_ANY is used to remove a previous selection.
   1351 		 * When no interface is selected, a default one is
   1352 		 * chosen every time a multicast packet is sent.
   1353 		 */
   1354 		if (in_nullhost(addr)) {
   1355 			imo->imo_multicast_ifp = NULL;
   1356 			break;
   1357 		}
   1358 		/*
   1359 		 * The selected interface is identified by its local
   1360 		 * IP address.  Find the interface and confirm that
   1361 		 * it supports multicasting.
   1362 		 */
   1363 		ifp = ip_multicast_if(&addr, &ifindex);
   1364 		if (ifp == NULL || (ifp->if_flags & IFF_MULTICAST) == 0) {
   1365 			error = EADDRNOTAVAIL;
   1366 			break;
   1367 		}
   1368 		imo->imo_multicast_ifp = ifp;
   1369 		if (ifindex)
   1370 			imo->imo_multicast_addr = addr;
   1371 		else
   1372 			imo->imo_multicast_addr.s_addr = INADDR_ANY;
   1373 		break;
   1374 
   1375 	case IP_MULTICAST_TTL:
   1376 		/*
   1377 		 * Set the IP time-to-live for outgoing multicast packets.
   1378 		 */
   1379 		if (m == NULL || m->m_len != 1) {
   1380 			error = EINVAL;
   1381 			break;
   1382 		}
   1383 		imo->imo_multicast_ttl = *(mtod(m, u_char *));
   1384 		break;
   1385 
   1386 	case IP_MULTICAST_LOOP:
   1387 		/*
   1388 		 * Set the loopback flag for outgoing multicast packets.
   1389 		 * Must be zero or one.
   1390 		 */
   1391 		if (m == NULL || m->m_len != 1 ||
   1392 		   (loop = *(mtod(m, u_char *))) > 1) {
   1393 			error = EINVAL;
   1394 			break;
   1395 		}
   1396 		imo->imo_multicast_loop = loop;
   1397 		break;
   1398 
   1399 	case IP_ADD_MEMBERSHIP:
   1400 		/*
   1401 		 * Add a multicast group membership.
   1402 		 * Group must be a valid IP multicast address.
   1403 		 */
   1404 		if (m == NULL || m->m_len != sizeof(struct ip_mreq)) {
   1405 			error = EINVAL;
   1406 			break;
   1407 		}
   1408 		mreq = mtod(m, struct ip_mreq *);
   1409 		if (!IN_MULTICAST(mreq->imr_multiaddr.s_addr)) {
   1410 			error = EINVAL;
   1411 			break;
   1412 		}
   1413 		/*
   1414 		 * If no interface address was provided, use the interface of
   1415 		 * the route to the given multicast address.
   1416 		 */
   1417 		if (in_nullhost(mreq->imr_interface)) {
   1418 			bzero((caddr_t)&ro, sizeof(ro));
   1419 			ro.ro_rt = NULL;
   1420 			dst = satosin(&ro.ro_dst);
   1421 			dst->sin_len = sizeof(*dst);
   1422 			dst->sin_family = AF_INET;
   1423 			dst->sin_addr = mreq->imr_multiaddr;
   1424 			rtalloc(&ro);
   1425 			if (ro.ro_rt == NULL) {
   1426 				error = EADDRNOTAVAIL;
   1427 				break;
   1428 			}
   1429 			ifp = ro.ro_rt->rt_ifp;
   1430 			rtfree(ro.ro_rt);
   1431 		} else {
   1432 			ifp = ip_multicast_if(&mreq->imr_interface, NULL);
   1433 		}
   1434 		/*
   1435 		 * See if we found an interface, and confirm that it
   1436 		 * supports multicast.
   1437 		 */
   1438 		if (ifp == NULL || (ifp->if_flags & IFF_MULTICAST) == 0) {
   1439 			error = EADDRNOTAVAIL;
   1440 			break;
   1441 		}
   1442 		/*
   1443 		 * See if the membership already exists or if all the
   1444 		 * membership slots are full.
   1445 		 */
   1446 		for (i = 0; i < imo->imo_num_memberships; ++i) {
   1447 			if (imo->imo_membership[i]->inm_ifp == ifp &&
   1448 			    in_hosteq(imo->imo_membership[i]->inm_addr,
   1449 				      mreq->imr_multiaddr))
   1450 				break;
   1451 		}
   1452 		if (i < imo->imo_num_memberships) {
   1453 			error = EADDRINUSE;
   1454 			break;
   1455 		}
   1456 		if (i == IP_MAX_MEMBERSHIPS) {
   1457 			error = ETOOMANYREFS;
   1458 			break;
   1459 		}
   1460 		/*
   1461 		 * Everything looks good; add a new record to the multicast
   1462 		 * address list for the given interface.
   1463 		 */
   1464 		if ((imo->imo_membership[i] =
   1465 		    in_addmulti(&mreq->imr_multiaddr, ifp)) == NULL) {
   1466 			error = ENOBUFS;
   1467 			break;
   1468 		}
   1469 		++imo->imo_num_memberships;
   1470 		break;
   1471 
   1472 	case IP_DROP_MEMBERSHIP:
   1473 		/*
   1474 		 * Drop a multicast group membership.
   1475 		 * Group must be a valid IP multicast address.
   1476 		 */
   1477 		if (m == NULL || m->m_len != sizeof(struct ip_mreq)) {
   1478 			error = EINVAL;
   1479 			break;
   1480 		}
   1481 		mreq = mtod(m, struct ip_mreq *);
   1482 		if (!IN_MULTICAST(mreq->imr_multiaddr.s_addr)) {
   1483 			error = EINVAL;
   1484 			break;
   1485 		}
   1486 		/*
   1487 		 * If an interface address was specified, get a pointer
   1488 		 * to its ifnet structure.
   1489 		 */
   1490 		if (in_nullhost(mreq->imr_interface))
   1491 			ifp = NULL;
   1492 		else {
   1493 			ifp = ip_multicast_if(&mreq->imr_interface, NULL);
   1494 			if (ifp == NULL) {
   1495 				error = EADDRNOTAVAIL;
   1496 				break;
   1497 			}
   1498 		}
   1499 		/*
   1500 		 * Find the membership in the membership array.
   1501 		 */
   1502 		for (i = 0; i < imo->imo_num_memberships; ++i) {
   1503 			if ((ifp == NULL ||
   1504 			     imo->imo_membership[i]->inm_ifp == ifp) &&
   1505 			     in_hosteq(imo->imo_membership[i]->inm_addr,
   1506 				       mreq->imr_multiaddr))
   1507 				break;
   1508 		}
   1509 		if (i == imo->imo_num_memberships) {
   1510 			error = EADDRNOTAVAIL;
   1511 			break;
   1512 		}
   1513 		/*
   1514 		 * Give up the multicast address record to which the
   1515 		 * membership points.
   1516 		 */
   1517 		in_delmulti(imo->imo_membership[i]);
   1518 		/*
   1519 		 * Remove the gap in the membership array.
   1520 		 */
   1521 		for (++i; i < imo->imo_num_memberships; ++i)
   1522 			imo->imo_membership[i-1] = imo->imo_membership[i];
   1523 		--imo->imo_num_memberships;
   1524 		break;
   1525 
   1526 	default:
   1527 		error = EOPNOTSUPP;
   1528 		break;
   1529 	}
   1530 
   1531 	/*
   1532 	 * If all options have default values, no need to keep the mbuf.
   1533 	 */
   1534 	if (imo->imo_multicast_ifp == NULL &&
   1535 	    imo->imo_multicast_ttl == IP_DEFAULT_MULTICAST_TTL &&
   1536 	    imo->imo_multicast_loop == IP_DEFAULT_MULTICAST_LOOP &&
   1537 	    imo->imo_num_memberships == 0) {
   1538 		free(*imop, M_IPMOPTS);
   1539 		*imop = NULL;
   1540 	}
   1541 
   1542 	return (error);
   1543 }
   1544 
   1545 /*
   1546  * Return the IP multicast options in response to user getsockopt().
   1547  */
   1548 int
   1549 ip_getmoptions(optname, imo, mp)
   1550 	int optname;
   1551 	struct ip_moptions *imo;
   1552 	struct mbuf **mp;
   1553 {
   1554 	u_char *ttl;
   1555 	u_char *loop;
   1556 	struct in_addr *addr;
   1557 	struct in_ifaddr *ia;
   1558 
   1559 	*mp = m_get(M_WAIT, MT_SOOPTS);
   1560 
   1561 	switch (optname) {
   1562 
   1563 	case IP_MULTICAST_IF:
   1564 		addr = mtod(*mp, struct in_addr *);
   1565 		(*mp)->m_len = sizeof(struct in_addr);
   1566 		if (imo == NULL || imo->imo_multicast_ifp == NULL)
   1567 			*addr = zeroin_addr;
   1568 		else if (imo->imo_multicast_addr.s_addr) {
   1569 			/* return the value user has set */
   1570 			*addr = imo->imo_multicast_addr;
   1571 		} else {
   1572 			IFP_TO_IA(imo->imo_multicast_ifp, ia);
   1573 			*addr = ia ? ia->ia_addr.sin_addr : zeroin_addr;
   1574 		}
   1575 		return (0);
   1576 
   1577 	case IP_MULTICAST_TTL:
   1578 		ttl = mtod(*mp, u_char *);
   1579 		(*mp)->m_len = 1;
   1580 		*ttl = imo ? imo->imo_multicast_ttl
   1581 			   : IP_DEFAULT_MULTICAST_TTL;
   1582 		return (0);
   1583 
   1584 	case IP_MULTICAST_LOOP:
   1585 		loop = mtod(*mp, u_char *);
   1586 		(*mp)->m_len = 1;
   1587 		*loop = imo ? imo->imo_multicast_loop
   1588 			    : IP_DEFAULT_MULTICAST_LOOP;
   1589 		return (0);
   1590 
   1591 	default:
   1592 		return (EOPNOTSUPP);
   1593 	}
   1594 }
   1595 
   1596 /*
   1597  * Discard the IP multicast options.
   1598  */
   1599 void
   1600 ip_freemoptions(imo)
   1601 	struct ip_moptions *imo;
   1602 {
   1603 	int i;
   1604 
   1605 	if (imo != NULL) {
   1606 		for (i = 0; i < imo->imo_num_memberships; ++i)
   1607 			in_delmulti(imo->imo_membership[i]);
   1608 		free(imo, M_IPMOPTS);
   1609 	}
   1610 }
   1611 
   1612 /*
   1613  * Routine called from ip_output() to loop back a copy of an IP multicast
   1614  * packet to the input queue of a specified interface.  Note that this
   1615  * calls the output routine of the loopback "driver", but with an interface
   1616  * pointer that might NOT be &loif -- easier than replicating that code here.
   1617  */
   1618 static void
   1619 ip_mloopback(ifp, m, dst)
   1620 	struct ifnet *ifp;
   1621 	struct mbuf *m;
   1622 	struct sockaddr_in *dst;
   1623 {
   1624 	struct ip *ip;
   1625 	struct mbuf *copym;
   1626 
   1627 	copym = m_copy(m, 0, M_COPYALL);
   1628 	if (copym != NULL
   1629 	 && (copym->m_flags & M_EXT || copym->m_len < sizeof(struct ip)))
   1630 		copym = m_pullup(copym, sizeof(struct ip));
   1631 	if (copym != NULL) {
   1632 		/*
   1633 		 * We don't bother to fragment if the IP length is greater
   1634 		 * than the interface's MTU.  Can this possibly matter?
   1635 		 */
   1636 		ip = mtod(copym, struct ip *);
   1637 		HTONS(ip->ip_len);
   1638 		HTONS(ip->ip_off);
   1639 		ip->ip_sum = 0;
   1640 		ip->ip_sum = in_cksum(copym, ip->ip_hl << 2);
   1641 		(void) looutput(ifp, copym, sintosa(dst), NULL);
   1642 	}
   1643 }
   1644