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