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