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