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