Home | History | Annotate | Line # | Download | only in netinet
ip_output.c revision 1.83.2.3
      1 /*	$NetBSD: ip_output.c,v 1.83.2.3 2001/06/21 20:08:41 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;
    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;
    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 		/* XXX This should basically never happen. */
    797 		printf("in_delayed_cksum: pullup len %d off %d proto %d\n",
    798 		    m->m_len, offset, ip->ip_p);
    799 		m_copyback(m, offset, sizeof(csum), (caddr_t) &csum);
    800 	} else
    801 		*(u_int16_t *)(mtod(m, caddr_t) + offset) = csum;
    802 }
    803 
    804 /*
    805  * Determine the maximum length of the options to be inserted;
    806  * we would far rather allocate too much space rather than too little.
    807  */
    808 
    809 u_int
    810 ip_optlen(inp)
    811 	struct inpcb *inp;
    812 {
    813 	struct mbuf *m = inp->inp_options;
    814 
    815 	if (m && m->m_len > offsetof(struct ipoption, ipopt_dst))
    816 		return(m->m_len - offsetof(struct ipoption, ipopt_dst));
    817 	else
    818 		return 0;
    819 }
    820 
    821 
    822 /*
    823  * Insert IP options into preformed packet.
    824  * Adjust IP destination as required for IP source routing,
    825  * as indicated by a non-zero in_addr at the start of the options.
    826  */
    827 static struct mbuf *
    828 ip_insertoptions(m, opt, phlen)
    829 	struct mbuf *m;
    830 	struct mbuf *opt;
    831 	int *phlen;
    832 {
    833 	struct ipoption *p = mtod(opt, struct ipoption *);
    834 	struct mbuf *n;
    835 	struct ip *ip = mtod(m, struct ip *);
    836 	unsigned optlen;
    837 
    838 	optlen = opt->m_len - sizeof(p->ipopt_dst);
    839 	if (optlen + (u_int16_t)ip->ip_len > IP_MAXPACKET)
    840 		return (m);		/* XXX should fail */
    841 	if (!in_nullhost(p->ipopt_dst))
    842 		ip->ip_dst = p->ipopt_dst;
    843 	if (m->m_flags & M_EXT || m->m_data - optlen < m->m_pktdat) {
    844 		MGETHDR(n, M_DONTWAIT, MT_HEADER);
    845 		if (n == 0)
    846 			return (m);
    847 		n->m_pkthdr.len = m->m_pkthdr.len + optlen;
    848 		m->m_len -= sizeof(struct ip);
    849 		m->m_data += sizeof(struct ip);
    850 		n->m_next = m;
    851 		m = n;
    852 		m->m_len = optlen + sizeof(struct ip);
    853 		m->m_data += max_linkhdr;
    854 		bcopy((caddr_t)ip, mtod(m, caddr_t), sizeof(struct ip));
    855 	} else {
    856 		m->m_data -= optlen;
    857 		m->m_len += optlen;
    858 		m->m_pkthdr.len += optlen;
    859 		memmove(mtod(m, caddr_t), ip, sizeof(struct ip));
    860 	}
    861 	ip = mtod(m, struct ip *);
    862 	bcopy((caddr_t)p->ipopt_list, (caddr_t)(ip + 1), (unsigned)optlen);
    863 	*phlen = sizeof(struct ip) + optlen;
    864 	ip->ip_len += optlen;
    865 	return (m);
    866 }
    867 
    868 /*
    869  * Copy options from ip to jp,
    870  * omitting those not copied during fragmentation.
    871  */
    872 int
    873 ip_optcopy(ip, jp)
    874 	struct ip *ip, *jp;
    875 {
    876 	u_char *cp, *dp;
    877 	int opt, optlen, cnt;
    878 
    879 	cp = (u_char *)(ip + 1);
    880 	dp = (u_char *)(jp + 1);
    881 	cnt = (ip->ip_hl << 2) - sizeof (struct ip);
    882 	for (; cnt > 0; cnt -= optlen, cp += optlen) {
    883 		opt = cp[0];
    884 		if (opt == IPOPT_EOL)
    885 			break;
    886 		if (opt == IPOPT_NOP) {
    887 			/* Preserve for IP mcast tunnel's LSRR alignment. */
    888 			*dp++ = IPOPT_NOP;
    889 			optlen = 1;
    890 			continue;
    891 		}
    892 #ifdef DIAGNOSTIC
    893 		if (cnt < IPOPT_OLEN + sizeof(*cp))
    894 			panic("malformed IPv4 option passed to ip_optcopy");
    895 #endif
    896 		optlen = cp[IPOPT_OLEN];
    897 #ifdef DIAGNOSTIC
    898 		if (optlen < IPOPT_OLEN + sizeof(*cp) || optlen > cnt)
    899 			panic("malformed IPv4 option passed to ip_optcopy");
    900 #endif
    901 		/* bogus lengths should have been caught by ip_dooptions */
    902 		if (optlen > cnt)
    903 			optlen = cnt;
    904 		if (IPOPT_COPIED(opt)) {
    905 			bcopy((caddr_t)cp, (caddr_t)dp, (unsigned)optlen);
    906 			dp += optlen;
    907 		}
    908 	}
    909 	for (optlen = dp - (u_char *)(jp+1); optlen & 0x3; optlen++)
    910 		*dp++ = IPOPT_EOL;
    911 	return (optlen);
    912 }
    913 
    914 /*
    915  * IP socket option processing.
    916  */
    917 int
    918 ip_ctloutput(op, so, level, optname, mp)
    919 	int op;
    920 	struct socket *so;
    921 	int level, optname;
    922 	struct mbuf **mp;
    923 {
    924 	struct inpcb *inp = sotoinpcb(so);
    925 	struct mbuf *m = *mp;
    926 	int optval = 0;
    927 	int error = 0;
    928 #ifdef IPSEC
    929 #ifdef __NetBSD__
    930 	struct proc *p = (curproc ? curproc->l_proc : 0);	/*XXX*/
    931 #endif
    932 #endif
    933 
    934 	if (level != IPPROTO_IP) {
    935 		error = EINVAL;
    936 		if (op == PRCO_SETOPT && *mp)
    937 			(void) m_free(*mp);
    938 	} else switch (op) {
    939 
    940 	case PRCO_SETOPT:
    941 		switch (optname) {
    942 		case IP_OPTIONS:
    943 #ifdef notyet
    944 		case IP_RETOPTS:
    945 			return (ip_pcbopts(optname, &inp->inp_options, m));
    946 #else
    947 			return (ip_pcbopts(&inp->inp_options, m));
    948 #endif
    949 
    950 		case IP_TOS:
    951 		case IP_TTL:
    952 		case IP_RECVOPTS:
    953 		case IP_RECVRETOPTS:
    954 		case IP_RECVDSTADDR:
    955 		case IP_RECVIF:
    956 			if (m == NULL || m->m_len != sizeof(int))
    957 				error = EINVAL;
    958 			else {
    959 				optval = *mtod(m, int *);
    960 				switch (optname) {
    961 
    962 				case IP_TOS:
    963 					inp->inp_ip.ip_tos = optval;
    964 					break;
    965 
    966 				case IP_TTL:
    967 					inp->inp_ip.ip_ttl = optval;
    968 					break;
    969 #define	OPTSET(bit) \
    970 	if (optval) \
    971 		inp->inp_flags |= bit; \
    972 	else \
    973 		inp->inp_flags &= ~bit;
    974 
    975 				case IP_RECVOPTS:
    976 					OPTSET(INP_RECVOPTS);
    977 					break;
    978 
    979 				case IP_RECVRETOPTS:
    980 					OPTSET(INP_RECVRETOPTS);
    981 					break;
    982 
    983 				case IP_RECVDSTADDR:
    984 					OPTSET(INP_RECVDSTADDR);
    985 					break;
    986 
    987 				case IP_RECVIF:
    988 					OPTSET(INP_RECVIF);
    989 					break;
    990 				}
    991 			}
    992 			break;
    993 #undef OPTSET
    994 
    995 		case IP_MULTICAST_IF:
    996 		case IP_MULTICAST_TTL:
    997 		case IP_MULTICAST_LOOP:
    998 		case IP_ADD_MEMBERSHIP:
    999 		case IP_DROP_MEMBERSHIP:
   1000 			error = ip_setmoptions(optname, &inp->inp_moptions, m);
   1001 			break;
   1002 
   1003 		case IP_PORTRANGE:
   1004 			if (m == 0 || m->m_len != sizeof(int))
   1005 				error = EINVAL;
   1006 			else {
   1007 				optval = *mtod(m, int *);
   1008 
   1009 				switch (optval) {
   1010 
   1011 				case IP_PORTRANGE_DEFAULT:
   1012 				case IP_PORTRANGE_HIGH:
   1013 					inp->inp_flags &= ~(INP_LOWPORT);
   1014 					break;
   1015 
   1016 				case IP_PORTRANGE_LOW:
   1017 					inp->inp_flags |= INP_LOWPORT;
   1018 					break;
   1019 
   1020 				default:
   1021 					error = EINVAL;
   1022 					break;
   1023 				}
   1024 			}
   1025 			break;
   1026 
   1027 #ifdef IPSEC
   1028 		case IP_IPSEC_POLICY:
   1029 		{
   1030 			caddr_t req = NULL;
   1031 			size_t len = 0;
   1032 			int priv = 0;
   1033 
   1034 #ifdef __NetBSD__
   1035 			if (p == 0 || suser(p->p_ucred, &p->p_acflag))
   1036 				priv = 0;
   1037 			else
   1038 				priv = 1;
   1039 #else
   1040 			priv = (in6p->in6p_socket->so_state & SS_PRIV);
   1041 #endif
   1042 			if (m) {
   1043 				req = mtod(m, caddr_t);
   1044 				len = m->m_len;
   1045 			}
   1046 			error = ipsec4_set_policy(inp, optname, req, len, priv);
   1047 			break;
   1048 		    }
   1049 #endif /*IPSEC*/
   1050 
   1051 		default:
   1052 			error = ENOPROTOOPT;
   1053 			break;
   1054 		}
   1055 		if (m)
   1056 			(void)m_free(m);
   1057 		break;
   1058 
   1059 	case PRCO_GETOPT:
   1060 		switch (optname) {
   1061 		case IP_OPTIONS:
   1062 		case IP_RETOPTS:
   1063 			*mp = m = m_get(M_WAIT, MT_SOOPTS);
   1064 			if (inp->inp_options) {
   1065 				m->m_len = inp->inp_options->m_len;
   1066 				bcopy(mtod(inp->inp_options, caddr_t),
   1067 				    mtod(m, caddr_t), (unsigned)m->m_len);
   1068 			} else
   1069 				m->m_len = 0;
   1070 			break;
   1071 
   1072 		case IP_TOS:
   1073 		case IP_TTL:
   1074 		case IP_RECVOPTS:
   1075 		case IP_RECVRETOPTS:
   1076 		case IP_RECVDSTADDR:
   1077 		case IP_RECVIF:
   1078 		case IP_ERRORMTU:
   1079 			*mp = m = m_get(M_WAIT, MT_SOOPTS);
   1080 			m->m_len = sizeof(int);
   1081 			switch (optname) {
   1082 
   1083 			case IP_TOS:
   1084 				optval = inp->inp_ip.ip_tos;
   1085 				break;
   1086 
   1087 			case IP_TTL:
   1088 				optval = inp->inp_ip.ip_ttl;
   1089 				break;
   1090 
   1091 			case IP_ERRORMTU:
   1092 				optval = inp->inp_errormtu;
   1093 				break;
   1094 
   1095 #define	OPTBIT(bit)	(inp->inp_flags & bit ? 1 : 0)
   1096 
   1097 			case IP_RECVOPTS:
   1098 				optval = OPTBIT(INP_RECVOPTS);
   1099 				break;
   1100 
   1101 			case IP_RECVRETOPTS:
   1102 				optval = OPTBIT(INP_RECVRETOPTS);
   1103 				break;
   1104 
   1105 			case IP_RECVDSTADDR:
   1106 				optval = OPTBIT(INP_RECVDSTADDR);
   1107 				break;
   1108 
   1109 			case IP_RECVIF:
   1110 				optval = OPTBIT(INP_RECVIF);
   1111 				break;
   1112 			}
   1113 			*mtod(m, int *) = optval;
   1114 			break;
   1115 
   1116 #ifdef IPSEC
   1117 		case IP_IPSEC_POLICY:
   1118 		{
   1119 			caddr_t req = NULL;
   1120 			size_t len = 0;
   1121 
   1122 			if (m) {
   1123 				req = mtod(m, caddr_t);
   1124 				len = m->m_len;
   1125 			}
   1126 			error = ipsec4_get_policy(inp, req, len, mp);
   1127 			break;
   1128 		}
   1129 #endif /*IPSEC*/
   1130 
   1131 		case IP_MULTICAST_IF:
   1132 		case IP_MULTICAST_TTL:
   1133 		case IP_MULTICAST_LOOP:
   1134 		case IP_ADD_MEMBERSHIP:
   1135 		case IP_DROP_MEMBERSHIP:
   1136 			error = ip_getmoptions(optname, inp->inp_moptions, mp);
   1137 			break;
   1138 
   1139 		case IP_PORTRANGE:
   1140 			*mp = m = m_get(M_WAIT, MT_SOOPTS);
   1141 			m->m_len = sizeof(int);
   1142 
   1143 			if (inp->inp_flags & INP_LOWPORT)
   1144 				optval = IP_PORTRANGE_LOW;
   1145 			else
   1146 				optval = IP_PORTRANGE_DEFAULT;
   1147 
   1148 			*mtod(m, int *) = optval;
   1149 			break;
   1150 
   1151 		default:
   1152 			error = ENOPROTOOPT;
   1153 			break;
   1154 		}
   1155 		break;
   1156 	}
   1157 	return (error);
   1158 }
   1159 
   1160 /*
   1161  * Set up IP options in pcb for insertion in output packets.
   1162  * Store in mbuf with pointer in pcbopt, adding pseudo-option
   1163  * with destination address if source routed.
   1164  */
   1165 int
   1166 #ifdef notyet
   1167 ip_pcbopts(optname, pcbopt, m)
   1168 	int optname;
   1169 #else
   1170 ip_pcbopts(pcbopt, m)
   1171 #endif
   1172 	struct mbuf **pcbopt;
   1173 	struct mbuf *m;
   1174 {
   1175 	int cnt, optlen;
   1176 	u_char *cp;
   1177 	u_char opt;
   1178 
   1179 	/* turn off any old options */
   1180 	if (*pcbopt)
   1181 		(void)m_free(*pcbopt);
   1182 	*pcbopt = 0;
   1183 	if (m == (struct mbuf *)0 || m->m_len == 0) {
   1184 		/*
   1185 		 * Only turning off any previous options.
   1186 		 */
   1187 		if (m)
   1188 			(void)m_free(m);
   1189 		return (0);
   1190 	}
   1191 
   1192 #ifndef	__vax__
   1193 	if (m->m_len % sizeof(int32_t))
   1194 		goto bad;
   1195 #endif
   1196 	/*
   1197 	 * IP first-hop destination address will be stored before
   1198 	 * actual options; move other options back
   1199 	 * and clear it when none present.
   1200 	 */
   1201 	if (m->m_data + m->m_len + sizeof(struct in_addr) >= &m->m_dat[MLEN])
   1202 		goto bad;
   1203 	cnt = m->m_len;
   1204 	m->m_len += sizeof(struct in_addr);
   1205 	cp = mtod(m, u_char *) + sizeof(struct in_addr);
   1206 	memmove(cp, mtod(m, caddr_t), (unsigned)cnt);
   1207 	bzero(mtod(m, caddr_t), sizeof(struct in_addr));
   1208 
   1209 	for (; cnt > 0; cnt -= optlen, cp += optlen) {
   1210 		opt = cp[IPOPT_OPTVAL];
   1211 		if (opt == IPOPT_EOL)
   1212 			break;
   1213 		if (opt == IPOPT_NOP)
   1214 			optlen = 1;
   1215 		else {
   1216 			if (cnt < IPOPT_OLEN + sizeof(*cp))
   1217 				goto bad;
   1218 			optlen = cp[IPOPT_OLEN];
   1219 			if (optlen < IPOPT_OLEN  + sizeof(*cp) || optlen > cnt)
   1220 				goto bad;
   1221 		}
   1222 		switch (opt) {
   1223 
   1224 		default:
   1225 			break;
   1226 
   1227 		case IPOPT_LSRR:
   1228 		case IPOPT_SSRR:
   1229 			/*
   1230 			 * user process specifies route as:
   1231 			 *	->A->B->C->D
   1232 			 * D must be our final destination (but we can't
   1233 			 * check that since we may not have connected yet).
   1234 			 * A is first hop destination, which doesn't appear in
   1235 			 * actual IP option, but is stored before the options.
   1236 			 */
   1237 			if (optlen < IPOPT_MINOFF - 1 + sizeof(struct in_addr))
   1238 				goto bad;
   1239 			m->m_len -= sizeof(struct in_addr);
   1240 			cnt -= sizeof(struct in_addr);
   1241 			optlen -= sizeof(struct in_addr);
   1242 			cp[IPOPT_OLEN] = optlen;
   1243 			/*
   1244 			 * Move first hop before start of options.
   1245 			 */
   1246 			bcopy((caddr_t)&cp[IPOPT_OFFSET+1], mtod(m, caddr_t),
   1247 			    sizeof(struct in_addr));
   1248 			/*
   1249 			 * Then copy rest of options back
   1250 			 * to close up the deleted entry.
   1251 			 */
   1252 			memmove(&cp[IPOPT_OFFSET+1],
   1253                             (caddr_t)(&cp[IPOPT_OFFSET+1] + sizeof(struct in_addr)),
   1254 			    (unsigned)cnt + sizeof(struct in_addr));
   1255 			break;
   1256 		}
   1257 	}
   1258 	if (m->m_len > MAX_IPOPTLEN + sizeof(struct in_addr))
   1259 		goto bad;
   1260 	*pcbopt = m;
   1261 	return (0);
   1262 
   1263 bad:
   1264 	(void)m_free(m);
   1265 	return (EINVAL);
   1266 }
   1267 
   1268 /*
   1269  * following RFC1724 section 3.3, 0.0.0.0/8 is interpreted as interface index.
   1270  */
   1271 static struct ifnet *
   1272 ip_multicast_if(a, ifindexp)
   1273 	struct in_addr *a;
   1274 	int *ifindexp;
   1275 {
   1276 	int ifindex;
   1277 	struct ifnet *ifp;
   1278 
   1279 	if (ifindexp)
   1280 		*ifindexp = 0;
   1281 	if (ntohl(a->s_addr) >> 24 == 0) {
   1282 		ifindex = ntohl(a->s_addr) & 0xffffff;
   1283 		if (ifindex < 0 || if_index < ifindex)
   1284 			return NULL;
   1285 		ifp = ifindex2ifnet[ifindex];
   1286 		if (ifindexp)
   1287 			*ifindexp = ifindex;
   1288 	} else {
   1289 		INADDR_TO_IFP(*a, ifp);
   1290 	}
   1291 	return ifp;
   1292 }
   1293 
   1294 /*
   1295  * Set the IP multicast options in response to user setsockopt().
   1296  */
   1297 int
   1298 ip_setmoptions(optname, imop, m)
   1299 	int optname;
   1300 	struct ip_moptions **imop;
   1301 	struct mbuf *m;
   1302 {
   1303 	int error = 0;
   1304 	u_char loop;
   1305 	int i;
   1306 	struct in_addr addr;
   1307 	struct ip_mreq *mreq;
   1308 	struct ifnet *ifp;
   1309 	struct ip_moptions *imo = *imop;
   1310 	struct route ro;
   1311 	struct sockaddr_in *dst;
   1312 	int ifindex;
   1313 
   1314 	if (imo == NULL) {
   1315 		/*
   1316 		 * No multicast option buffer attached to the pcb;
   1317 		 * allocate one and initialize to default values.
   1318 		 */
   1319 		imo = (struct ip_moptions *)malloc(sizeof(*imo), M_IPMOPTS,
   1320 		    M_WAITOK);
   1321 
   1322 		if (imo == NULL)
   1323 			return (ENOBUFS);
   1324 		*imop = imo;
   1325 		imo->imo_multicast_ifp = NULL;
   1326 		imo->imo_multicast_addr.s_addr = INADDR_ANY;
   1327 		imo->imo_multicast_ttl = IP_DEFAULT_MULTICAST_TTL;
   1328 		imo->imo_multicast_loop = IP_DEFAULT_MULTICAST_LOOP;
   1329 		imo->imo_num_memberships = 0;
   1330 	}
   1331 
   1332 	switch (optname) {
   1333 
   1334 	case IP_MULTICAST_IF:
   1335 		/*
   1336 		 * Select the interface for outgoing multicast packets.
   1337 		 */
   1338 		if (m == NULL || m->m_len != sizeof(struct in_addr)) {
   1339 			error = EINVAL;
   1340 			break;
   1341 		}
   1342 		addr = *(mtod(m, struct in_addr *));
   1343 		/*
   1344 		 * INADDR_ANY is used to remove a previous selection.
   1345 		 * When no interface is selected, a default one is
   1346 		 * chosen every time a multicast packet is sent.
   1347 		 */
   1348 		if (in_nullhost(addr)) {
   1349 			imo->imo_multicast_ifp = NULL;
   1350 			break;
   1351 		}
   1352 		/*
   1353 		 * The selected interface is identified by its local
   1354 		 * IP address.  Find the interface and confirm that
   1355 		 * it supports multicasting.
   1356 		 */
   1357 		ifp = ip_multicast_if(&addr, &ifindex);
   1358 		if (ifp == NULL || (ifp->if_flags & IFF_MULTICAST) == 0) {
   1359 			error = EADDRNOTAVAIL;
   1360 			break;
   1361 		}
   1362 		imo->imo_multicast_ifp = ifp;
   1363 		if (ifindex)
   1364 			imo->imo_multicast_addr = addr;
   1365 		else
   1366 			imo->imo_multicast_addr.s_addr = INADDR_ANY;
   1367 		break;
   1368 
   1369 	case IP_MULTICAST_TTL:
   1370 		/*
   1371 		 * Set the IP time-to-live for outgoing multicast packets.
   1372 		 */
   1373 		if (m == NULL || m->m_len != 1) {
   1374 			error = EINVAL;
   1375 			break;
   1376 		}
   1377 		imo->imo_multicast_ttl = *(mtod(m, u_char *));
   1378 		break;
   1379 
   1380 	case IP_MULTICAST_LOOP:
   1381 		/*
   1382 		 * Set the loopback flag for outgoing multicast packets.
   1383 		 * Must be zero or one.
   1384 		 */
   1385 		if (m == NULL || m->m_len != 1 ||
   1386 		   (loop = *(mtod(m, u_char *))) > 1) {
   1387 			error = EINVAL;
   1388 			break;
   1389 		}
   1390 		imo->imo_multicast_loop = loop;
   1391 		break;
   1392 
   1393 	case IP_ADD_MEMBERSHIP:
   1394 		/*
   1395 		 * Add a multicast group membership.
   1396 		 * Group must be a valid IP multicast address.
   1397 		 */
   1398 		if (m == NULL || m->m_len != sizeof(struct ip_mreq)) {
   1399 			error = EINVAL;
   1400 			break;
   1401 		}
   1402 		mreq = mtod(m, struct ip_mreq *);
   1403 		if (!IN_MULTICAST(mreq->imr_multiaddr.s_addr)) {
   1404 			error = EINVAL;
   1405 			break;
   1406 		}
   1407 		/*
   1408 		 * If no interface address was provided, use the interface of
   1409 		 * the route to the given multicast address.
   1410 		 */
   1411 		if (in_nullhost(mreq->imr_interface)) {
   1412 			bzero((caddr_t)&ro, sizeof(ro));
   1413 			ro.ro_rt = NULL;
   1414 			dst = satosin(&ro.ro_dst);
   1415 			dst->sin_len = sizeof(*dst);
   1416 			dst->sin_family = AF_INET;
   1417 			dst->sin_addr = mreq->imr_multiaddr;
   1418 			rtalloc(&ro);
   1419 			if (ro.ro_rt == NULL) {
   1420 				error = EADDRNOTAVAIL;
   1421 				break;
   1422 			}
   1423 			ifp = ro.ro_rt->rt_ifp;
   1424 			rtfree(ro.ro_rt);
   1425 		} else {
   1426 			ifp = ip_multicast_if(&mreq->imr_interface, NULL);
   1427 		}
   1428 		/*
   1429 		 * See if we found an interface, and confirm that it
   1430 		 * supports multicast.
   1431 		 */
   1432 		if (ifp == NULL || (ifp->if_flags & IFF_MULTICAST) == 0) {
   1433 			error = EADDRNOTAVAIL;
   1434 			break;
   1435 		}
   1436 		/*
   1437 		 * See if the membership already exists or if all the
   1438 		 * membership slots are full.
   1439 		 */
   1440 		for (i = 0; i < imo->imo_num_memberships; ++i) {
   1441 			if (imo->imo_membership[i]->inm_ifp == ifp &&
   1442 			    in_hosteq(imo->imo_membership[i]->inm_addr,
   1443 				      mreq->imr_multiaddr))
   1444 				break;
   1445 		}
   1446 		if (i < imo->imo_num_memberships) {
   1447 			error = EADDRINUSE;
   1448 			break;
   1449 		}
   1450 		if (i == IP_MAX_MEMBERSHIPS) {
   1451 			error = ETOOMANYREFS;
   1452 			break;
   1453 		}
   1454 		/*
   1455 		 * Everything looks good; add a new record to the multicast
   1456 		 * address list for the given interface.
   1457 		 */
   1458 		if ((imo->imo_membership[i] =
   1459 		    in_addmulti(&mreq->imr_multiaddr, ifp)) == NULL) {
   1460 			error = ENOBUFS;
   1461 			break;
   1462 		}
   1463 		++imo->imo_num_memberships;
   1464 		break;
   1465 
   1466 	case IP_DROP_MEMBERSHIP:
   1467 		/*
   1468 		 * Drop a multicast group membership.
   1469 		 * Group must be a valid IP multicast address.
   1470 		 */
   1471 		if (m == NULL || m->m_len != sizeof(struct ip_mreq)) {
   1472 			error = EINVAL;
   1473 			break;
   1474 		}
   1475 		mreq = mtod(m, struct ip_mreq *);
   1476 		if (!IN_MULTICAST(mreq->imr_multiaddr.s_addr)) {
   1477 			error = EINVAL;
   1478 			break;
   1479 		}
   1480 		/*
   1481 		 * If an interface address was specified, get a pointer
   1482 		 * to its ifnet structure.
   1483 		 */
   1484 		if (in_nullhost(mreq->imr_interface))
   1485 			ifp = NULL;
   1486 		else {
   1487 			ifp = ip_multicast_if(&mreq->imr_interface, NULL);
   1488 			if (ifp == NULL) {
   1489 				error = EADDRNOTAVAIL;
   1490 				break;
   1491 			}
   1492 		}
   1493 		/*
   1494 		 * Find the membership in the membership array.
   1495 		 */
   1496 		for (i = 0; i < imo->imo_num_memberships; ++i) {
   1497 			if ((ifp == NULL ||
   1498 			     imo->imo_membership[i]->inm_ifp == ifp) &&
   1499 			     in_hosteq(imo->imo_membership[i]->inm_addr,
   1500 				       mreq->imr_multiaddr))
   1501 				break;
   1502 		}
   1503 		if (i == imo->imo_num_memberships) {
   1504 			error = EADDRNOTAVAIL;
   1505 			break;
   1506 		}
   1507 		/*
   1508 		 * Give up the multicast address record to which the
   1509 		 * membership points.
   1510 		 */
   1511 		in_delmulti(imo->imo_membership[i]);
   1512 		/*
   1513 		 * Remove the gap in the membership array.
   1514 		 */
   1515 		for (++i; i < imo->imo_num_memberships; ++i)
   1516 			imo->imo_membership[i-1] = imo->imo_membership[i];
   1517 		--imo->imo_num_memberships;
   1518 		break;
   1519 
   1520 	default:
   1521 		error = EOPNOTSUPP;
   1522 		break;
   1523 	}
   1524 
   1525 	/*
   1526 	 * If all options have default values, no need to keep the mbuf.
   1527 	 */
   1528 	if (imo->imo_multicast_ifp == NULL &&
   1529 	    imo->imo_multicast_ttl == IP_DEFAULT_MULTICAST_TTL &&
   1530 	    imo->imo_multicast_loop == IP_DEFAULT_MULTICAST_LOOP &&
   1531 	    imo->imo_num_memberships == 0) {
   1532 		free(*imop, M_IPMOPTS);
   1533 		*imop = NULL;
   1534 	}
   1535 
   1536 	return (error);
   1537 }
   1538 
   1539 /*
   1540  * Return the IP multicast options in response to user getsockopt().
   1541  */
   1542 int
   1543 ip_getmoptions(optname, imo, mp)
   1544 	int optname;
   1545 	struct ip_moptions *imo;
   1546 	struct mbuf **mp;
   1547 {
   1548 	u_char *ttl;
   1549 	u_char *loop;
   1550 	struct in_addr *addr;
   1551 	struct in_ifaddr *ia;
   1552 
   1553 	*mp = m_get(M_WAIT, MT_SOOPTS);
   1554 
   1555 	switch (optname) {
   1556 
   1557 	case IP_MULTICAST_IF:
   1558 		addr = mtod(*mp, struct in_addr *);
   1559 		(*mp)->m_len = sizeof(struct in_addr);
   1560 		if (imo == NULL || imo->imo_multicast_ifp == NULL)
   1561 			*addr = zeroin_addr;
   1562 		else if (imo->imo_multicast_addr.s_addr) {
   1563 			/* return the value user has set */
   1564 			*addr = imo->imo_multicast_addr;
   1565 		} else {
   1566 			IFP_TO_IA(imo->imo_multicast_ifp, ia);
   1567 			*addr = ia ? ia->ia_addr.sin_addr : zeroin_addr;
   1568 		}
   1569 		return (0);
   1570 
   1571 	case IP_MULTICAST_TTL:
   1572 		ttl = mtod(*mp, u_char *);
   1573 		(*mp)->m_len = 1;
   1574 		*ttl = imo ? imo->imo_multicast_ttl
   1575 			   : IP_DEFAULT_MULTICAST_TTL;
   1576 		return (0);
   1577 
   1578 	case IP_MULTICAST_LOOP:
   1579 		loop = mtod(*mp, u_char *);
   1580 		(*mp)->m_len = 1;
   1581 		*loop = imo ? imo->imo_multicast_loop
   1582 			    : IP_DEFAULT_MULTICAST_LOOP;
   1583 		return (0);
   1584 
   1585 	default:
   1586 		return (EOPNOTSUPP);
   1587 	}
   1588 }
   1589 
   1590 /*
   1591  * Discard the IP multicast options.
   1592  */
   1593 void
   1594 ip_freemoptions(imo)
   1595 	struct ip_moptions *imo;
   1596 {
   1597 	int i;
   1598 
   1599 	if (imo != NULL) {
   1600 		for (i = 0; i < imo->imo_num_memberships; ++i)
   1601 			in_delmulti(imo->imo_membership[i]);
   1602 		free(imo, M_IPMOPTS);
   1603 	}
   1604 }
   1605 
   1606 /*
   1607  * Routine called from ip_output() to loop back a copy of an IP multicast
   1608  * packet to the input queue of a specified interface.  Note that this
   1609  * calls the output routine of the loopback "driver", but with an interface
   1610  * pointer that might NOT be &loif -- easier than replicating that code here.
   1611  */
   1612 static void
   1613 ip_mloopback(ifp, m, dst)
   1614 	struct ifnet *ifp;
   1615 	struct mbuf *m;
   1616 	struct sockaddr_in *dst;
   1617 {
   1618 	struct ip *ip;
   1619 	struct mbuf *copym;
   1620 
   1621 	copym = m_copy(m, 0, M_COPYALL);
   1622 	if (copym != NULL
   1623 	 && (copym->m_flags & M_EXT || copym->m_len < sizeof(struct ip)))
   1624 		copym = m_pullup(copym, sizeof(struct ip));
   1625 	if (copym != NULL) {
   1626 		/*
   1627 		 * We don't bother to fragment if the IP length is greater
   1628 		 * than the interface's MTU.  Can this possibly matter?
   1629 		 */
   1630 		ip = mtod(copym, struct ip *);
   1631 		HTONS(ip->ip_len);
   1632 		HTONS(ip->ip_off);
   1633 		ip->ip_sum = 0;
   1634 		ip->ip_sum = in_cksum(copym, ip->ip_hl << 2);
   1635 		(void) looutput(ifp, copym, sintosa(dst), NULL);
   1636 	}
   1637 }
   1638