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