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