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