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