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